cryptlib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*
  2. * Copyright 1998-2018 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  4. *
  5. * Licensed under the Apache License 2.0 (the "License"). You may not use
  6. * this file except in compliance with the License. You can obtain a copy
  7. * in the file LICENSE in the source distribution or at
  8. * https://www.openssl.org/source/license.html
  9. */
  10. #include "e_os.h"
  11. #include "crypto/cryptlib.h"
  12. #include <openssl/safestack.h>
  13. #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
  14. defined(__x86_64) || defined(__x86_64__) || \
  15. defined(_M_AMD64) || defined(_M_X64)
  16. extern unsigned int OPENSSL_ia32cap_P[4];
  17. # if defined(OPENSSL_CPUID_OBJ)
  18. /*
  19. * Purpose of these minimalistic and character-type-agnostic subroutines
  20. * is to break dependency on MSVCRT (on Windows) and locale. This makes
  21. * OPENSSL_cpuid_setup safe to use as "constructor". "Character-type-
  22. * agnostic" means that they work with either wide or 8-bit characters,
  23. * exploiting the fact that first 127 characters can be simply casted
  24. * between the sets, while the rest would be simply rejected by ossl_is*
  25. * subroutines.
  26. */
  27. # ifdef _WIN32
  28. typedef WCHAR variant_char;
  29. static variant_char *ossl_getenv(const char *name)
  30. {
  31. /*
  32. * Since we pull only one environment variable, it's simpler to
  33. * to just ignore |name| and use equivalent wide-char L-literal.
  34. * As well as to ignore excessively long values...
  35. */
  36. static WCHAR value[48];
  37. DWORD len = GetEnvironmentVariableW(L"OPENSSL_ia32cap", value, 48);
  38. return (len > 0 && len < 48) ? value : NULL;
  39. }
  40. # else
  41. typedef char variant_char;
  42. # define ossl_getenv getenv
  43. # endif
  44. # include "crypto/ctype.h"
  45. static int todigit(variant_char c)
  46. {
  47. if (ossl_isdigit(c))
  48. return c - '0';
  49. else if (ossl_isxdigit(c))
  50. return ossl_tolower(c) - 'a' + 10;
  51. /* return largest base value to make caller terminate the loop */
  52. return 16;
  53. }
  54. static uint64_t ossl_strtouint64(const variant_char *str)
  55. {
  56. uint64_t ret = 0;
  57. unsigned int digit, base = 10;
  58. if (*str == '0') {
  59. base = 8, str++;
  60. if (ossl_tolower(*str) == 'x')
  61. base = 16, str++;
  62. }
  63. while((digit = todigit(*str++)) < base)
  64. ret = ret * base + digit;
  65. return ret;
  66. }
  67. static variant_char *ossl_strchr(const variant_char *str, char srch)
  68. { variant_char c;
  69. while((c = *str)) {
  70. if (c == srch)
  71. return (variant_char *)str;
  72. str++;
  73. }
  74. return NULL;
  75. }
  76. # define OPENSSL_CPUID_SETUP
  77. typedef uint64_t IA32CAP;
  78. void OPENSSL_cpuid_setup(void)
  79. {
  80. static int trigger = 0;
  81. IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
  82. IA32CAP vec;
  83. const variant_char *env;
  84. if (trigger)
  85. return;
  86. trigger = 1;
  87. if ((env = ossl_getenv("OPENSSL_ia32cap")) != NULL) {
  88. int off = (env[0] == '~') ? 1 : 0;
  89. vec = ossl_strtouint64(env + off);
  90. if (off) {
  91. IA32CAP mask = vec;
  92. vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~mask;
  93. if (mask & (1<<24)) {
  94. /*
  95. * User disables FXSR bit, mask even other capabilities
  96. * that operate exclusively on XMM, so we don't have to
  97. * double-check all the time. We mask PCLMULQDQ, AMD XOP,
  98. * AES-NI and AVX. Formally speaking we don't have to
  99. * do it in x86_64 case, but we can safely assume that
  100. * x86_64 users won't actually flip this flag.
  101. */
  102. vec &= ~((IA32CAP)(1<<1|1<<11|1<<25|1<<28) << 32);
  103. }
  104. } else if (env[0] == ':') {
  105. vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
  106. }
  107. if ((env = ossl_strchr(env, ':')) != NULL) {
  108. IA32CAP vecx;
  109. env++;
  110. off = (env[0] == '~') ? 1 : 0;
  111. vecx = ossl_strtouint64(env + off);
  112. if (off) {
  113. OPENSSL_ia32cap_P[2] &= ~(unsigned int)vecx;
  114. OPENSSL_ia32cap_P[3] &= ~(unsigned int)(vecx >> 32);
  115. } else {
  116. OPENSSL_ia32cap_P[2] = (unsigned int)vecx;
  117. OPENSSL_ia32cap_P[3] = (unsigned int)(vecx >> 32);
  118. }
  119. } else {
  120. OPENSSL_ia32cap_P[2] = 0;
  121. OPENSSL_ia32cap_P[3] = 0;
  122. }
  123. } else {
  124. vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
  125. }
  126. /*
  127. * |(1<<10) sets a reserved bit to signal that variable
  128. * was initialized already... This is to avoid interference
  129. * with cpuid snippets in ELF .init segment.
  130. */
  131. OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10);
  132. OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32);
  133. }
  134. # else
  135. unsigned int OPENSSL_ia32cap_P[4];
  136. # endif
  137. #endif
  138. #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
  139. void OPENSSL_cpuid_setup(void)
  140. {
  141. }
  142. #endif
  143. #if defined(_WIN32)
  144. # include <tchar.h>
  145. # include <signal.h>
  146. # ifdef __WATCOMC__
  147. # if defined(_UNICODE) || defined(__UNICODE__)
  148. # define _vsntprintf _vsnwprintf
  149. # else
  150. # define _vsntprintf _vsnprintf
  151. # endif
  152. # endif
  153. # ifdef _MSC_VER
  154. # define alloca _alloca
  155. # endif
  156. # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
  157. # ifdef OPENSSL_SYS_WIN_CORE
  158. int OPENSSL_isservice(void)
  159. {
  160. /* OneCore API cannot interact with GUI */
  161. return 1;
  162. }
  163. # else
  164. int OPENSSL_isservice(void)
  165. {
  166. HWINSTA h;
  167. DWORD len;
  168. WCHAR *name;
  169. static union {
  170. void *p;
  171. FARPROC f;
  172. } _OPENSSL_isservice = {
  173. NULL
  174. };
  175. if (_OPENSSL_isservice.p == NULL) {
  176. HANDLE mod = GetModuleHandle(NULL);
  177. FARPROC f = NULL;
  178. if (mod != NULL)
  179. f = GetProcAddress(mod, "_OPENSSL_isservice");
  180. if (f == NULL)
  181. _OPENSSL_isservice.p = (void *)-1;
  182. else
  183. _OPENSSL_isservice.f = f;
  184. }
  185. if (_OPENSSL_isservice.p != (void *)-1)
  186. return (*_OPENSSL_isservice.f) ();
  187. h = GetProcessWindowStation();
  188. if (h == NULL)
  189. return -1;
  190. if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
  191. GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  192. return -1;
  193. if (len > 512)
  194. return -1; /* paranoia */
  195. len++, len &= ~1; /* paranoia */
  196. name = (WCHAR *)alloca(len + sizeof(WCHAR));
  197. if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
  198. return -1;
  199. len++, len &= ~1; /* paranoia */
  200. name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
  201. # if 1
  202. /*
  203. * This doesn't cover "interactive" services [working with real
  204. * WinSta0's] nor programs started non-interactively by Task Scheduler
  205. * [those are working with SAWinSta].
  206. */
  207. if (wcsstr(name, L"Service-0x"))
  208. return 1;
  209. # else
  210. /* This covers all non-interactive programs such as services. */
  211. if (!wcsstr(name, L"WinSta0"))
  212. return 1;
  213. # endif
  214. else
  215. return 0;
  216. }
  217. # endif
  218. # else
  219. int OPENSSL_isservice(void)
  220. {
  221. return 0;
  222. }
  223. # endif
  224. void OPENSSL_showfatal(const char *fmta, ...)
  225. {
  226. va_list ap;
  227. TCHAR buf[256];
  228. const TCHAR *fmt;
  229. /*
  230. * First check if it's a console application, in which case the
  231. * error message would be printed to standard error.
  232. * Windows CE does not have a concept of a console application,
  233. * so we need to guard the check.
  234. */
  235. # ifdef STD_ERROR_HANDLE
  236. HANDLE h;
  237. if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
  238. GetFileType(h) != FILE_TYPE_UNKNOWN) {
  239. /* must be console application */
  240. int len;
  241. DWORD out;
  242. va_start(ap, fmta);
  243. len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
  244. WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
  245. va_end(ap);
  246. return;
  247. }
  248. # endif
  249. if (sizeof(TCHAR) == sizeof(char))
  250. fmt = (const TCHAR *)fmta;
  251. else
  252. do {
  253. int keepgoing;
  254. size_t len_0 = strlen(fmta) + 1, i;
  255. WCHAR *fmtw;
  256. fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
  257. if (fmtw == NULL) {
  258. fmt = (const TCHAR *)L"no stack?";
  259. break;
  260. }
  261. if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
  262. for (i = 0; i < len_0; i++)
  263. fmtw[i] = (WCHAR)fmta[i];
  264. for (i = 0; i < len_0; i++) {
  265. if (fmtw[i] == L'%')
  266. do {
  267. keepgoing = 0;
  268. switch (fmtw[i + 1]) {
  269. case L'0':
  270. case L'1':
  271. case L'2':
  272. case L'3':
  273. case L'4':
  274. case L'5':
  275. case L'6':
  276. case L'7':
  277. case L'8':
  278. case L'9':
  279. case L'.':
  280. case L'*':
  281. case L'-':
  282. i++;
  283. keepgoing = 1;
  284. break;
  285. case L's':
  286. fmtw[i + 1] = L'S';
  287. break;
  288. case L'S':
  289. fmtw[i + 1] = L's';
  290. break;
  291. case L'c':
  292. fmtw[i + 1] = L'C';
  293. break;
  294. case L'C':
  295. fmtw[i + 1] = L'c';
  296. break;
  297. }
  298. } while (keepgoing);
  299. }
  300. fmt = (const TCHAR *)fmtw;
  301. } while (0);
  302. va_start(ap, fmta);
  303. _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap);
  304. buf[OSSL_NELEM(buf) - 1] = _T('\0');
  305. va_end(ap);
  306. # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
  307. # ifdef OPENSSL_SYS_WIN_CORE
  308. /* ONECORE is always NONGUI and NT >= 0x0601 */
  309. /*
  310. * TODO: (For non GUI and no std error cases)
  311. * Add event logging feature here.
  312. */
  313. # if !defined(NDEBUG)
  314. /*
  315. * We are in a situation where we tried to report a critical
  316. * error and this failed for some reason. As a last resort,
  317. * in debug builds, send output to the debugger or any other
  318. * tool like DebugView which can monitor the output.
  319. */
  320. OutputDebugString(buf);
  321. # endif
  322. # else
  323. /* this -------------v--- guards NT-specific calls */
  324. if (check_winnt() && OPENSSL_isservice() > 0) {
  325. HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL"));
  326. if (hEventLog != NULL) {
  327. const TCHAR *pmsg = buf;
  328. if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL,
  329. 1, 0, &pmsg, NULL)) {
  330. # if !defined(NDEBUG)
  331. /*
  332. * We are in a situation where we tried to report a critical
  333. * error and this failed for some reason. As a last resort,
  334. * in debug builds, send output to the debugger or any other
  335. * tool like DebugView which can monitor the output.
  336. */
  337. OutputDebugString(pmsg);
  338. # endif
  339. }
  340. (void)DeregisterEventSource(hEventLog);
  341. }
  342. } else {
  343. MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
  344. }
  345. # endif
  346. # else
  347. MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
  348. # endif
  349. }
  350. #else
  351. void OPENSSL_showfatal(const char *fmta, ...)
  352. {
  353. #ifndef OPENSSL_NO_STDIO
  354. va_list ap;
  355. va_start(ap, fmta);
  356. vfprintf(stderr, fmta, ap);
  357. va_end(ap);
  358. #endif
  359. }
  360. int OPENSSL_isservice(void)
  361. {
  362. return 0;
  363. }
  364. #endif
  365. void OPENSSL_die(const char *message, const char *file, int line)
  366. {
  367. OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n",
  368. file, line, message);
  369. #if !defined(_WIN32)
  370. abort();
  371. #else
  372. /*
  373. * Win32 abort() customarily shows a dialog, but we just did that...
  374. */
  375. # if !defined(_WIN32_WCE)
  376. raise(SIGABRT);
  377. # endif
  378. _exit(3);
  379. #endif
  380. }
  381. #if !defined(OPENSSL_CPUID_OBJ)
  382. /*
  383. * The volatile is used to to ensure that the compiler generates code that reads
  384. * all values from the array and doesn't try to optimize this away. The standard
  385. * doesn't actually require this behavior if the original data pointed to is
  386. * not volatile, but compilers do this in practice anyway.
  387. *
  388. * There are also assembler versions of this function.
  389. */
  390. # undef CRYPTO_memcmp
  391. int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len)
  392. {
  393. size_t i;
  394. const volatile unsigned char *a = in_a;
  395. const volatile unsigned char *b = in_b;
  396. unsigned char x = 0;
  397. for (i = 0; i < len; i++)
  398. x |= a[i] ^ b[i];
  399. return x;
  400. }
  401. /*
  402. * For systems that don't provide an instruction counter register or equivalent.
  403. */
  404. uint32_t OPENSSL_rdtsc(void)
  405. {
  406. return 0;
  407. }
  408. size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt)
  409. {
  410. return 0;
  411. }
  412. size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max)
  413. {
  414. return 0;
  415. }
  416. #endif
  417. #if defined(__TANDEM) && defined(OPENSSL_VPROC)
  418. /*
  419. * Define a VPROC function for HP NonStop build crypto library.
  420. * This is used by platform version identification tools.
  421. * Do not inline this procedure or make it static.
  422. */
  423. # define OPENSSL_VPROC_STRING_(x) x##_CRYPTO
  424. # define OPENSSL_VPROC_STRING(x) OPENSSL_VPROC_STRING_(x)
  425. # define OPENSSL_VPROC_FUNC OPENSSL_VPROC_STRING(OPENSSL_VPROC)
  426. void OPENSSL_VPROC_FUNC(void) {}
  427. #endif /* __TANDEM */