eng_padlock.c 28 KB

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