eng_padlock.c 28 KB

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