cc9f9dc41e4adaaf75a9b718c5cefcfe25b418e5
[openssl.git] / crypto / engine / eng_padlock.c
1 /* 
2  * Support for VIA PadLock Advanced Cryptography Engine (ACE)
3  * Written by Michal Ludvig <michal@logix.cz>
4  *            http://www.logix.cz/michal
5  *
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!
9  */
10
11 /* ====================================================================
12  * Copyright (c) 1999-2001 The OpenSSL Project.  All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  *
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  *
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
24  *    distribution.
25  *
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/)"
30  *
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.
35  *
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.
39  *
40  * 6. Redistributions of any form whatsoever must retain the following
41  *    acknowledgment:
42  *    "This product includes software developed by the OpenSSL Project
43  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
44  *
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  * ====================================================================
58  *
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).
62  *
63  */
64
65
66 #include <stdio.h>
67 #include <string.h>
68
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>
76 #endif
77 #include <openssl/rand.h>
78
79 #ifndef OPENSSL_NO_HW
80 #ifndef OPENSSL_NO_HW_PADLOCK
81
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
86 #  endif
87 #elif (OPENSSL_VERSION_NUMBER >= 0x00907000L)
88 #  ifdef ENGINE_DYNAMIC_SUPPORT
89 #    define DYNAMIC_ENGINE
90 #  endif
91 #else
92 #  error "Only OpenSSL >= 0.9.7 is supported"
93 #endif
94
95 /* VIA PadLock AES is available *ONLY* on some x86 CPUs.
96    Not only that it doesn't exist elsewhere, but it
97    even can't be compiled on other platforms!
98  
99    In addition, because of the heavy use of inline assembler,
100    compiler choice is limited to GCC and Microsoft C. */
101 #undef COMPILE_HW_PADLOCK
102 #if !defined(I386_ONLY) && !defined(OPENSSL_NO_INLINE_ASM)
103 # if (defined(__GNUC__) && (defined(__i386__) || defined(__i386))) || \
104      (defined(_MSC_VER) && defined(_M_IX86))
105 #  define COMPILE_HW_PADLOCK
106 static ENGINE *ENGINE_padlock (void);
107 # endif
108 #endif
109
110 void ENGINE_load_padlock (void)
111 {
112 /* On non-x86 CPUs it just returns. */
113 #ifdef COMPILE_HW_PADLOCK
114         ENGINE *toadd = ENGINE_padlock ();
115         if (!toadd) return;
116         ENGINE_add (toadd);
117         ENGINE_free (toadd);
118         ERR_clear_error ();
119 #endif
120 }
121
122 #ifdef COMPILE_HW_PADLOCK
123 /* We do these includes here to avoid header problems on platforms that
124    do not have the VIA padlock anyway... */
125 #ifdef _MSC_VER
126 # include <malloc.h>
127 # define alloca _alloca
128 #else
129 # include <stdlib.h>
130 #endif
131
132 /* Function for ENGINE detection and control */
133 static int padlock_available(void);
134 static int padlock_init(ENGINE *e);
135
136 /* RNG Stuff */
137 static RAND_METHOD padlock_rand;
138
139 /* Cipher Stuff */
140 #ifndef OPENSSL_NO_AES
141 static int padlock_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid);
142 #endif
143
144 /* Engine names */
145 static const char *padlock_id = "padlock";
146 static char padlock_name[100];
147
148 /* Available features */
149 static int padlock_use_ace = 0; /* Advanced Cryptography Engine */
150 static int padlock_use_rng = 0; /* Random Number Generator */
151 #ifndef OPENSSL_NO_AES
152 static int padlock_aes_align_required = 1;
153 #endif
154
155 /* ===== Engine "management" functions ===== */
156
157 /* Prepare the ENGINE structure for registration */
158 static int
159 padlock_bind_helper(ENGINE *e)
160 {
161         /* Check available features */
162         padlock_available();
163
164 #if 1   /* disable RNG for now, see commentary in vicinity of RNG code */
165         padlock_use_rng=0;
166 #endif
167
168         /* Generate a nice engine name with available features */
169         BIO_snprintf(padlock_name, sizeof(padlock_name),
170                 "VIA PadLock (%s, %s)", 
171                  padlock_use_rng ? "RNG" : "no-RNG",
172                  padlock_use_ace ? "ACE" : "no-ACE");
173
174         /* Register everything or return with an error */ 
175         if (!ENGINE_set_id(e, padlock_id) ||
176             !ENGINE_set_name(e, padlock_name) ||
177
178             !ENGINE_set_init_function(e, padlock_init) ||
179 #ifndef OPENSSL_NO_AES
180             (padlock_use_ace && !ENGINE_set_ciphers (e, padlock_ciphers)) ||
181 #endif
182             (padlock_use_rng && !ENGINE_set_RAND (e, &padlock_rand))) {
183                 return 0;
184         }
185
186         /* Everything looks good */
187         return 1;
188 }
189
190 /* Constructor */
191 static ENGINE *
192 ENGINE_padlock(void)
193 {
194         ENGINE *eng = ENGINE_new();
195
196         if (!eng) {
197                 return NULL;
198         }
199
200         if (!padlock_bind_helper(eng)) {
201                 ENGINE_free(eng);
202                 return NULL;
203         }
204
205         return eng;
206 }
207
208 /* Check availability of the engine */
209 static int
210 padlock_init(ENGINE *e)
211 {
212         return (padlock_use_rng || padlock_use_ace);
213 }
214
215 /* This stuff is needed if this ENGINE is being compiled into a self-contained
216  * shared-library.
217  */
218 #ifdef DYNAMIC_ENGINE
219 static int
220 padlock_bind_fn(ENGINE *e, const char *id)
221 {
222         if (id && (strcmp(id, padlock_id) != 0)) {
223                 return 0;
224         }
225
226         if (!padlock_bind_helper(e))  {
227                 return 0;
228         }
229
230         return 1;
231 }
232
233 IMPLEMENT_DYNAMIC_CHECK_FN ();
234 IMPLEMENT_DYNAMIC_BIND_FN (padlock_bind_fn);
235 #endif /* DYNAMIC_ENGINE */
236
237 /* ===== Here comes the "real" engine ===== */
238
239 #ifndef OPENSSL_NO_AES
240 /* Some AES-related constants */
241 #define AES_BLOCK_SIZE          16
242 #define AES_KEY_SIZE_128        16
243 #define AES_KEY_SIZE_192        24
244 #define AES_KEY_SIZE_256        32
245
246 /* Here we store the status information relevant to the 
247    current context. */
248 /* BIG FAT WARNING:
249  *      Inline assembler in PADLOCK_XCRYPT_ASM()
250  *      depends on the order of items in this structure.
251  *      Don't blindly modify, reorder, etc!
252  */
253 struct padlock_cipher_data
254 {
255         unsigned char iv[AES_BLOCK_SIZE];       /* Initialization vector */
256         union { unsigned int pad[4];
257                 struct {
258                         int rounds:4;
259                         int algo:3;
260                         int keygen:1;
261                         int interm:1;
262                         int encdec:1;
263                         int ksize:2;
264                 } b;
265         } cword;                /* Control word */
266         AES_KEY ks;             /* Encryption key */
267 };
268
269 /*
270  * Essentially this variable belongs in thread local storage.
271  * Having this variable global on the other hand can only cause
272  * few bogus key reloads [if any at all on single-CPU system],
273  * so we accept the penatly...
274  */
275 static volatile struct padlock_cipher_data *padlock_saved_context;
276 #endif
277
278 /*
279  * =======================================================
280  * Inline assembler section(s).
281  * =======================================================
282  * Order of arguments is chosen to facilitate Windows port
283  * using __fastcall calling convention. If you wish to add
284  * more routines, keep in mind that first __fastcall
285  * argument is passed in %ecx and second - in %edx.
286  * =======================================================
287  */
288 #if defined(__GNUC__) && __GNUC__>=2
289 /*
290  * As for excessive "push %ebx"/"pop %ebx" found all over.
291  * When generating position-independent code GCC won't let
292  * us use "b" in assembler templates nor even respect "ebx"
293  * in "clobber description." Therefore the trouble...
294  */
295
296 /* Helper function - check if a CPUID instruction
297    is available on this CPU */
298 static int
299 padlock_insn_cpuid_available(void)
300 {
301         int result = -1;
302
303         /* We're checking if the bit #21 of EFLAGS 
304            can be toggled. If yes = CPUID is available. */
305         asm volatile (
306                 "pushf\n"
307                 "popl %%eax\n"
308                 "xorl $0x200000, %%eax\n"
309                 "movl %%eax, %%ecx\n"
310                 "andl $0x200000, %%ecx\n"
311                 "pushl %%eax\n"
312                 "popf\n"
313                 "pushf\n"
314                 "popl %%eax\n"
315                 "andl $0x200000, %%eax\n"
316                 "xorl %%eax, %%ecx\n"
317                 "movl %%ecx, %0\n"
318                 : "=r" (result) : : "eax", "ecx");
319         
320         return (result == 0);
321 }
322
323 /* Load supported features of the CPU to see if
324    the PadLock is available. */
325 static int
326 padlock_available(void)
327 {
328         char vendor_string[16];
329         unsigned int eax, edx;
330
331         /* First check if the CPUID instruction is available at all... */
332         if (! padlock_insn_cpuid_available())
333                 return 0;
334
335         /* Are we running on the Centaur (VIA) CPU? */
336         eax = 0x00000000;
337         vendor_string[12] = 0;
338         asm volatile (
339                 "pushl  %%ebx\n"
340                 "cpuid\n"
341                 "movl   %%ebx,(%%edi)\n"
342                 "movl   %%edx,4(%%edi)\n"
343                 "movl   %%ecx,8(%%edi)\n"
344                 "popl   %%ebx"
345                 : "+a"(eax) : "D"(vendor_string) : "ecx", "edx");
346         if (strcmp(vendor_string, "CentaurHauls") != 0)
347                 return 0;
348
349         /* Check for Centaur Extended Feature Flags presence */
350         eax = 0xC0000000;
351         asm volatile ("pushl %%ebx; cpuid; popl %%ebx"
352                 : "+a"(eax) : : "ecx", "edx");
353         if (eax < 0xC0000001)
354                 return 0;
355
356         /* Read the Centaur Extended Feature Flags */
357         eax = 0xC0000001;
358         asm volatile ("pushl %%ebx; cpuid; popl %%ebx"
359                 : "+a"(eax), "=d"(edx) : : "ecx");
360
361         /* Fill up some flags */
362         padlock_use_ace = ((edx & (0x3<<6)) == (0x3<<6));
363         padlock_use_rng = ((edx & (0x3<<2)) == (0x3<<2));
364
365         return padlock_use_ace + padlock_use_rng;
366 }
367
368 #ifndef OPENSSL_NO_AES
369 /* Our own htonl()/ntohl() */
370 static inline void
371 padlock_bswapl(AES_KEY *ks)
372 {
373         size_t i = sizeof(ks->rd_key)/sizeof(ks->rd_key[0]);
374         unsigned int *key = ks->rd_key;
375
376         while (i--) {
377                 asm volatile ("bswapl %0" : "+r"(*key));
378                 key++;
379         }
380 }
381 #endif
382
383 /* Force key reload from memory to the CPU microcode.
384    Loading EFLAGS from the stack clears EFLAGS[30] 
385    which does the trick. */
386 static inline void
387 padlock_reload_key(void)
388 {
389         asm volatile ("pushfl; popfl");
390 }
391
392 #ifndef OPENSSL_NO_AES
393 /*
394  * This is heuristic key context tracing. At first one
395  * believes that one should use atomic swap instructions,
396  * but it's not actually necessary. Point is that if
397  * padlock_saved_context was changed by another thread
398  * after we've read it and before we compare it with cdata,
399  * our key *shall* be reloaded upon thread context switch
400  * and we are therefore set in either case...
401  */
402 static inline void
403 padlock_verify_context(struct padlock_cipher_data *cdata)
404 {
405         asm volatile (
406         "pushfl\n"
407 "       btl     $30,(%%esp)\n"
408 "       jnc     1f\n"
409 "       cmpl    %2,%1\n"
410 "       je      1f\n"
411 "       popfl\n"
412 "       subl    $4,%%esp\n"
413 "1:     addl    $4,%%esp\n"
414 "       movl    %2,%0"
415         :"+m"(padlock_saved_context)
416         : "r"(padlock_saved_context), "r"(cdata) : "cc");
417 }
418
419 /* Template for padlock_xcrypt_* modes */
420 /* BIG FAT WARNING: 
421  *      The offsets used with 'leal' instructions
422  *      describe items of the 'padlock_cipher_data'
423  *      structure.
424  */
425 #define PADLOCK_XCRYPT_ASM(name,rep_xcrypt)     \
426 static inline void *name(size_t cnt,            \
427         struct padlock_cipher_data *cdata,      \
428         void *out, const void *inp)             \
429 {       void *iv;                               \
430         asm volatile ( "pushl   %%ebx\n"        \
431                 "       leal    16(%0),%%edx\n" \
432                 "       leal    32(%0),%%ebx\n" \
433                         rep_xcrypt "\n"         \
434                 "       popl    %%ebx"          \
435                 : "=a"(iv), "=c"(cnt), "=D"(out), "=S"(inp) \
436                 : "0"(cdata), "1"(cnt), "2"(out), "3"(inp) \
437                 : "edx", "cc");                 \
438         return iv;                              \
439 }
440
441 /* Generate all functions with appropriate opcodes */
442 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ecb, ".byte 0xf3,0x0f,0xa7,0xc8")     /* rep xcryptecb */
443 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cbc, ".byte 0xf3,0x0f,0xa7,0xd0")     /* rep xcryptcbc */
444 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cfb, ".byte 0xf3,0x0f,0xa7,0xe0")     /* rep xcryptcfb */
445 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ofb, ".byte 0xf3,0x0f,0xa7,0xe8")     /* rep xcryptofb */
446 #endif
447
448 /* The RNG call itself */
449 static inline unsigned int
450 padlock_xstore(void *addr, unsigned int edx_in)
451 {
452         unsigned int eax_out;
453
454         asm volatile (".byte 0x0f,0xa7,0xc0"    /* xstore */
455             : "=a"(eax_out),"=m"(*(unsigned *)addr)
456             : "D"(addr), "d" (edx_in)
457             );
458
459         return eax_out;
460 }
461
462 /* Why not inline 'rep movsd'? I failed to find information on what
463  * value in Direction Flag one can expect and consequently have to
464  * apply "better-safe-than-sorry" approach and assume "undefined."
465  * I could explicitly clear it and restore the original value upon
466  * return from padlock_aes_cipher, but it's presumably too much
467  * trouble for too little gain...
468  *
469  * In case you wonder 'rep xcrypt*' instructions above are *not*
470  * affected by the Direction Flag and pointers advance toward
471  * larger addresses unconditionally.
472  */ 
473 static inline unsigned char *
474 padlock_memcpy(void *dst,const void *src,size_t n)
475 {
476         long       *d=dst;
477         const long *s=src;
478
479         n /= sizeof(*d);
480         do { *d++ = *s++; } while (--n);
481
482         return dst;
483 }
484
485 #elif defined(_MSC_VER)
486 /*
487  * Unlike GCC these are real functions. In order to minimize impact
488  * on performance we adhere to __fastcall calling convention in
489  * order to get two first arguments passed through %ecx and %edx.
490  * Which kind of suits very well, as instructions in question use
491  * both %ecx and %edx as input:-)
492  */
493 #define REP_XCRYPT(code)                \
494         _asm _emit 0xf3                 \
495         _asm _emit 0x0f _asm _emit 0xa7 \
496         _asm _emit code
497
498 /* BIG FAT WARNING: 
499  *      The offsets used with 'lea' instructions
500  *      describe items of the 'padlock_cipher_data'
501  *      structure.
502  */
503 #define PADLOCK_XCRYPT_ASM(name,code)   \
504 static void * __fastcall                \
505         name (size_t cnt, void *cdata,  \
506         void *outp, const void *inp)    \
507 {       _asm    mov     eax,edx         \
508         _asm    lea     edx,[eax+16]    \
509         _asm    lea     ebx,[eax+32]    \
510         _asm    mov     edi,outp        \
511         _asm    mov     esi,inp         \
512         REP_XCRYPT(code)                \
513 }
514
515 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ecb,0xc8)
516 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cbc,0xd0)
517 PADLOCK_XCRYPT_ASM(padlock_xcrypt_cfb,0xe0)
518 PADLOCK_XCRYPT_ASM(padlock_xcrypt_ofb,0xe8)
519
520 static int __fastcall
521 padlock_xstore(void *outp,unsigned int code)
522 {       _asm    mov     edi,ecx
523         _asm _emit 0x0f _asm _emit 0xa7 _asm _emit 0xc0
524 }
525
526 static void __fastcall
527 padlock_reload_key(void)
528 {       _asm pushfd _asm popfd          }
529
530 static void __fastcall
531 padlock_verify_context(void *cdata)
532 {       _asm    {
533                 pushfd
534                 bt      DWORD PTR[esp],30
535                 jnc     skip
536                 cmp     ecx,padlock_saved_context
537                 je      skip
538                 popfd
539                 sub     esp,4
540         skip:   add     esp,4
541                 mov     padlock_saved_context,ecx
542                 }
543 }
544
545 static int
546 padlock_available(void)
547 {       _asm    {
548                 pushfd
549                 pop     eax
550                 mov     ecx,eax
551                 xor     eax,1<<21
552                 push    eax
553                 popfd
554                 pushfd
555                 pop     eax
556                 xor     eax,ecx
557                 bt      eax,21
558                 jnc     noluck
559                 mov     eax,0
560                 cpuid
561                 xor     eax,eax
562                 cmp     ebx,'tneC'
563                 jne     noluck
564                 cmp     edx,'Hrua'
565                 jne     noluck
566                 cmp     ecx,'slua'
567                 jne     noluck
568                 mov     eax,0xC0000000
569                 cpuid
570                 mov     edx,eax
571                 xor     eax,eax
572                 cmp     edx,0xC0000001
573                 jb      noluck
574                 mov     eax,0xC0000001
575                 cpuid
576                 xor     eax,eax
577                 bt      edx,6
578                 jnc     skip_a
579                 bt      edx,7
580                 jnc     skip_a
581                 mov     padlock_use_ace,1
582                 inc     eax
583         skip_a: bt      edx,2
584                 jnc     skip_r
585                 bt      edx,3
586                 jnc     skip_r
587                 mov     padlock_use_rng,1
588                 inc     eax
589         skip_r:
590         noluck:
591                 }
592 }
593
594 static void __fastcall
595 padlock_bswapl(void *key)
596 {       _asm    {
597                 pushfd
598                 cld
599                 mov     esi,ecx
600                 mov     edi,ecx
601                 mov     ecx,60
602         up:     lodsd
603                 bswap   eax
604                 stosd
605                 loop    up
606                 popfd
607                 }
608 }
609
610 /* MS actually specifies status of Direction Flag and compiler even
611  * manages to compile following as 'rep movsd' all by itself...
612  */
613 #define padlock_memcpy(o,i,n) ((unsigned char *)memcpy((o),(i),(n)&~3U))
614 #endif
615
616 /* ===== AES encryption/decryption ===== */
617 #ifndef OPENSSL_NO_AES
618
619 #if defined(NID_aes_128_cfb128) && ! defined (NID_aes_128_cfb)
620 #define NID_aes_128_cfb NID_aes_128_cfb128
621 #endif
622
623 #if defined(NID_aes_128_ofb128) && ! defined (NID_aes_128_ofb)
624 #define NID_aes_128_ofb NID_aes_128_ofb128
625 #endif
626
627 #if defined(NID_aes_192_cfb128) && ! defined (NID_aes_192_cfb)
628 #define NID_aes_192_cfb NID_aes_192_cfb128
629 #endif
630
631 #if defined(NID_aes_192_ofb128) && ! defined (NID_aes_192_ofb)
632 #define NID_aes_192_ofb NID_aes_192_ofb128
633 #endif
634
635 #if defined(NID_aes_256_cfb128) && ! defined (NID_aes_256_cfb)
636 #define NID_aes_256_cfb NID_aes_256_cfb128
637 #endif
638
639 #if defined(NID_aes_256_ofb128) && ! defined (NID_aes_256_ofb)
640 #define NID_aes_256_ofb NID_aes_256_ofb128
641 #endif
642
643 /* List of supported ciphers. */
644 static int padlock_cipher_nids[] = {
645         NID_aes_128_ecb,
646         NID_aes_128_cbc,
647         NID_aes_128_cfb,
648         NID_aes_128_ofb,
649
650         NID_aes_192_ecb,
651         NID_aes_192_cbc,
652 #if 0
653         NID_aes_192_cfb,        /* FIXME: AES192/256 CFB/OFB don't work. */
654         NID_aes_192_ofb,
655 #endif
656
657         NID_aes_256_ecb,
658         NID_aes_256_cbc,
659 #if 0
660         NID_aes_256_cfb,
661         NID_aes_256_ofb,
662 #endif
663 };
664 static int padlock_cipher_nids_num = (sizeof(padlock_cipher_nids)/
665                                       sizeof(padlock_cipher_nids[0]));
666
667 /* Function prototypes ... */
668 static int padlock_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
669                                 const unsigned char *iv, int enc);
670 static int padlock_aes_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
671                               const unsigned char *in, size_t nbytes);
672
673 #define NEAREST_ALIGNED(ptr) ( (unsigned char *)(ptr) +         \
674         ( (0x10 - ((size_t)(ptr) & 0x0F)) & 0x0F )      )
675 #define ALIGNED_CIPHER_DATA(ctx) ((struct padlock_cipher_data *)\
676         NEAREST_ALIGNED(ctx->cipher_data))
677
678 /* Declaring so many ciphers by hand would be a pain.
679    Instead introduce a bit of preprocessor magic :-) */
680 #define DECLARE_AES_EVP(ksize,lmode,umode)      \
681 static const EVP_CIPHER padlock_aes_##ksize##_##lmode = {       \
682         NID_aes_##ksize##_##lmode,              \
683         AES_BLOCK_SIZE,                 \
684         AES_KEY_SIZE_##ksize,           \
685         AES_BLOCK_SIZE,                 \
686         0 | EVP_CIPH_##umode##_MODE,    \
687         padlock_aes_init_key,           \
688         padlock_aes_cipher,             \
689         NULL,                           \
690         sizeof(struct padlock_cipher_data) + 16,        \
691         EVP_CIPHER_set_asn1_iv,         \
692         EVP_CIPHER_get_asn1_iv,         \
693         NULL,                           \
694         NULL                            \
695 }
696
697 DECLARE_AES_EVP(128,ecb,ECB);
698 DECLARE_AES_EVP(128,cbc,CBC);
699 DECLARE_AES_EVP(128,cfb,CFB);
700 DECLARE_AES_EVP(128,ofb,OFB);
701
702 DECLARE_AES_EVP(192,ecb,ECB);
703 DECLARE_AES_EVP(192,cbc,CBC);
704 DECLARE_AES_EVP(192,cfb,CFB);
705 DECLARE_AES_EVP(192,ofb,OFB);
706
707 DECLARE_AES_EVP(256,ecb,ECB);
708 DECLARE_AES_EVP(256,cbc,CBC);
709 DECLARE_AES_EVP(256,cfb,CFB);
710 DECLARE_AES_EVP(256,ofb,OFB);
711
712 static int
713 padlock_ciphers (ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid)
714 {
715         /* No specific cipher => return a list of supported nids ... */
716         if (!cipher) {
717                 *nids = padlock_cipher_nids;
718                 return padlock_cipher_nids_num;
719         }
720
721         /* ... or the requested "cipher" otherwise */
722         switch (nid) {
723           case NID_aes_128_ecb:
724             *cipher = &padlock_aes_128_ecb;
725             break;
726           case NID_aes_128_cbc:
727             *cipher = &padlock_aes_128_cbc;
728             break;
729           case NID_aes_128_cfb:
730             *cipher = &padlock_aes_128_cfb;
731             break;
732           case NID_aes_128_ofb:
733             *cipher = &padlock_aes_128_ofb;
734             break;
735
736           case NID_aes_192_ecb:
737             *cipher = &padlock_aes_192_ecb;
738             break;
739           case NID_aes_192_cbc:
740             *cipher = &padlock_aes_192_cbc;
741             break;
742           case NID_aes_192_cfb:
743             *cipher = &padlock_aes_192_cfb;
744             break;
745           case NID_aes_192_ofb:
746             *cipher = &padlock_aes_192_ofb;
747             break;
748
749           case NID_aes_256_ecb:
750             *cipher = &padlock_aes_256_ecb;
751             break;
752           case NID_aes_256_cbc:
753             *cipher = &padlock_aes_256_cbc;
754             break;
755           case NID_aes_256_cfb:
756             *cipher = &padlock_aes_256_cfb;
757             break;
758           case NID_aes_256_ofb:
759             *cipher = &padlock_aes_256_ofb;
760             break;
761
762           default:
763             /* Sorry, we don't support this NID */
764             *cipher = NULL;
765             return 0;
766         }
767
768         return 1;
769 }
770
771 /* Prepare the encryption key for PadLock usage */
772 static int
773 padlock_aes_init_key (EVP_CIPHER_CTX *ctx, const unsigned char *key,
774                       const unsigned char *iv, int enc)
775 {
776         struct padlock_cipher_data *cdata;
777         int key_len = EVP_CIPHER_CTX_key_length(ctx) * 8;
778
779         if (key==NULL) return 0;        /* ERROR */
780
781         cdata = ALIGNED_CIPHER_DATA(ctx);
782         memset(cdata, 0, sizeof(struct padlock_cipher_data));
783
784         /* Prepare Control word. */
785         cdata->cword.b.encdec = (ctx->encrypt == 0);
786         cdata->cword.b.rounds = 10 + (key_len - 128) / 32;
787         cdata->cword.b.ksize = (key_len - 128) / 64;
788
789         switch(key_len) {
790                 case 128:
791                         /* PadLock can generate an extended key for
792                            AES128 in hardware */
793                         memcpy(cdata->ks.rd_key, key, AES_KEY_SIZE_128);
794                         cdata->cword.b.keygen = 0;
795                         break;
796
797                 case 192:
798                 case 256:
799                         /* Generate an extended AES key in software.
800                            Needed for AES192/AES256 */
801                         /* Well, the above applies to Stepping 8 CPUs
802                            and is listed as hardware errata. They most
803                            likely will fix it at some point and then
804                            a check for stepping would be due here. */
805                         if (enc)
806                                 AES_set_encrypt_key(key, key_len, &cdata->ks);
807                         else
808                                 AES_set_decrypt_key(key, key_len, &cdata->ks);
809 #ifndef AES_ASM
810                         /* OpenSSL C functions use byte-swapped extended key. */
811                         padlock_bswapl(&cdata->ks);
812 #endif
813                         cdata->cword.b.keygen = 1;
814                         break;
815
816                 default:
817                         /* ERROR */
818                         return 0;
819         }
820
821         /*
822          * This is done to cover for cases when user reuses the
823          * context for new key. The catch is that if we don't do
824          * this, padlock_eas_cipher might proceed with old key...
825          */
826         padlock_reload_key ();
827
828         return 1;
829 }
830
831 /* 
832  * Simplified version of padlock_aes_cipher() used when
833  * 1) both input and output buffers are at aligned addresses.
834  * or when
835  * 2) running on a newer CPU that doesn't require aligned buffers.
836  */
837 static int
838 padlock_aes_cipher_omnivorous(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
839                 const unsigned char *in_arg, size_t nbytes)
840 {
841         struct padlock_cipher_data *cdata;
842         void  *iv;
843
844         cdata = ALIGNED_CIPHER_DATA(ctx);
845         padlock_verify_context(cdata);
846
847         switch (EVP_CIPHER_CTX_mode(ctx)) {
848         case EVP_CIPH_ECB_MODE:
849                 padlock_xcrypt_ecb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg);
850                 break;
851
852         case EVP_CIPH_CBC_MODE:
853                 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
854                 iv = padlock_xcrypt_cbc(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg);
855                 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
856                 break;
857
858         case EVP_CIPH_CFB_MODE:
859                 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
860                 iv = padlock_xcrypt_cfb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg);
861                 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
862                 break;
863
864         case EVP_CIPH_OFB_MODE:
865                 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
866                 padlock_xcrypt_ofb(nbytes/AES_BLOCK_SIZE, cdata, out_arg, in_arg);
867                 memcpy(ctx->iv, cdata->iv, AES_BLOCK_SIZE);
868                 break;
869
870         default:
871                 return 0;
872         }
873
874         memset(cdata->iv, 0, AES_BLOCK_SIZE);
875
876         return 1;
877 }
878
879 #ifndef  PADLOCK_CHUNK
880 # define PADLOCK_CHUNK  4096    /* Must be a power of 2 larger than 16 */
881 #endif
882 #if PADLOCK_CHUNK<16 || PADLOCK_CHUNK&(PADLOCK_CHUNK-1)
883 # error "insane PADLOCK_CHUNK..."
884 #endif
885
886 /* Re-align the arguments to 16-Bytes boundaries and run the 
887    encryption function itself. This function is not AES-specific. */
888 static int
889 padlock_aes_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
890                    const unsigned char *in_arg, size_t nbytes)
891 {
892         struct padlock_cipher_data *cdata;
893         const  void *inp;
894         unsigned char  *out;
895         void  *iv;
896         int    inp_misaligned, out_misaligned, realign_in_loop;
897         size_t chunk, allocated=0;
898
899         if (nbytes == 0)
900                 return 1;
901         if (nbytes % AES_BLOCK_SIZE)
902                 return 0; /* are we expected to do tail processing? */
903
904         /* VIA promises CPUs that won't require alignment in the future.
905            For now padlock_aes_align_required is initialized to 1 and
906            the condition is never met... */
907         if (!padlock_aes_align_required)
908                 return padlock_aes_cipher_omnivorous(ctx, out_arg, in_arg, nbytes);
909
910         inp_misaligned = (((size_t)in_arg) & 0x0F);
911         out_misaligned = (((size_t)out_arg) & 0x0F);
912
913         /* Note that even if output is aligned and input not,
914          * I still prefer to loop instead of copy the whole
915          * input and then encrypt in one stroke. This is done
916          * in order to improve L1 cache utilization... */
917         realign_in_loop = out_misaligned|inp_misaligned;
918
919         if (!realign_in_loop)
920                 return padlock_aes_cipher_omnivorous(ctx, out_arg, in_arg, nbytes);
921
922         /* this takes one "if" out of the loops */
923         chunk  = nbytes;
924         chunk %= PADLOCK_CHUNK;
925         if (chunk==0) chunk = PADLOCK_CHUNK;
926
927         if (out_misaligned) {
928                 /* optmize for small input */
929                 allocated = (chunk<nbytes?PADLOCK_CHUNK:nbytes);
930                 out = alloca(0x10 + allocated);
931                 out = NEAREST_ALIGNED(out);
932         }
933         else
934                 out = out_arg;
935
936         cdata = ALIGNED_CIPHER_DATA(ctx);
937         padlock_verify_context(cdata);
938
939         switch (EVP_CIPHER_CTX_mode(ctx)) {
940         case EVP_CIPH_ECB_MODE:
941                 do      {
942                         if (inp_misaligned)
943                                 inp = padlock_memcpy(out, in_arg, chunk);
944                         else
945                                 inp = in_arg;
946                         in_arg += chunk;
947
948                         padlock_xcrypt_ecb(chunk/AES_BLOCK_SIZE, cdata, out, inp);
949
950                         if (out_misaligned)
951                                 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
952                         else
953                                 out     = out_arg+=chunk;
954
955                         nbytes -= chunk;
956                         chunk   = PADLOCK_CHUNK;
957                 } while (nbytes);
958                 break;
959
960         case EVP_CIPH_CBC_MODE:
961                 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
962                 goto cbc_shortcut;
963                 do      {
964                         if (iv != cdata->iv)
965                                 memcpy(cdata->iv, iv, AES_BLOCK_SIZE);
966                         chunk = PADLOCK_CHUNK;
967                 cbc_shortcut: /* optimize for small input */
968                         if (inp_misaligned)
969                                 inp = padlock_memcpy(out, in_arg, chunk);
970                         else
971                                 inp = in_arg;
972                         in_arg += chunk;
973
974                         iv = padlock_xcrypt_cbc(chunk/AES_BLOCK_SIZE, cdata, out, inp);
975
976                         if (out_misaligned)
977                                 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
978                         else
979                                 out     = out_arg+=chunk;
980
981                 } while (nbytes -= chunk);
982                 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
983                 break;
984
985         case EVP_CIPH_CFB_MODE:
986                 memcpy (cdata->iv, ctx->iv, AES_BLOCK_SIZE);
987                 goto cfb_shortcut;
988                 do      {
989                         if (iv != cdata->iv)
990                                 memcpy(cdata->iv, iv, AES_BLOCK_SIZE);
991                         chunk = PADLOCK_CHUNK;
992                 cfb_shortcut: /* optimize for small input */
993                         if (inp_misaligned)
994                                 inp = padlock_memcpy(out, in_arg, chunk);
995                         else
996                                 inp = in_arg;
997                         in_arg += chunk;
998
999                         iv = padlock_xcrypt_cfb(chunk/AES_BLOCK_SIZE, cdata, out, inp);
1000
1001                         if (out_misaligned)
1002                                 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1003                         else
1004                                 out     = out_arg+=chunk;
1005
1006                 } while (nbytes -= chunk);
1007                 memcpy(ctx->iv, iv, AES_BLOCK_SIZE);
1008                 break;
1009
1010         case EVP_CIPH_OFB_MODE:
1011                 memcpy(cdata->iv, ctx->iv, AES_BLOCK_SIZE);
1012                 do      {
1013                         if (inp_misaligned)
1014                                 inp = padlock_memcpy(out, in_arg, chunk);
1015                         else
1016                                 inp = in_arg;
1017                         in_arg += chunk;
1018
1019                         padlock_xcrypt_ofb(chunk/AES_BLOCK_SIZE, cdata, out, inp);
1020
1021                         if (out_misaligned)
1022                                 out_arg = padlock_memcpy(out_arg, out, chunk) + chunk;
1023                         else
1024                                 out     = out_arg+=chunk;
1025
1026                         nbytes -= chunk;
1027                         chunk   = PADLOCK_CHUNK;
1028                 } while (nbytes);
1029                 memcpy(ctx->iv, cdata->iv, AES_BLOCK_SIZE);
1030                 break;
1031
1032         default:
1033                 return 0;
1034         }
1035
1036         /* Clean the realign buffer if it was used */
1037         if (out_misaligned) {
1038                 volatile unsigned long *p=(void *)out;
1039                 size_t   n = allocated/sizeof(*p);
1040                 while (n--) *p++=0;
1041         }
1042
1043         memset(cdata->iv, 0, AES_BLOCK_SIZE);
1044
1045         return 1;
1046 }
1047
1048 #endif /* OPENSSL_NO_AES */
1049
1050 /* ===== Random Number Generator ===== */
1051 /*
1052  * This code is not engaged. The reason is that it does not comply
1053  * with recommendations for VIA RNG usage for secure applications
1054  * (posted at http://www.via.com.tw/en/viac3/c3.jsp) nor does it
1055  * provide meaningful error control...
1056  */
1057 /* Wrapper that provides an interface between the API and 
1058    the raw PadLock RNG */
1059 static int
1060 padlock_rand_bytes(unsigned char *output, int count)
1061 {
1062         unsigned int eax, buf;
1063
1064         while (count >= 8) {
1065                 eax = padlock_xstore(output, 0);
1066                 if (!(eax&(1<<6)))      return 0; /* RNG disabled */
1067                 /* this ---vv--- covers DC bias, Raw Bits and String Filter */
1068                 if (eax&(0x1F<<10))     return 0;
1069                 if ((eax&0x1F)==0)      continue; /* no data, retry... */
1070                 if ((eax&0x1F)!=8)      return 0; /* fatal failure...  */
1071                 output += 8;
1072                 count  -= 8;
1073         }
1074         while (count > 0) {
1075                 eax = padlock_xstore(&buf, 3);
1076                 if (!(eax&(1<<6)))      return 0; /* RNG disabled */
1077                 /* this ---vv--- covers DC bias, Raw Bits and String Filter */
1078                 if (eax&(0x1F<<10))     return 0;
1079                 if ((eax&0x1F)==0)      continue; /* no data, retry... */
1080                 if ((eax&0x1F)!=1)      return 0; /* fatal failure...  */
1081                 *output++ = (unsigned char)buf;
1082                 count--;
1083         }
1084         *(volatile unsigned int *)&buf=0;
1085
1086         return 1;
1087 }
1088
1089 /* Dummy but necessary function */
1090 static int
1091 padlock_rand_status(void)
1092 {
1093         return 1;
1094 }
1095
1096 /* Prepare structure for registration */
1097 static RAND_METHOD padlock_rand = {
1098         NULL,                   /* seed */
1099         padlock_rand_bytes,     /* bytes */
1100         NULL,                   /* cleanup */
1101         NULL,                   /* add */
1102         padlock_rand_bytes,     /* pseudorand */
1103         padlock_rand_status,    /* rand status */
1104 };
1105
1106 #endif /* COMPILE_HW_PADLOCK */
1107
1108 #endif /* !OPENSSL_NO_HW_PADLOCK */
1109 #endif /* !OPENSSL_NO_HW */