844a78fc6d137a7336f683a5dffebcbe1ca48a11
[openssl.git] / engines / e_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 #include <stdio.h>
66 #include <string.h>
67
68 #include <openssl/opensslconf.h>
69 #include <openssl/crypto.h>
70 #include <openssl/engine.h>
71 #include <openssl/evp.h>
72 #include <openssl/aes.h>
73 #include <openssl/rand.h>
74 #include <openssl/err.h>
75 #include <openssl/modes.h>
76
77 #ifndef OPENSSL_NO_HW
78 # ifndef OPENSSL_NO_HW_PADLOCK
79
80 /* Attempt to have a single source for both 0.9.7 and 0.9.8 :-) */
81 #  if (OPENSSL_VERSION_NUMBER >= 0x00908000L)
82 #   ifndef OPENSSL_NO_DYNAMIC_ENGINE
83 #    define DYNAMIC_ENGINE
84 #   endif
85 #  elif (OPENSSL_VERSION_NUMBER >= 0x00907000L)
86 #   ifdef ENGINE_DYNAMIC_SUPPORT
87 #    define DYNAMIC_ENGINE
88 #   endif
89 #  else
90 #   error "Only OpenSSL >= 0.9.7 is supported"
91 #  endif
92
93 /*
94  * VIA PadLock AES is available *ONLY* on some x86 CPUs. Not only that it
95  * doesn't exist elsewhere, but it even can't be compiled on other platforms!
96  */
97
98 #  undef COMPILE_HW_PADLOCK
99 #  if !defined(I386_ONLY) && !defined(OPENSSL_NO_ASM)
100 #   if    defined(__i386__) || defined(__i386) ||    \
101         defined(__x86_64__) || defined(__x86_64) || \
102         defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)
103 #    define COMPILE_HW_PADLOCK
104 #    ifdef OPENSSL_NO_DYNAMIC_ENGINE
105 static ENGINE *ENGINE_padlock(void);
106 #    endif
107 #   endif
108 #  endif
109
110 #  ifdef OPENSSL_NO_DYNAMIC_ENGINE
111 void engine_load_padlock_int(void);
112 void engine_load_padlock_int(void)
113 {
114 /* On non-x86 CPUs it just returns. */
115 #   ifdef COMPILE_HW_PADLOCK
116     ENGINE *toadd = ENGINE_padlock();
117     if (!toadd)
118         return;
119     ENGINE_add(toadd);
120     ENGINE_free(toadd);
121     ERR_clear_error();
122 #   endif
123 }
124
125 #  endif
126
127 #  ifdef COMPILE_HW_PADLOCK
128
129 /* Function for ENGINE detection and control */
130 static int padlock_available(void);
131 static int padlock_init(ENGINE *e);
132
133 /* RNG Stuff */
134 static RAND_METHOD padlock_rand;
135
136 /* Cipher Stuff */
137 static int padlock_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
138                            const int **nids, int nid);
139
140 /* Engine names */
141 static const char *padlock_id = "padlock";
142 static char padlock_name[100];
143
144 /* Available features */
145 static int padlock_use_ace = 0; /* Advanced Cryptography Engine */
146 static int padlock_use_rng = 0; /* Random Number Generator */
147
148 /* ===== Engine "management" functions ===== */
149
150 /* Prepare the ENGINE structure for registration */
151 static int padlock_bind_helper(ENGINE *e)
152 {
153     /* Check available features */
154     padlock_available();
155
156     /*
157      * RNG is currently disabled for reasons discussed in commentary just
158      * before padlock_rand_bytes function.
159      */
160     padlock_use_rng = 0;
161
162     /* Generate a nice engine name with available features */
163     BIO_snprintf(padlock_name, sizeof(padlock_name),
164                  "VIA PadLock (%s, %s)",
165                  padlock_use_rng ? "RNG" : "no-RNG",
166                  padlock_use_ace ? "ACE" : "no-ACE");
167
168     /* Register everything or return with an error */
169     if (!ENGINE_set_id(e, padlock_id) ||
170         !ENGINE_set_name(e, padlock_name) ||
171         !ENGINE_set_init_function(e, padlock_init) ||
172         (padlock_use_ace && !ENGINE_set_ciphers(e, padlock_ciphers)) ||
173         (padlock_use_rng && !ENGINE_set_RAND(e, &padlock_rand))) {
174         return 0;
175     }
176
177     /* Everything looks good */
178     return 1;
179 }
180
181 #   ifdef OPENSSL_NO_DYNAMIC_ENGINE
182 /* Constructor */
183 static ENGINE *ENGINE_padlock(void)
184 {
185     ENGINE *eng = ENGINE_new();
186
187     if (eng == NULL) {
188         return NULL;
189     }
190
191     if (!padlock_bind_helper(eng)) {
192         ENGINE_free(eng);
193         return NULL;
194     }
195
196     return eng;
197 }
198 #   endif
199
200 /* Check availability of the engine */
201 static int padlock_init(ENGINE *e)
202 {
203     return (padlock_use_rng || padlock_use_ace);
204 }
205
206 /*
207  * This stuff is needed if this ENGINE is being compiled into a
208  * self-contained shared-library.
209  */
210 #   ifdef DYNAMIC_ENGINE
211 static int padlock_bind_fn(ENGINE *e, const char *id)
212 {
213     if (id && (strcmp(id, padlock_id) != 0)) {
214         return 0;
215     }
216
217     if (!padlock_bind_helper(e)) {
218         return 0;
219     }
220
221     return 1;
222 }
223
224 IMPLEMENT_DYNAMIC_CHECK_FN()
225 IMPLEMENT_DYNAMIC_BIND_FN(padlock_bind_fn)
226 #   endif                       /* DYNAMIC_ENGINE */
227 /* ===== Here comes the "real" engine ===== */
228
229 /* Some AES-related constants */
230 #   define AES_BLOCK_SIZE          16
231 #   define AES_KEY_SIZE_128        16
232 #   define AES_KEY_SIZE_192        24
233 #   define AES_KEY_SIZE_256        32
234     /*
235      * Here we store the status information relevant to the current context.
236      */
237     /*
238      * BIG FAT WARNING: Inline assembler in PADLOCK_XCRYPT_ASM() depends on
239      * the order of items in this structure.  Don't blindly modify, reorder,
240      * etc!
241      */
242 struct padlock_cipher_data {
243     unsigned char iv[AES_BLOCK_SIZE]; /* Initialization vector */
244     union {
245         unsigned int pad[4];
246         struct {
247             int rounds:4;
248             int dgst:1;         /* n/a in C3 */
249             int align:1;        /* n/a in C3 */
250             int ciphr:1;        /* n/a in C3 */
251             unsigned int keygen:1;
252             int interm:1;
253             unsigned int encdec:1;
254             int ksize:2;
255         } b;
256     } cword;                    /* Control word */
257     AES_KEY ks;                 /* Encryption key */
258 };
259
260 /* Interface to assembler module */
261 unsigned int padlock_capability();
262 void padlock_key_bswap(AES_KEY *key);
263 void padlock_verify_context(struct padlock_cipher_data *ctx);
264 void padlock_reload_key();
265 void padlock_aes_block(void *out, const void *inp,
266                        struct padlock_cipher_data *ctx);
267 int padlock_ecb_encrypt(void *out, const void *inp,
268                         struct padlock_cipher_data *ctx, size_t len);
269 int padlock_cbc_encrypt(void *out, const void *inp,
270                         struct padlock_cipher_data *ctx, size_t len);
271 int padlock_cfb_encrypt(void *out, const void *inp,
272                         struct padlock_cipher_data *ctx, size_t len);
273 int padlock_ofb_encrypt(void *out, const void *inp,
274                         struct padlock_cipher_data *ctx, size_t len);
275 int padlock_ctr32_encrypt(void *out, const void *inp,
276                           struct padlock_cipher_data *ctx, size_t len);
277 int padlock_xstore(void *out, int edx);
278 void padlock_sha1_oneshot(void *ctx, const void *inp, size_t len);
279 void padlock_sha1(void *ctx, const void *inp, size_t len);
280 void padlock_sha256_oneshot(void *ctx, const void *inp, size_t len);
281 void padlock_sha256(void *ctx, const void *inp, size_t len);
282
283 /*
284  * Load supported features of the CPU to see if the PadLock is available.
285  */
286 static int padlock_available(void)
287 {
288     unsigned int edx = padlock_capability();
289
290     /* Fill up some flags */
291     padlock_use_ace = ((edx & (0x3 << 6)) == (0x3 << 6));
292     padlock_use_rng = ((edx & (0x3 << 2)) == (0x3 << 2));
293
294     return padlock_use_ace + padlock_use_rng;
295 }
296
297 /* ===== AES encryption/decryption ===== */
298
299 #   if defined(NID_aes_128_cfb128) && ! defined (NID_aes_128_cfb)
300 #    define NID_aes_128_cfb NID_aes_128_cfb128
301 #   endif
302
303 #   if defined(NID_aes_128_ofb128) && ! defined (NID_aes_128_ofb)
304 #    define NID_aes_128_ofb NID_aes_128_ofb128
305 #   endif
306
307 #   if defined(NID_aes_192_cfb128) && ! defined (NID_aes_192_cfb)
308 #    define NID_aes_192_cfb NID_aes_192_cfb128
309 #   endif
310
311 #   if defined(NID_aes_192_ofb128) && ! defined (NID_aes_192_ofb)
312 #    define NID_aes_192_ofb NID_aes_192_ofb128
313 #   endif
314
315 #   if defined(NID_aes_256_cfb128) && ! defined (NID_aes_256_cfb)
316 #    define NID_aes_256_cfb NID_aes_256_cfb128
317 #   endif
318
319 #   if defined(NID_aes_256_ofb128) && ! defined (NID_aes_256_ofb)
320 #    define NID_aes_256_ofb NID_aes_256_ofb128
321 #   endif
322
323 /* List of supported ciphers. */
324 static const int padlock_cipher_nids[] = {
325     NID_aes_128_ecb,
326     NID_aes_128_cbc,
327     NID_aes_128_cfb,
328     NID_aes_128_ofb,
329     NID_aes_128_ctr,
330
331     NID_aes_192_ecb,
332     NID_aes_192_cbc,
333     NID_aes_192_cfb,
334     NID_aes_192_ofb,
335     NID_aes_192_ctr,
336
337     NID_aes_256_ecb,
338     NID_aes_256_cbc,
339     NID_aes_256_cfb,
340     NID_aes_256_ofb,
341     NID_aes_256_ctr
342 };
343
344 static int padlock_cipher_nids_num = (sizeof(padlock_cipher_nids) /
345                                       sizeof(padlock_cipher_nids[0]));
346
347 /* Function prototypes ... */
348 static int padlock_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
349                                 const unsigned char *iv, int enc);
350
351 #   define NEAREST_ALIGNED(ptr) ( (unsigned char *)(ptr) +         \
352         ( (0x10 - ((size_t)(ptr) & 0x0F)) & 0x0F )      )
353 #   define ALIGNED_CIPHER_DATA(ctx) ((struct padlock_cipher_data *)\
354         NEAREST_ALIGNED(EVP_CIPHER_CTX_get_cipher_data(ctx)))
355
356 static int
357 padlock_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
358                    const unsigned char *in_arg, size_t nbytes)
359 {
360     return padlock_ecb_encrypt(out_arg, in_arg,
361                                ALIGNED_CIPHER_DATA(ctx), nbytes);
362 }
363
364 static int
365 padlock_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
366                    const unsigned char *in_arg, size_t nbytes)
367 {
368     struct padlock_cipher_data *cdata = ALIGNED_CIPHER_DATA(ctx);
369     int ret;
370
371     memcpy(cdata->iv, EVP_CIPHER_CTX_iv(ctx), AES_BLOCK_SIZE);
372     if ((ret = padlock_cbc_encrypt(out_arg, in_arg, cdata, nbytes)))
373         memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), cdata->iv, AES_BLOCK_SIZE);
374     return ret;
375 }
376
377 static int
378 padlock_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
379                    const unsigned char *in_arg, size_t nbytes)
380 {
381     struct padlock_cipher_data *cdata = ALIGNED_CIPHER_DATA(ctx);
382     size_t chunk;
383
384     if ((chunk = EVP_CIPHER_CTX_num(ctx))) {   /* borrow chunk variable */
385         unsigned char *ivp = EVP_CIPHER_CTX_iv_noconst(ctx);
386
387         if (chunk >= AES_BLOCK_SIZE)
388             return 0;           /* bogus value */
389
390         if (EVP_CIPHER_CTX_encrypting(ctx))
391             while (chunk < AES_BLOCK_SIZE && nbytes != 0) {
392                 ivp[chunk] = *(out_arg++) = *(in_arg++) ^ ivp[chunk];
393                 chunk++, nbytes--;
394         } else
395             while (chunk < AES_BLOCK_SIZE && nbytes != 0) {
396                 unsigned char c = *(in_arg++);
397                 *(out_arg++) = c ^ ivp[chunk];
398                 ivp[chunk++] = c, nbytes--;
399             }
400
401         EVP_CIPHER_CTX_set_num(ctx, chunk % AES_BLOCK_SIZE);
402     }
403
404     if (nbytes == 0)
405         return 1;
406
407     memcpy(cdata->iv, EVP_CIPHER_CTX_iv(ctx), AES_BLOCK_SIZE);
408
409     if ((chunk = nbytes & ~(AES_BLOCK_SIZE - 1))) {
410         if (!padlock_cfb_encrypt(out_arg, in_arg, cdata, chunk))
411             return 0;
412         nbytes -= chunk;
413     }
414
415     if (nbytes) {
416         unsigned char *ivp = cdata->iv;
417
418         out_arg += chunk;
419         in_arg += chunk;
420         EVP_CIPHER_CTX_set_num(ctx, nbytes);
421         if (cdata->cword.b.encdec) {
422             cdata->cword.b.encdec = 0;
423             padlock_reload_key();
424             padlock_aes_block(ivp, ivp, cdata);
425             cdata->cword.b.encdec = 1;
426             padlock_reload_key();
427             while (nbytes) {
428                 unsigned char c = *(in_arg++);
429                 *(out_arg++) = c ^ *ivp;
430                 *(ivp++) = c, nbytes--;
431             }
432         } else {
433             padlock_reload_key();
434             padlock_aes_block(ivp, ivp, cdata);
435             padlock_reload_key();
436             while (nbytes) {
437                 *ivp = *(out_arg++) = *(in_arg++) ^ *ivp;
438                 ivp++, nbytes--;
439             }
440         }
441     }
442
443     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), cdata->iv, AES_BLOCK_SIZE);
444
445     return 1;
446 }
447
448 static int
449 padlock_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
450                    const unsigned char *in_arg, size_t nbytes)
451 {
452     struct padlock_cipher_data *cdata = ALIGNED_CIPHER_DATA(ctx);
453     size_t chunk;
454
455     /*
456      * ctx->num is maintained in byte-oriented modes, such as CFB and OFB...
457      */
458     if ((chunk = EVP_CIPHER_CTX_num(ctx))) {   /* borrow chunk variable */
459         unsigned char *ivp = EVP_CIPHER_CTX_iv_noconst(ctx);
460
461         if (chunk >= AES_BLOCK_SIZE)
462             return 0;           /* bogus value */
463
464         while (chunk < AES_BLOCK_SIZE && nbytes != 0) {
465             *(out_arg++) = *(in_arg++) ^ ivp[chunk];
466             chunk++, nbytes--;
467         }
468
469         EVP_CIPHER_CTX_set_num(ctx, chunk % AES_BLOCK_SIZE);
470     }
471
472     if (nbytes == 0)
473         return 1;
474
475     memcpy(cdata->iv, EVP_CIPHER_CTX_iv(ctx), AES_BLOCK_SIZE);
476
477     if ((chunk = nbytes & ~(AES_BLOCK_SIZE - 1))) {
478         if (!padlock_ofb_encrypt(out_arg, in_arg, cdata, chunk))
479             return 0;
480         nbytes -= chunk;
481     }
482
483     if (nbytes) {
484         unsigned char *ivp = cdata->iv;
485
486         out_arg += chunk;
487         in_arg += chunk;
488         EVP_CIPHER_CTX_set_num(ctx, nbytes);
489         padlock_reload_key();   /* empirically found */
490         padlock_aes_block(ivp, ivp, cdata);
491         padlock_reload_key();   /* empirically found */
492         while (nbytes) {
493             *(out_arg++) = *(in_arg++) ^ *ivp;
494             ivp++, nbytes--;
495         }
496     }
497
498     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), cdata->iv, AES_BLOCK_SIZE);
499
500     return 1;
501 }
502
503 static void padlock_ctr32_encrypt_glue(const unsigned char *in,
504                                        unsigned char *out, size_t blocks,
505                                        struct padlock_cipher_data *ctx,
506                                        const unsigned char *ivec)
507 {
508     memcpy(ctx->iv, ivec, AES_BLOCK_SIZE);
509     padlock_ctr32_encrypt(out, in, ctx, AES_BLOCK_SIZE * blocks);
510 }
511
512 static int
513 padlock_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out_arg,
514                    const unsigned char *in_arg, size_t nbytes)
515 {
516     struct padlock_cipher_data *cdata = ALIGNED_CIPHER_DATA(ctx);
517     unsigned int num = EVP_CIPHER_CTX_num(ctx);
518
519     CRYPTO_ctr128_encrypt_ctr32(in_arg, out_arg, nbytes,
520                                 cdata, EVP_CIPHER_CTX_iv_noconst(ctx),
521                                 EVP_CIPHER_CTX_buf_noconst(ctx), &num,
522                                 (ctr128_f) padlock_ctr32_encrypt_glue);
523
524     EVP_CIPHER_CTX_set_num(ctx, (size_t)num);
525     return 1;
526 }
527
528 #   define EVP_CIPHER_block_size_ECB       AES_BLOCK_SIZE
529 #   define EVP_CIPHER_block_size_CBC       AES_BLOCK_SIZE
530 #   define EVP_CIPHER_block_size_OFB       1
531 #   define EVP_CIPHER_block_size_CFB       1
532 #   define EVP_CIPHER_block_size_CTR       1
533
534 /*
535  * Declaring so many ciphers by hand would be a pain. Instead introduce a bit
536  * of preprocessor magic :-)
537  */
538 #   define DECLARE_AES_EVP(ksize,lmode,umode)      \
539 static EVP_CIPHER *_hidden_aes_##ksize##_##lmode = NULL; \
540 static const EVP_CIPHER *padlock_aes_##ksize##_##lmode(void) \
541 {                                                                       \
542     if (_hidden_aes_##ksize##_##lmode == NULL                           \
543         && ((_hidden_aes_##ksize##_##lmode =                            \
544              EVP_CIPHER_meth_new(NID_aes_##ksize##_##lmode,             \
545                                  EVP_CIPHER_block_size_##umode,         \
546                                  AES_KEY_SIZE_##ksize)) == NULL         \
547             || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_##ksize##_##lmode, \
548                                               AES_BLOCK_SIZE)           \
549             || !EVP_CIPHER_meth_set_flags(_hidden_aes_##ksize##_##lmode, \
550                                           0 | EVP_CIPH_##umode##_MODE)  \
551             || !EVP_CIPHER_meth_set_init(_hidden_aes_##ksize##_##lmode, \
552                                          padlock_aes_init_key)          \
553             || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_##ksize##_##lmode, \
554                                               padlock_##lmode##_cipher) \
555             || !EVP_CIPHER_meth_set_impl_ctx_size(_hidden_aes_##ksize##_##lmode, \
556                                                   sizeof(struct padlock_cipher_data) + 16) \
557             || !EVP_CIPHER_meth_set_set_asn1_params(_hidden_aes_##ksize##_##lmode, \
558                                                     EVP_CIPHER_set_asn1_iv) \
559             || !EVP_CIPHER_meth_set_get_asn1_params(_hidden_aes_##ksize##_##lmode, \
560                                                     EVP_CIPHER_get_asn1_iv))) { \
561         EVP_CIPHER_meth_free(_hidden_aes_##ksize##_##lmode);            \
562         _hidden_aes_##ksize##_##lmode = NULL;                           \
563     }                                                                   \
564     return _hidden_aes_##ksize##_##lmode;                               \
565 }
566
567 DECLARE_AES_EVP(128, ecb, ECB)
568 DECLARE_AES_EVP(128, cbc, CBC)
569 DECLARE_AES_EVP(128, cfb, CFB)
570 DECLARE_AES_EVP(128, ofb, OFB)
571 DECLARE_AES_EVP(128, ctr, CTR)
572
573 DECLARE_AES_EVP(192, ecb, ECB)
574 DECLARE_AES_EVP(192, cbc, CBC)
575 DECLARE_AES_EVP(192, cfb, CFB)
576 DECLARE_AES_EVP(192, ofb, OFB)
577 DECLARE_AES_EVP(192, ctr, CTR)
578
579 DECLARE_AES_EVP(256, ecb, ECB)
580 DECLARE_AES_EVP(256, cbc, CBC)
581 DECLARE_AES_EVP(256, cfb, CFB)
582 DECLARE_AES_EVP(256, ofb, OFB)
583 DECLARE_AES_EVP(256, ctr, CTR)
584
585 static int
586 padlock_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids,
587                 int nid)
588 {
589     /* No specific cipher => return a list of supported nids ... */
590     if (!cipher) {
591         *nids = padlock_cipher_nids;
592         return padlock_cipher_nids_num;
593     }
594
595     /* ... or the requested "cipher" otherwise */
596     switch (nid) {
597     case NID_aes_128_ecb:
598         *cipher = padlock_aes_128_ecb();
599         break;
600     case NID_aes_128_cbc:
601         *cipher = padlock_aes_128_cbc();
602         break;
603     case NID_aes_128_cfb:
604         *cipher = padlock_aes_128_cfb();
605         break;
606     case NID_aes_128_ofb:
607         *cipher = padlock_aes_128_ofb();
608         break;
609     case NID_aes_128_ctr:
610         *cipher = padlock_aes_128_ctr();
611         break;
612
613     case NID_aes_192_ecb:
614         *cipher = padlock_aes_192_ecb();
615         break;
616     case NID_aes_192_cbc:
617         *cipher = padlock_aes_192_cbc();
618         break;
619     case NID_aes_192_cfb:
620         *cipher = padlock_aes_192_cfb();
621         break;
622     case NID_aes_192_ofb:
623         *cipher = padlock_aes_192_ofb();
624         break;
625     case NID_aes_192_ctr:
626         *cipher = padlock_aes_192_ctr();
627         break;
628
629     case NID_aes_256_ecb:
630         *cipher = padlock_aes_256_ecb();
631         break;
632     case NID_aes_256_cbc:
633         *cipher = padlock_aes_256_cbc();
634         break;
635     case NID_aes_256_cfb:
636         *cipher = padlock_aes_256_cfb();
637         break;
638     case NID_aes_256_ofb:
639         *cipher = padlock_aes_256_ofb();
640         break;
641     case NID_aes_256_ctr:
642         *cipher = padlock_aes_256_ctr();
643         break;
644
645     default:
646         /* Sorry, we don't support this NID */
647         *cipher = NULL;
648         return 0;
649     }
650
651     return 1;
652 }
653
654 /* Prepare the encryption key for PadLock usage */
655 static int
656 padlock_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
657                      const unsigned char *iv, int enc)
658 {
659     struct padlock_cipher_data *cdata;
660     int key_len = EVP_CIPHER_CTX_key_length(ctx) * 8;
661     unsigned long mode = EVP_CIPHER_CTX_mode(ctx);
662
663     if (key == NULL)
664         return 0;               /* ERROR */
665
666     cdata = ALIGNED_CIPHER_DATA(ctx);
667     memset(cdata, 0, sizeof(*cdata));
668
669     /* Prepare Control word. */
670     if (mode == EVP_CIPH_OFB_MODE || mode == EVP_CIPH_CTR_MODE)
671         cdata->cword.b.encdec = 0;
672     else
673         cdata->cword.b.encdec = (EVP_CIPHER_CTX_encrypting(ctx) == 0);
674     cdata->cword.b.rounds = 10 + (key_len - 128) / 32;
675     cdata->cword.b.ksize = (key_len - 128) / 64;
676
677     switch (key_len) {
678     case 128:
679         /*
680          * PadLock can generate an extended key for AES128 in hardware
681          */
682         memcpy(cdata->ks.rd_key, key, AES_KEY_SIZE_128);
683         cdata->cword.b.keygen = 0;
684         break;
685
686     case 192:
687     case 256:
688         /*
689          * Generate an extended AES key in software. Needed for AES192/AES256
690          */
691         /*
692          * Well, the above applies to Stepping 8 CPUs and is listed as
693          * hardware errata. They most likely will fix it at some point and
694          * then a check for stepping would be due here.
695          */
696         if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
697             && !enc)
698             AES_set_decrypt_key(key, key_len, &cdata->ks);
699         else
700             AES_set_encrypt_key(key, key_len, &cdata->ks);
701 #   ifndef AES_ASM
702         /*
703          * OpenSSL C functions use byte-swapped extended key.
704          */
705         padlock_key_bswap(&cdata->ks);
706 #   endif
707         cdata->cword.b.keygen = 1;
708         break;
709
710     default:
711         /* ERROR */
712         return 0;
713     }
714
715     /*
716      * This is done to cover for cases when user reuses the
717      * context for new key. The catch is that if we don't do
718      * this, padlock_eas_cipher might proceed with old key...
719      */
720     padlock_reload_key();
721
722     return 1;
723 }
724
725 /* ===== Random Number Generator ===== */
726 /*
727  * This code is not engaged. The reason is that it does not comply
728  * with recommendations for VIA RNG usage for secure applications
729  * (posted at http://www.via.com.tw/en/viac3/c3.jsp) nor does it
730  * provide meaningful error control...
731  */
732 /*
733  * Wrapper that provides an interface between the API and the raw PadLock
734  * RNG
735  */
736 static int padlock_rand_bytes(unsigned char *output, int count)
737 {
738     unsigned int eax, buf;
739
740     while (count >= 8) {
741         eax = padlock_xstore(output, 0);
742         if (!(eax & (1 << 6)))
743             return 0;           /* RNG disabled */
744         /* this ---vv--- covers DC bias, Raw Bits and String Filter */
745         if (eax & (0x1F << 10))
746             return 0;
747         if ((eax & 0x1F) == 0)
748             continue;           /* no data, retry... */
749         if ((eax & 0x1F) != 8)
750             return 0;           /* fatal failure...  */
751         output += 8;
752         count -= 8;
753     }
754     while (count > 0) {
755         eax = padlock_xstore(&buf, 3);
756         if (!(eax & (1 << 6)))
757             return 0;           /* RNG disabled */
758         /* this ---vv--- covers DC bias, Raw Bits and String Filter */
759         if (eax & (0x1F << 10))
760             return 0;
761         if ((eax & 0x1F) == 0)
762             continue;           /* no data, retry... */
763         if ((eax & 0x1F) != 1)
764             return 0;           /* fatal failure...  */
765         *output++ = (unsigned char)buf;
766         count--;
767     }
768     OPENSSL_cleanse(&buf, sizeof(buf));
769
770     return 1;
771 }
772
773 /* Dummy but necessary function */
774 static int padlock_rand_status(void)
775 {
776     return 1;
777 }
778
779 /* Prepare structure for registration */
780 static RAND_METHOD padlock_rand = {
781     NULL,                       /* seed */
782     padlock_rand_bytes,         /* bytes */
783     NULL,                       /* cleanup */
784     NULL,                       /* add */
785     padlock_rand_bytes,         /* pseudorand */
786     padlock_rand_status,        /* rand status */
787 };
788
789 #  endif                        /* COMPILE_HW_PADLOCK */
790 # endif                         /* !OPENSSL_NO_HW_PADLOCK */
791 #endif                          /* !OPENSSL_NO_HW */
792
793 #if defined(OPENSSL_NO_HW) || defined(OPENSSL_NO_HW_PADLOCK) \
794         || !defined(COMPILE_HW_PADLOCK)
795 # ifndef OPENSSL_NO_DYNAMIC_ENGINE
796 OPENSSL_EXPORT
797     int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns);
798 OPENSSL_EXPORT
799     int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns)
800 {
801     return 0;
802 }
803
804 IMPLEMENT_DYNAMIC_CHECK_FN()
805 # endif
806 #endif