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).
69 #include <openssl/opensslconf.h>
70 #include <openssl/crypto.h>
71 #include <openssl/dso.h>
72 #include <openssl/engine.h>
73 #include <openssl/evp.h>
74 #ifndef OPENSSL_NO_AES
75 #include <openssl/aes.h>
77 #include <openssl/rand.h>
78 #include <openssl/err.h>
81 #ifndef OPENSSL_NO_HW_PADLOCK
83 /* Attempt to have a single source for both 0.9.7 and 0.9.8 :-) */
84 #if (OPENSSL_VERSION_NUMBER >= 0x00908000L)
85 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
86 # define DYNAMIC_ENGINE
88 #elif (OPENSSL_VERSION_NUMBER >= 0x00907000L)
89 # ifdef ENGINE_DYNAMIC_SUPPORT
90 # define DYNAMIC_ENGINE
93 # error "Only OpenSSL >= 0.9.7 is supported"
96 /* VIA PadLock AES is available *ONLY* on some x86 CPUs.
97 Not only that it doesn't exist elsewhere, but it
98 even can't be compiled on other platforms!
100 In addition, because of the heavy use of inline assembler,
101 compiler choice 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__) && __GNUC__>=2 && \
105 (defined(__i386__) || defined(__i386) || \
106 defined(__x86_64__) || defined(__x86_64)) \
108 (defined(_MSC_VER) && defined(_M_IX86))
109 # define COMPILE_HW_PADLOCK
110 # ifdef OPENSSL_NO_DYNAMIC_ENGINE
111 static ENGINE *ENGINE_padlock (void);
116 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
118 void ENGINE_load_padlock (void)
120 /* On non-x86 CPUs it just returns. */
121 #ifdef COMPILE_HW_PADLOCK
122 ENGINE *toadd = ENGINE_padlock ();
132 #ifdef COMPILE_HW_PADLOCK
133 /* We do these includes here to avoid header problems on platforms that
134 do not have the VIA padlock anyway... */
139 # define alloca _alloca
141 #elif defined(__GNUC__)
143 # define alloca(s) __builtin_alloca((s))
147 /* Function for ENGINE detection and control */
148 static int padlock_available(void);
149 static int padlock_init(ENGINE *e);
152 static RAND_METHOD padlock_rand;
155 #ifndef OPENSSL_NO_AES
156 static int padlock_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid);
160 static const char *padlock_id = "padlock";
161 static char padlock_name[100];
163 /* Available features */
164 static int padlock_use_ace = 0; /* Advanced Cryptography Engine */
165 static int padlock_use_rng = 0; /* Random Number Generator */
166 #ifndef OPENSSL_NO_AES
167 static int padlock_aes_align_required = 1;
170 /* ===== Engine "management" functions ===== */
172 /* Prepare the ENGINE structure for registration */
174 padlock_bind_helper(ENGINE *e)
176 /* Check available features */
179 #if 1 /* disable RNG for now, see commentary in vicinity of RNG code */
183 /* Generate a nice engine name with available features */
184 BIO_snprintf(padlock_name, sizeof(padlock_name),
185 "VIA PadLock (%s, %s)",
186 padlock_use_rng ? "RNG" : "no-RNG",
187 padlock_use_ace ? "ACE" : "no-ACE");
189 /* Register everything or return with an error */
190 if (!ENGINE_set_id(e, padlock_id) ||
191 !ENGINE_set_name(e, padlock_name) ||
193 !ENGINE_set_init_function(e, padlock_init) ||
194 #ifndef OPENSSL_NO_AES
195 (padlock_use_ace && !ENGINE_set_ciphers (e, padlock_ciphers)) ||
197 (padlock_use_rng && !ENGINE_set_RAND (e, &padlock_rand))) {
201 /* Everything looks good */
205 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
210 ENGINE *eng = ENGINE_new();
216 if (!padlock_bind_helper(eng)) {
225 /* Check availability of the engine */
227 padlock_init(ENGINE *e)
229 return (padlock_use_rng || padlock_use_ace);
232 /* This stuff is needed if this ENGINE is being compiled into a self-contained
235 #ifdef DYNAMIC_ENGINE
237 padlock_bind_fn(ENGINE *e, const char *id)
239 if (id && (strcmp(id, padlock_id) != 0)) {
243 if (!padlock_bind_helper(e)) {
250 IMPLEMENT_DYNAMIC_CHECK_FN()
251 IMPLEMENT_DYNAMIC_BIND_FN (padlock_bind_fn)
252 #endif /* DYNAMIC_ENGINE */
254 /* ===== Here comes the "real" engine ===== */
256 #ifndef OPENSSL_NO_AES
257 /* Some AES-related constants */
258 #define AES_BLOCK_SIZE 16
259 #define AES_KEY_SIZE_128 16
260 #define AES_KEY_SIZE_192 24
261 #define AES_KEY_SIZE_256 32
263 /* Here we store the status information relevant to the
266 * Inline assembler in PADLOCK_XCRYPT_ASM()
267 * depends on the order of items in this structure.
268 * Don't blindly modify, reorder, etc!
270 struct padlock_cipher_data
272 unsigned char iv[AES_BLOCK_SIZE]; /* Initialization vector */
273 union { unsigned int pad[4];
276 int dgst:1; /* n/a in C3 */
277 int align:1; /* n/a in C3 */
278 int ciphr:1; /* n/a in C3 */
279 unsigned int keygen:1;
281 unsigned int encdec:1;
284 } cword; /* Control word */
285 AES_KEY ks; /* Encryption key */
289 * Essentially this variable belongs in thread local storage.
290 * Having this variable global on the other hand can only cause
291 * few bogus key reloads [if any at all on single-CPU system],
292 * so we accept the penatly...
294 static volatile struct padlock_cipher_data *padlock_saved_context;
298 * =======================================================
299 * Inline assembler section(s).
300 * =======================================================
301 * Order of arguments is chosen to facilitate Windows port
302 * using __fastcall calling convention. If you wish to add
303 * more routines, keep in mind that first __fastcall
304 * argument is passed in %ecx and second - in %edx.
305 * =======================================================
307 #if defined(__GNUC__) && __GNUC__>=2
308 #if defined(__i386__) || defined(__i386)
310 * As for excessive "push %ebx"/"pop %ebx" found all over.
311 * When generating position-independent code GCC won't let
312 * us use "b" in assembler templates nor even respect "ebx"
313 * in "clobber description." Therefore the trouble...
316 /* Helper function - check if a CPUID instruction
317 is available on this CPU */
319 padlock_insn_cpuid_available(void)
323 /* We're checking if the bit #21 of EFLAGS
324 can be toggled. If yes = CPUID is available. */
328 "xorl $0x200000, %%eax\n"
329 "movl %%eax, %%ecx\n"
330 "andl $0x200000, %%ecx\n"
335 "andl $0x200000, %%eax\n"
336 "xorl %%eax, %%ecx\n"
338 : "=r" (result) : : "eax", "ecx");
340 return (result == 0);
343 /* Load supported features of the CPU to see if
344 the PadLock is available. */
346 padlock_available(void)
348 char vendor_string[16];
349 unsigned int eax, edx;
351 /* First check if the CPUID instruction is available at all... */
352 if (! padlock_insn_cpuid_available())
355 /* Are we running on the Centaur (VIA) CPU? */
357 vendor_string[12] = 0;
361 "movl %%ebx,(%%edi)\n"
362 "movl %%edx,4(%%edi)\n"
363 "movl %%ecx,8(%%edi)\n"
365 : "+a"(eax) : "D"(vendor_string) : "ecx", "edx");
366 if (strcmp(vendor_string, "CentaurHauls") != 0)
369 /* Check for Centaur Extended Feature Flags presence */
371 asm volatile ("pushl %%ebx; cpuid; popl %%ebx"
372 : "+a"(eax) : : "ecx", "edx");
373 if (eax < 0xC0000001)
376 /* Read the Centaur Extended Feature Flags */
378 asm volatile ("pushl %%ebx; cpuid; popl %%ebx"
379 : "+a"(eax), "=d"(edx) : : "ecx");
381 /* Fill up some flags */
382 padlock_use_ace = ((edx & (0x3<<6)) == (0x3<<6));
383 padlock_use_rng = ((edx & (0x3<<2)) == (0x3<<2));
385 return padlock_use_ace + padlock_use_rng;
388 /* Force key reload from memory to the CPU microcode.
389 Loading EFLAGS from the stack clears EFLAGS[30]
390 which does the trick. */
392 padlock_reload_key(void)
394 asm volatile ("pushfl; popfl");
397 #ifndef OPENSSL_NO_AES
399 * This is heuristic key context tracing. At first one
400 * believes that one should use atomic swap instructions,
401 * but it's not actually necessary. Point is that if
402 * padlock_saved_context was changed by another thread
403 * after we've read it and before we compare it with cdata,
404 * our key *shall* be reloaded upon thread context switch
405 * and we are therefore set in either case...
408 padlock_verify_context(struct padlock_cipher_data *cdata)
420 :"+m"(padlock_saved_context)
421 : "r"(padlock_saved_context), "r"(cdata) : "cc");
424 /* Template for padlock_xcrypt_* modes */
426 * The offsets used with 'leal' instructions
427 * describe items of the 'padlock_cipher_data'
430 #define PADLOCK_XCRYPT_ASM(name,rep_xcrypt) \
431 static inline void *name(size_t cnt, \
432 struct padlock_cipher_data *cdata, \
433 void *out, const void *inp) \
435 asm volatile ( "pushl %%ebx\n" \
436 " leal 16(%0),%%edx\n" \
437 " leal 32(%0),%%ebx\n" \
440 : "=a"(iv), "=c"(cnt), "=D"(out), "=S"(inp) \
441 : "0"(cdata), "1"(cnt), "2"(out), "3"(inp) \
442 : "edx", "cc", "memory"); \
447 #elif defined(__x86_64__) || defined(__x86_64)
449 /* Load supported features of the CPU to see if
450 the PadLock is available. */
452 padlock_available(void)
454 char vendor_string[16];
455 unsigned int eax, edx;
457 /* Are we running on the Centaur (VIA) CPU? */
459 vendor_string[12] = 0;
467 : "+a"(eax) : "r"(vendor_string) : "rcx", "rdx");
468 if (strcmp(vendor_string, "CentaurHauls") != 0)
471 /* Check for Centaur Extended Feature Flags presence */
473 asm volatile ("pushq %%rbx; cpuid; popq %%rbx"
474 : "+a"(eax) : : "rcx", "rdx");
475 if (eax < 0xC0000001)
478 /* Read the Centaur Extended Feature Flags */
480 asm volatile ("pushq %%rbx; cpuid; popq %%rbx"
481 : "+a"(eax), "=d"(edx) : : "rcx");
483 /* Fill up some flags */
484 padlock_use_ace = ((edx & (0x3<<6)) == (0x3<<6));
485 padlock_use_rng = ((edx & (0x3<<2)) == (0x3<<2));
487 return padlock_use_ace + padlock_use_rng;
490 /* Force key reload from memory to the CPU microcode.
491 Loading EFLAGS from the stack clears EFLAGS[30]
492 which does the trick. */
494 padlock_reload_key(void)
496 asm volatile ("pushfq; popfq");
499 #ifndef OPENSSL_NO_AES
501 * This is heuristic key context tracing. At first one
502 * believes that one should use atomic swap instructions,
503 * but it's not actually necessary. Point is that if
504 * padlock_saved_context was changed by another thread
505 * after we've read it and before we compare it with cdata,
506 * our key *shall* be reloaded upon thread context switch
507 * and we are therefore set in either case...
510 padlock_verify_context(struct padlock_cipher_data *cdata)
522 :"+m"(padlock_saved_context)
523 : "r"(padlock_saved_context), "r"(cdata) : "cc");
526 /* Template for padlock_xcrypt_* modes */
528 * The offsets used with 'leal' instructions
529 * describe items of the 'padlock_cipher_data'
532 #define PADLOCK_XCRYPT_ASM(name,rep_xcrypt) \
533 static inline void *name(size_t cnt, \
534 struct padlock_cipher_data *cdata, \
535 void *out, const void *inp) \
537 asm volatile ( "pushq %%rbx\n" \
538 " leaq 16(%0),%%rdx\n" \
539 " leaq 32(%0),%%rbx\n" \
542 : "=a"(iv), "=c"(cnt), "=D"(out), "=S"(inp) \
543 : "0"(cdata), "1"(cnt), "2"(out), "3"(inp) \
544 : "rdx", "cc", "memory"); \
551 #ifndef OPENSSL_NO_AES
552 /* Generate all functions with appropriate opcodes */
553 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ecb, ".byte 0xf3,0x0f,0xa7,0xc8") /* rep xcryptecb */
554 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cbc, ".byte 0xf3,0x0f,0xa7,0xd0") /* rep xcryptcbc */
555 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cfb, ".byte 0xf3,0x0f,0xa7,0xe0") /* rep xcryptcfb */
556 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ofb, ".byte 0xf3,0x0f,0xa7,0xe8") /* rep xcryptofb */
558 /* Our own htonl()/ntohl() */
560 padlock_bswapl(AES_KEY *ks)
562 size_t i = sizeof(ks->rd_key)/sizeof(ks->rd_key[0]);
563 unsigned int *key = ks->rd_key;
566 asm volatile ("bswapl %0" : "+r"(*key));
572 /* The RNG call itself */
573 static inline unsigned int
574 padlock_xstore(void *addr, unsigned int edx_in)
576 unsigned int eax_out;
578 asm volatile (".byte 0x0f,0xa7,0xc0" /* xstore */
579 : "=a"(eax_out),"=m"(*(unsigned *)addr)
580 : "D"(addr), "d" (edx_in)
586 /* Why not inline 'rep movsd'? I failed to find information on what
587 * value in Direction Flag one can expect and consequently have to
588 * apply "better-safe-than-sorry" approach and assume "undefined."
589 * I could explicitly clear it and restore the original value upon
590 * return from padlock_aes_cipher, but it's presumably too much
591 * trouble for too little gain...
593 * In case you wonder 'rep xcrypt*' instructions above are *not*
594 * affected by the Direction Flag and pointers advance toward
595 * larger addresses unconditionally.
597 static inline unsigned char *
598 padlock_memcpy(void *dst,const void *src,size_t n)
604 do { *d++ = *s++; } while (--n);
609 #elif defined(_MSC_VER)
611 * Unlike GCC these are real functions. In order to minimize impact
612 * on performance we adhere to __fastcall calling convention in
613 * order to get two first arguments passed through %ecx and %edx.
614 * Which kind of suits very well, as instructions in question use
615 * both %ecx and %edx as input:-)
617 #define REP_XCRYPT(code) \
619 _asm _emit 0x0f _asm _emit 0xa7 \
623 * The offsets used with 'lea' instructions
624 * describe items of the 'padlock_cipher_data'
627 #define PADLOCK_XCRYPT_ASM(name,code) \
628 static void * __fastcall \
629 name (size_t cnt, void *cdata, \
630 void *outp, const void *inp) \
632 _asm lea edx,[eax+16] \
633 _asm lea ebx,[eax+32] \
639 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ecb,0xc8)
640 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cbc,0xd0)
641 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cfb,0xe0)
642 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ofb,0xe8)
644 static int __fastcall
645 padlock_xstore(void *outp,unsigned int code)
647 _asm _emit 0x0f _asm _emit 0xa7 _asm _emit 0xc0
650 static void __fastcall
651 padlock_reload_key(void)
652 { _asm pushfd _asm popfd }
654 static void __fastcall
655 padlock_verify_context(void *cdata)
660 cmp ecx,padlock_saved_context
665 mov padlock_saved_context,ecx
670 padlock_available(void)
705 mov padlock_use_ace,1
711 mov padlock_use_rng,1
718 static void __fastcall
719 padlock_bswapl(void *key)
734 /* MS actually specifies status of Direction Flag and compiler even
735 * manages to compile following as 'rep movsd' all by itself...
737 #define padlock_memcpy(o,i,n) ((unsigned char *)memcpy((o),(i),(n)&~3U))
740 /* ===== AES encryption/decryption ===== */
741 #ifndef OPENSSL_NO_AES
743 #if defined(NID_aes_128_cfb128) && ! defined (NID_aes_128_cfb)
744 #define NID_aes_128_cfb NID_aes_128_cfb128
747 #if defined(NID_aes_128_ofb128) && ! defined (NID_aes_128_ofb)
748 #define NID_aes_128_ofb NID_aes_128_ofb128
751 #if defined(NID_aes_192_cfb128) && ! defined (NID_aes_192_cfb)
752 #define NID_aes_192_cfb NID_aes_192_cfb128
755 #if defined(NID_aes_192_ofb128) && ! defined (NID_aes_192_ofb)
756 #define NID_aes_192_ofb NID_aes_192_ofb128
759 #if defined(NID_aes_256_cfb128) && ! defined (NID_aes_256_cfb)
760 #define NID_aes_256_cfb NID_aes_256_cfb128
763 #if defined(NID_aes_256_ofb128) && ! defined (NID_aes_256_ofb)
764 #define NID_aes_256_ofb NID_aes_256_ofb128
767 /* List of supported ciphers. */
768 static int padlock_cipher_nids[] = {
784 static int padlock_cipher_nids_num = (sizeof(padlock_cipher_nids)/
785 sizeof(padlock_cipher_nids[0]));
787 /* Function prototypes ... */
788 static int padlock_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
789 const unsigned char *iv, int enc);
790 static int padlock_aes_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
791 const unsigned char *in, size_t nbytes);
793 #define NEAREST_ALIGNED(ptr) ( (unsigned char *)(ptr) + \
794 ( (0x10 - ((size_t)(ptr) & 0x0F)) & 0x0F ) )
795 #define ALIGNED_CIPHER_DATA(ctx) ((struct padlock_cipher_data *)\
796 NEAREST_ALIGNED(ctx->cipher_data))
798 #define EVP_CIPHER_block_size_ECB AES_BLOCK_SIZE
799 #define EVP_CIPHER_block_size_CBC AES_BLOCK_SIZE
800 #define EVP_CIPHER_block_size_OFB 1
801 #define EVP_CIPHER_block_size_CFB 1
803 /* Declaring so many ciphers by hand would be a pain.
804 Instead introduce a bit of preprocessor magic :-) */
805 #define DECLARE_AES_EVP(ksize,lmode,umode) \
806 static const EVP_CIPHER padlock_aes_##ksize##_##lmode = { \
807 NID_aes_##ksize##_##lmode, \
808 EVP_CIPHER_block_size_##umode, \
809 AES_KEY_SIZE_##ksize, \
811 0 | EVP_CIPH_##umode##_MODE, \
812 padlock_aes_init_key, \
813 padlock_aes_cipher, \
815 sizeof(struct padlock_cipher_data) + 16, \
816 EVP_CIPHER_set_asn1_iv, \
817 EVP_CIPHER_get_asn1_iv, \
822 DECLARE_AES_EVP(128,ecb,ECB);
823 DECLARE_AES_EVP(128,cbc,CBC);
824 DECLARE_AES_EVP(128,cfb,CFB);
825 DECLARE_AES_EVP(128,ofb,OFB);
827 DECLARE_AES_EVP(192,ecb,ECB);
828 DECLARE_AES_EVP(192,cbc,CBC);
829 DECLARE_AES_EVP(192,cfb,CFB);
830 DECLARE_AES_EVP(192,ofb,OFB);
832 DECLARE_AES_EVP(256,ecb,ECB);
833 DECLARE_AES_EVP(256,cbc,CBC);
834 DECLARE_AES_EVP(256,cfb,CFB);
835 DECLARE_AES_EVP(256,ofb,OFB);
838 padlock_ciphers (ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid)
840 /* No specific cipher => return a list of supported nids ... */
842 *nids = padlock_cipher_nids;
843 return padlock_cipher_nids_num;
846 /* ... or the requested "cipher" otherwise */
848 case NID_aes_128_ecb:
849 *cipher = &padlock_aes_128_ecb;
851 case NID_aes_128_cbc:
852 *cipher = &padlock_aes_128_cbc;
854 case NID_aes_128_cfb:
855 *cipher = &padlock_aes_128_cfb;
857 case NID_aes_128_ofb:
858 *cipher = &padlock_aes_128_ofb;
861 case NID_aes_192_ecb:
862 *cipher = &padlock_aes_192_ecb;
864 case NID_aes_192_cbc:
865 *cipher = &padlock_aes_192_cbc;
867 case NID_aes_192_cfb:
868 *cipher = &padlock_aes_192_cfb;
870 case NID_aes_192_ofb:
871 *cipher = &padlock_aes_192_ofb;
874 case NID_aes_256_ecb:
875 *cipher = &padlock_aes_256_ecb;
877 case NID_aes_256_cbc:
878 *cipher = &padlock_aes_256_cbc;
880 case NID_aes_256_cfb:
881 *cipher = &padlock_aes_256_cfb;
883 case NID_aes_256_ofb:
884 *cipher = &padlock_aes_256_ofb;
888 /* Sorry, we don't support this NID */
896 /* Prepare the encryption key for PadLock usage */
898 padlock_aes_init_key (EVP_CIPHER_CTX *ctx, const unsigned char *key,
899 const unsigned char *iv, int enc)
901 struct padlock_cipher_data *cdata;
902 int key_len = EVP_CIPHER_CTX_key_length(ctx) * 8;
904 if (key==NULL) return 0; /* ERROR */
906 cdata = ALIGNED_CIPHER_DATA(ctx);
907 memset(cdata, 0, sizeof(struct padlock_cipher_data));
909 /* Prepare Control word. */
910 if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_OFB_MODE)
911 cdata->cword.b.encdec = 0;
913 cdata->cword.b.encdec = (ctx->encrypt == 0);
914 cdata->cword.b.rounds = 10 + (key_len - 128) / 32;
915 cdata->cword.b.ksize = (key_len - 128) / 64;
919 /* PadLock can generate an extended key for
920 AES128 in hardware */
921 memcpy(cdata->ks.rd_key, key, AES_KEY_SIZE_128);
922 cdata->cword.b.keygen = 0;
927 /* Generate an extended AES key in software.
928 Needed for AES192/AES256 */
929 /* Well, the above applies to Stepping 8 CPUs
930 and is listed as hardware errata. They most
931 likely will fix it at some point and then
932 a check for stepping would be due here. */
933 if (EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_CFB_MODE ||
934 EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_OFB_MODE ||
936 AES_set_encrypt_key(key, key_len, &cdata->ks);
938 AES_set_decrypt_key(key, key_len, &cdata->ks);
940 /* OpenSSL C functions use byte-swapped extended key. */
941 padlock_bswapl(&cdata->ks);
943 cdata->cword.b.keygen = 1;
952 * This is done to cover for cases when user reuses the
953 * context for new key. The catch is that if we don't do
954 * this, padlock_eas_cipher might proceed with old key...
956 padlock_reload_key ();
962 * Simplified version of padlock_aes_cipher() used when
963 * 1) both input and output buffers are at aligned addresses.
965 * 2) running on a newer CPU that doesn't require aligned buffers.
968 padlock_aes_cipher_omnivorous(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
969 const unsigned char *in_arg, size_t nbytes)
971 struct padlock_cipher_data *cdata;
974 cdata = ALIGNED_CIPHER_DATA(ctx);
975 padlock_verify_context(cdata);
977 switch (EVP_CIPHER_CTX_mode(ctx)) {
978 case EVP_CIPH_ECB_MODE:
979 padlock_xcrypt_ecb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg);
982 case EVP_CIPH_CBC_MODE:
983 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
984 iv = padlock_xcrypt_cbc(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg);
985 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
988 case EVP_CIPH_CFB_MODE:
989 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
990 iv = padlock_xcrypt_cfb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg);
991 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
994 case EVP_CIPH_OFB_MODE:
995 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
996 padlock_xcrypt_ofb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg);
997 memcpy(ctx->iv, cdata->iv, AES_BLOCK_SIZE);
1004 memset(cdata->iv, 0, AES_BLOCK_SIZE);
1009 #ifndef PADLOCK_CHUNK
1010 # define PADLOCK_CHUNK 512 /* Must be a power of 2 larger than 16 */
1012 #if PADLOCK_CHUNK<16 || PADLOCK_CHUNK&(PADLOCK_CHUNK-1)
1013 # error "insane PADLOCK_CHUNK..."
1016 /* Re-align the arguments to 16-Bytes boundaries and run the
1017 encryption function itself. This function is not AES-specific. */
1019 padlock_aes_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
1020 const unsigned char *in_arg, size_t nbytes)
1022 struct padlock_cipher_data *cdata;
1026 int inp_misaligned, out_misaligned, realign_in_loop;
1027 size_t chunk, allocated=0;
1029 /* ctx->num is maintained in byte-oriented modes,
1030 such as CFB and OFB... */
1031 if ((chunk = ctx->num)) { /* borrow chunk variable */
1032 unsigned char *ivp=ctx->iv;
1034 switch (EVP_CIPHER_CTX_mode(ctx)) {
1035 case EVP_CIPH_CFB_MODE:
1036 if (chunk >= AES_BLOCK_SIZE)
1037 return 0; /* bogus value */
1040 while (chunk<AES_BLOCK_SIZE && nbytes!=0) {
1041 ivp[chunk] = *(out_arg++) = *(in_arg++) ^ ivp[chunk];
1044 else while (chunk<AES_BLOCK_SIZE && nbytes!=0) {
1045 unsigned char c = *(in_arg++);
1046 *(out_arg++) = c ^ ivp[chunk];
1047 ivp[chunk++] = c, nbytes--;
1050 ctx->num = chunk%AES_BLOCK_SIZE;
1052 case EVP_CIPH_OFB_MODE:
1053 if (chunk >= AES_BLOCK_SIZE)
1054 return 0; /* bogus value */
1056 while (chunk<AES_BLOCK_SIZE && nbytes!=0) {
1057 *(out_arg++) = *(in_arg++) ^ ivp[chunk];
1061 ctx->num = chunk%AES_BLOCK_SIZE;
1069 if (nbytes % AES_BLOCK_SIZE)
1070 return 0; /* are we expected to do tail processing? */
1072 /* nbytes is always multiple of AES_BLOCK_SIZE in ECB and CBC
1073 modes and arbitrary value in byte-oriented modes, such as
1077 /* VIA promises CPUs that won't require alignment in the future.
1078 For now padlock_aes_align_required is initialized to 1 and
1079 the condition is never met... */
1080 /* C7 core is capable to manage unaligned input in non-ECB[!]
1081 mode, but performance penalties appear to be approximately
1082 same as for software alignment below or ~3x. They promise to
1083 improve it in the future, but for now we can just as well
1084 pretend that it can only handle aligned input... */
1085 if (!padlock_aes_align_required && (nbytes%AES_BLOCK_SIZE)==0)
1086 return padlock_aes_cipher_omnivorous(ctx, out_arg, in_arg, nbytes);
1088 inp_misaligned = (((size_t)in_arg) & 0x0F);
1089 out_misaligned = (((size_t)out_arg) & 0x0F);
1091 /* Note that even if output is aligned and input not,
1092 * I still prefer to loop instead of copy the whole
1093 * input and then encrypt in one stroke. This is done
1094 * in order to improve L1 cache utilization... */
1095 realign_in_loop = out_misaligned|inp_misaligned;
1097 if (!realign_in_loop && (nbytes%AES_BLOCK_SIZE)==0)
1098 return padlock_aes_cipher_omnivorous(ctx, out_arg, in_arg, nbytes);
1100 /* this takes one "if" out of the loops */
1102 chunk %= PADLOCK_CHUNK;
1103 if (chunk==0) chunk = PADLOCK_CHUNK;
1105 if (out_misaligned) {
1106 /* optmize for small input */
1107 allocated = (chunk<nbytes?PADLOCK_CHUNK:nbytes);
1108 out = alloca(0x10 + allocated);
1109 out = NEAREST_ALIGNED(out);
1114 cdata = ALIGNED_CIPHER_DATA(ctx);
1115 padlock_verify_context(cdata);
1117 switch (EVP_CIPHER_CTX_mode(ctx)) {
1118 case EVP_CIPH_ECB_MODE:
1121 inp = padlock_memcpy(out, in_arg, chunk);
1126 padlock_xcrypt_ecb(chunk/AES_BLOCK_SIZE, cdata, out, inp);
1129 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1131 out = out_arg+=chunk;
1134 chunk = PADLOCK_CHUNK;
1138 case EVP_CIPH_CBC_MODE:
1139 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
1142 if (iv != cdata->iv)
1143 memcpy(cdata->iv, iv, AES_BLOCK_SIZE);
1144 chunk = PADLOCK_CHUNK;
1145 cbc_shortcut: /* optimize for small input */
1147 inp = padlock_memcpy(out, in_arg, chunk);
1152 iv = padlock_xcrypt_cbc(chunk/AES_BLOCK_SIZE, cdata, out, inp);
1155 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1157 out = out_arg+=chunk;
1159 } while (nbytes -= chunk);
1160 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
1163 case EVP_CIPH_CFB_MODE:
1164 memcpy (iv = cdata->iv, ctx->iv, AES_BLOCK_SIZE);
1165 chunk &= ~(AES_BLOCK_SIZE-1);
1166 if (chunk) goto cfb_shortcut;
1167 else goto cfb_skiploop;
1169 if (iv != cdata->iv)
1170 memcpy(cdata->iv, iv, AES_BLOCK_SIZE);
1171 chunk = PADLOCK_CHUNK;
1172 cfb_shortcut: /* optimize for small input */
1174 inp = padlock_memcpy(out, in_arg, chunk);
1179 iv = padlock_xcrypt_cfb(chunk/AES_BLOCK_SIZE, cdata, out, inp);
1182 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1184 out = out_arg+=chunk;
1187 } while (nbytes >= AES_BLOCK_SIZE);
1191 unsigned char *ivp = cdata->iv;
1194 memcpy(ivp, iv, AES_BLOCK_SIZE);
1198 if (cdata->cword.b.encdec) {
1199 cdata->cword.b.encdec=0;
1200 padlock_reload_key();
1201 padlock_xcrypt_ecb(1,cdata,ivp,ivp);
1202 cdata->cword.b.encdec=1;
1203 padlock_reload_key();
1205 unsigned char c = *(in_arg++);
1206 *(out_arg++) = c ^ *ivp;
1207 *(ivp++) = c, nbytes--;
1210 else { padlock_reload_key();
1211 padlock_xcrypt_ecb(1,cdata,ivp,ivp);
1212 padlock_reload_key();
1214 *ivp = *(out_arg++) = *(in_arg++) ^ *ivp;
1220 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
1223 case EVP_CIPH_OFB_MODE:
1224 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
1225 chunk &= ~(AES_BLOCK_SIZE-1);
1228 inp = padlock_memcpy(out, in_arg, chunk);
1233 padlock_xcrypt_ofb(chunk/AES_BLOCK_SIZE, cdata, out, inp);
1236 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1238 out = out_arg+=chunk;
1241 chunk = PADLOCK_CHUNK;
1242 } while (nbytes >= AES_BLOCK_SIZE);
1245 unsigned char *ivp = cdata->iv;
1248 padlock_reload_key(); /* empirically found */
1249 padlock_xcrypt_ecb(1,cdata,ivp,ivp);
1250 padlock_reload_key(); /* empirically found */
1252 *(out_arg++) = *(in_arg++) ^ *ivp;
1257 memcpy(ctx->iv, cdata->iv, AES_BLOCK_SIZE);
1264 /* Clean the realign buffer if it was used */
1265 if (out_misaligned) {
1266 volatile unsigned long *p=(void *)out;
1267 size_t n = allocated/sizeof(*p);
1271 memset(cdata->iv, 0, AES_BLOCK_SIZE);
1276 #endif /* OPENSSL_NO_AES */
1278 /* ===== Random Number Generator ===== */
1280 * This code is not engaged. The reason is that it does not comply
1281 * with recommendations for VIA RNG usage for secure applications
1282 * (posted at http://www.via.com.tw/en/viac3/c3.jsp) nor does it
1283 * provide meaningful error control...
1285 /* Wrapper that provides an interface between the API and
1286 the raw PadLock RNG */
1288 padlock_rand_bytes(unsigned char *output, int count)
1290 unsigned int eax, buf;
1292 while (count >= 8) {
1293 eax = padlock_xstore(output, 0);
1294 if (!(eax&(1<<6))) return 0; /* RNG disabled */
1295 /* this ---vv--- covers DC bias, Raw Bits and String Filter */
1296 if (eax&(0x1F<<10)) return 0;
1297 if ((eax&0x1F)==0) continue; /* no data, retry... */
1298 if ((eax&0x1F)!=8) return 0; /* fatal failure... */
1303 eax = padlock_xstore(&buf, 3);
1304 if (!(eax&(1<<6))) return 0; /* RNG disabled */
1305 /* this ---vv--- covers DC bias, Raw Bits and String Filter */
1306 if (eax&(0x1F<<10)) return 0;
1307 if ((eax&0x1F)==0) continue; /* no data, retry... */
1308 if ((eax&0x1F)!=1) return 0; /* fatal failure... */
1309 *output++ = (unsigned char)buf;
1312 *(volatile unsigned int *)&buf=0;
1317 /* Dummy but necessary function */
1319 padlock_rand_status(void)
1324 /* Prepare structure for registration */
1325 static RAND_METHOD padlock_rand = {
1327 padlock_rand_bytes, /* bytes */
1330 padlock_rand_bytes, /* pseudorand */
1331 padlock_rand_status, /* rand status */
1334 #else /* !COMPILE_HW_PADLOCK */
1335 #ifndef OPENSSL_NO_DYNAMIC_ENGINE
1337 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
1339 int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { return 0; }
1340 IMPLEMENT_DYNAMIC_CHECK_FN()
1342 #endif /* COMPILE_HW_PADLOCK */
1344 #endif /* !OPENSSL_NO_HW_PADLOCK */
1345 #endif /* !OPENSSL_NO_HW */