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