crypto/cryptlib.c: mask more capability bits upon FXSR bit flip.
[openssl.git] / crypto / cryptlib.c
1 /*
2  * Copyright 1998-2017 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 #include <stdio.h>
23 #  define OPENSSL_CPUID_SETUP
24 typedef uint64_t IA32CAP;
25 void OPENSSL_cpuid_setup(void)
26 {
27     static int trigger = 0;
28     IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
29     IA32CAP vec;
30     char *env;
31
32     if (trigger)
33         return;
34
35     trigger = 1;
36     if ((env = getenv("OPENSSL_ia32cap"))) {
37         int off = (env[0] == '~') ? 1 : 0;
38 #  if defined(_WIN32)
39         if (!sscanf(env + off, "%I64i", &vec))
40             vec = strtoul(env + off, NULL, 0);
41 #  else
42         if (!sscanf(env + off, "%lli", (long long *)&vec))
43             vec = strtoul(env + off, NULL, 0);
44 #  endif
45         if (off) {
46             IA32CAP mask = vec;
47             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~mask;
48             if (mask & (1<<24)) {
49                 /*
50                  * User disables FXSR bit, mask even other capabilities
51                  * that operate exclusively on XMM, so we don't have to
52                  * double-check all the time. We mask PCLMULQDQ, AMD XOP,
53                  * AES-NI and AVX. Formally speaking we don't have to
54                  * do it in x86_64 case, but we can safely assume that
55                  * x86_64 users won't actually flip this flag.
56                  */
57                 vec &= ~((IA32CAP)(1<<1|1<<11|1<<25|1<<28) << 32);
58             }
59         } else if (env[0] == ':') {
60             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
61         }
62
63         if ((env = strchr(env, ':'))) {
64             unsigned int vecx;
65             env++;
66             off = (env[0] == '~') ? 1 : 0;
67             vecx = strtoul(env + off, NULL, 0);
68             if (off)
69                 OPENSSL_ia32cap_P[2] &= ~vecx;
70             else
71                 OPENSSL_ia32cap_P[2] = vecx;
72         } else {
73             OPENSSL_ia32cap_P[2] = 0;
74         }
75     } else {
76         vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
77     }
78
79     /*
80      * |(1<<10) sets a reserved bit to signal that variable
81      * was initialized already... This is to avoid interference
82      * with cpuid snippets in ELF .init segment.
83      */
84     OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10);
85     OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32);
86 }
87 # else
88 unsigned int OPENSSL_ia32cap_P[4];
89 # endif
90 #endif
91 int OPENSSL_NONPIC_relocated = 0;
92 #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
93 void OPENSSL_cpuid_setup(void)
94 {
95 }
96 #endif
97
98 #if defined(_WIN32) && !defined(__CYGWIN__)
99 # include <tchar.h>
100 # include <signal.h>
101 # ifdef __WATCOMC__
102 #  if defined(_UNICODE) || defined(__UNICODE__)
103 #   define _vsntprintf _vsnwprintf
104 #  else
105 #   define _vsntprintf _vsnprintf
106 #  endif
107 # endif
108 # ifdef _MSC_VER
109 #  define alloca _alloca
110 # endif
111
112 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
113 int OPENSSL_isservice(void)
114 {
115     HWINSTA h;
116     DWORD len;
117     WCHAR *name;
118     static union {
119         void *p;
120         FARPROC f;
121     } _OPENSSL_isservice = {
122         NULL
123     };
124
125     if (_OPENSSL_isservice.p == NULL) {
126         HANDLE mod = GetModuleHandle(NULL);
127         if (mod != NULL)
128             _OPENSSL_isservice.f = GetProcAddress(mod, "_OPENSSL_isservice");
129         if (_OPENSSL_isservice.p == NULL)
130             _OPENSSL_isservice.p = (void *)-1;
131     }
132
133     if (_OPENSSL_isservice.p != (void *)-1)
134         return (*_OPENSSL_isservice.f) ();
135
136     h = GetProcessWindowStation();
137     if (h == NULL)
138         return -1;
139
140     if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
141         GetLastError() != ERROR_INSUFFICIENT_BUFFER)
142         return -1;
143
144     if (len > 512)
145         return -1;              /* paranoia */
146     len++, len &= ~1;           /* paranoia */
147     name = (WCHAR *)alloca(len + sizeof(WCHAR));
148     if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
149         return -1;
150
151     len++, len &= ~1;           /* paranoia */
152     name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
153 #  if 1
154     /*
155      * This doesn't cover "interactive" services [working with real
156      * WinSta0's] nor programs started non-interactively by Task Scheduler
157      * [those are working with SAWinSta].
158      */
159     if (wcsstr(name, L"Service-0x"))
160         return 1;
161 #  else
162     /* This covers all non-interactive programs such as services. */
163     if (!wcsstr(name, L"WinSta0"))
164         return 1;
165 #  endif
166     else
167         return 0;
168 }
169 # else
170 int OPENSSL_isservice(void)
171 {
172     return 0;
173 }
174 # endif
175
176 void OPENSSL_showfatal(const char *fmta, ...)
177 {
178     va_list ap;
179     TCHAR buf[256];
180     const TCHAR *fmt;
181     /*
182      * First check if it's a console application, in which case the
183      * error message would be printed to standard error.
184      * Windows CE does not have a concept of a console application,
185      * so we need to guard the check.
186      */
187 # ifdef STD_ERROR_HANDLE
188     HANDLE h;
189
190     if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
191         GetFileType(h) != FILE_TYPE_UNKNOWN) {
192         /* must be console application */
193         int len;
194         DWORD out;
195
196         va_start(ap, fmta);
197         len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
198         WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
199         va_end(ap);
200         return;
201     }
202 # endif
203
204     if (sizeof(TCHAR) == sizeof(char))
205         fmt = (const TCHAR *)fmta;
206     else
207         do {
208             int keepgoing;
209             size_t len_0 = strlen(fmta) + 1, i;
210             WCHAR *fmtw;
211
212             fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
213             if (fmtw == NULL) {
214                 fmt = (const TCHAR *)L"no stack?";
215                 break;
216             }
217             if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
218                 for (i = 0; i < len_0; i++)
219                     fmtw[i] = (WCHAR)fmta[i];
220             for (i = 0; i < len_0; i++) {
221                 if (fmtw[i] == L'%')
222                     do {
223                         keepgoing = 0;
224                         switch (fmtw[i + 1]) {
225                         case L'0':
226                         case L'1':
227                         case L'2':
228                         case L'3':
229                         case L'4':
230                         case L'5':
231                         case L'6':
232                         case L'7':
233                         case L'8':
234                         case L'9':
235                         case L'.':
236                         case L'*':
237                         case L'-':
238                             i++;
239                             keepgoing = 1;
240                             break;
241                         case L's':
242                             fmtw[i + 1] = L'S';
243                             break;
244                         case L'S':
245                             fmtw[i + 1] = L's';
246                             break;
247                         case L'c':
248                             fmtw[i + 1] = L'C';
249                             break;
250                         case L'C':
251                             fmtw[i + 1] = L'c';
252                             break;
253                         }
254                     } while (keepgoing);
255             }
256             fmt = (const TCHAR *)fmtw;
257         } while (0);
258
259     va_start(ap, fmta);
260     _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap);
261     buf[OSSL_NELEM(buf) - 1] = _T('\0');
262     va_end(ap);
263
264 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
265     /* this -------------v--- guards NT-specific calls */
266     if (check_winnt() && OPENSSL_isservice() > 0) {
267         HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL"));
268
269         if (hEventLog != NULL) {
270             const TCHAR *pmsg = buf;
271
272             if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL,
273                              1, 0, &pmsg, NULL)) {
274 #if defined(DEBUG)
275                 /*
276                  * We are in a situation where we tried to report a critical
277                  * error and this failed for some reason. As a last resort,
278                  * in debug builds, send output to the debugger or any other
279                  * tool like DebugView which can monitor the output.
280                  */
281                 OutputDebugString(pmsg);
282 #endif
283             }
284
285             (void)DeregisterEventSource(hEventLog);
286         }
287     } else
288 # endif
289         MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
290 }
291 #else
292 void OPENSSL_showfatal(const char *fmta, ...)
293 {
294 #ifndef OPENSSL_NO_STDIO
295     va_list ap;
296
297     va_start(ap, fmta);
298     vfprintf(stderr, fmta, ap);
299     va_end(ap);
300 #endif
301 }
302
303 int OPENSSL_isservice(void)
304 {
305     return 0;
306 }
307 #endif
308
309 void OPENSSL_die(const char *message, const char *file, int line)
310 {
311     OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n",
312                       file, line, message);
313 #if !defined(_WIN32) || defined(__CYGWIN__)
314     abort();
315 #else
316     /*
317      * Win32 abort() customarily shows a dialog, but we just did that...
318      */
319 # if !defined(_WIN32_WCE)
320     raise(SIGABRT);
321 # endif
322     _exit(3);
323 #endif
324 }
325
326 #if !defined(OPENSSL_CPUID_OBJ)
327 /*
328  * The volatile is used to to ensure that the compiler generates code that reads
329  * all values from the array and doesn't try to optimize this away. The standard
330  * doesn't actually require this behavior if the original data pointed to is
331  * not volatile, but compilers do this in practice anyway.
332  *
333  * There are also assembler versions of this function.
334  */
335 # undef CRYPTO_memcmp
336 int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len)
337 {
338     size_t i;
339     const volatile unsigned char *a = in_a;
340     const volatile unsigned char *b = in_b;
341     unsigned char x = 0;
342
343     for (i = 0; i < len; i++)
344         x |= a[i] ^ b[i];
345
346     return x;
347 }
348 #endif