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