crypto/cryptlib.c: resolve possible race in OPENSSL_isservice.
[openssl.git] / crypto / cryptlib.c
1 /*
2  * Copyright 1998-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12  * ECDH support in OpenSSL originally developed by
13  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
14  */
15
16 #include "internal/cryptlib_int.h"
17 #include <openssl/safestack.h>
18
19 #if     defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
20         defined(__x86_64) || defined(__x86_64__) || \
21         defined(_M_AMD64) || defined(_M_X64)
22
23 extern unsigned int OPENSSL_ia32cap_P[4];
24
25 # if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
26 #include <stdio.h>
27 #  define OPENSSL_CPUID_SETUP
28 typedef uint64_t IA32CAP;
29 void OPENSSL_cpuid_setup(void)
30 {
31     static int trigger = 0;
32     IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
33     IA32CAP vec;
34     char *env;
35
36     if (trigger)
37         return;
38
39     trigger = 1;
40     if ((env = getenv("OPENSSL_ia32cap"))) {
41         int off = (env[0] == '~') ? 1 : 0;
42 #  if defined(_WIN32)
43         if (!sscanf(env + off, "%I64i", &vec))
44             vec = strtoul(env + off, NULL, 0);
45 #  else
46         if (!sscanf(env + off, "%lli", (long long *)&vec))
47             vec = strtoul(env + off, NULL, 0);
48 #  endif
49         if (off) {
50             IA32CAP mask = vec;
51             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~mask;
52             if (mask & (1<<24)) {
53                 /*
54                  * User disables FXSR bit, mask even other capabilities
55                  * that operate exclusively on XMM, so we don't have to
56                  * double-check all the time. We mask PCLMULQDQ, AMD XOP,
57                  * AES-NI and AVX. Formally speaking we don't have to
58                  * do it in x86_64 case, but we can safely assume that
59                  * x86_64 users won't actually flip this flag.
60                  */
61                 vec &= ~((IA32CAP)(1<<1|1<<11|1<<25|1<<28) << 32);
62             }
63         } else if (env[0] == ':') {
64             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
65         }
66
67         if ((env = strchr(env, ':'))) {
68             unsigned int vecx;
69             env++;
70             off = (env[0] == '~') ? 1 : 0;
71             vecx = strtoul(env + off, NULL, 0);
72             if (off)
73                 OPENSSL_ia32cap_P[2] &= ~vecx;
74             else
75                 OPENSSL_ia32cap_P[2] = vecx;
76         } else {
77             OPENSSL_ia32cap_P[2] = 0;
78         }
79     } else {
80         vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
81     }
82
83     /*
84      * |(1<<10) sets a reserved bit to signal that variable
85      * was initialized already... This is to avoid interference
86      * with cpuid snippets in ELF .init segment.
87      */
88     OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10);
89     OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32);
90 }
91 # else
92 unsigned int OPENSSL_ia32cap_P[4];
93 # endif
94 #endif
95 int OPENSSL_NONPIC_relocated = 0;
96 #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
97 void OPENSSL_cpuid_setup(void)
98 {
99 }
100 #endif
101
102 #if defined(_WIN32)
103 # include <tchar.h>
104 # include <signal.h>
105 # ifdef __WATCOMC__
106 #  if defined(_UNICODE) || defined(__UNICODE__)
107 #   define _vsntprintf _vsnwprintf
108 #  else
109 #   define _vsntprintf _vsnprintf
110 #  endif
111 # endif
112 # ifdef _MSC_VER
113 #  define alloca _alloca
114 # endif
115
116 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
117 int OPENSSL_isservice(void)
118 {
119     HWINSTA h;
120     DWORD len;
121     WCHAR *name;
122     static union {
123         void *p;
124         FARPROC f;
125     } _OPENSSL_isservice = {
126         NULL
127     };
128
129     if (_OPENSSL_isservice.p == NULL) {
130         HANDLE mod = GetModuleHandle(NULL);
131         FARPROC f;
132
133         if (mod != NULL)
134             f = GetProcAddress(mod, "_OPENSSL_isservice");
135         if (f == NULL)
136             _OPENSSL_isservice.p = (void *)-1;
137         else
138             _OPENSSL_isservice.f = f;
139     }
140
141     if (_OPENSSL_isservice.p != (void *)-1)
142         return (*_OPENSSL_isservice.f) ();
143
144     h = GetProcessWindowStation();
145     if (h == NULL)
146         return -1;
147
148     if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
149         GetLastError() != ERROR_INSUFFICIENT_BUFFER)
150         return -1;
151
152     if (len > 512)
153         return -1;              /* paranoia */
154     len++, len &= ~1;           /* paranoia */
155     name = (WCHAR *)alloca(len + sizeof(WCHAR));
156     if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
157         return -1;
158
159     len++, len &= ~1;           /* paranoia */
160     name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
161 #  if 1
162     /*
163      * This doesn't cover "interactive" services [working with real
164      * WinSta0's] nor programs started non-interactively by Task Scheduler
165      * [those are working with SAWinSta].
166      */
167     if (wcsstr(name, L"Service-0x"))
168         return 1;
169 #  else
170     /* This covers all non-interactive programs such as services. */
171     if (!wcsstr(name, L"WinSta0"))
172         return 1;
173 #  endif
174     else
175         return 0;
176 }
177 # else
178 int OPENSSL_isservice(void)
179 {
180     return 0;
181 }
182 # endif
183
184 void OPENSSL_showfatal(const char *fmta, ...)
185 {
186     va_list ap;
187     TCHAR buf[256];
188     const TCHAR *fmt;
189 # ifdef STD_ERROR_HANDLE        /* what a dirty trick! */
190     HANDLE h;
191
192     if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
193         GetFileType(h) != FILE_TYPE_UNKNOWN) {
194         /* must be console application */
195         int len;
196         DWORD out;
197
198         va_start(ap, fmta);
199         len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
200         WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
201         va_end(ap);
202         return;
203     }
204 # endif
205
206     if (sizeof(TCHAR) == sizeof(char))
207         fmt = (const TCHAR *)fmta;
208     else
209         do {
210             int keepgoing;
211             size_t len_0 = strlen(fmta) + 1, i;
212             WCHAR *fmtw;
213
214             fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
215             if (fmtw == NULL) {
216                 fmt = (const TCHAR *)L"no stack?";
217                 break;
218             }
219             if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
220                 for (i = 0; i < len_0; i++)
221                     fmtw[i] = (WCHAR)fmta[i];
222             for (i = 0; i < len_0; i++) {
223                 if (fmtw[i] == L'%')
224                     do {
225                         keepgoing = 0;
226                         switch (fmtw[i + 1]) {
227                         case L'0':
228                         case L'1':
229                         case L'2':
230                         case L'3':
231                         case L'4':
232                         case L'5':
233                         case L'6':
234                         case L'7':
235                         case L'8':
236                         case L'9':
237                         case L'.':
238                         case L'*':
239                         case L'-':
240                             i++;
241                             keepgoing = 1;
242                             break;
243                         case L's':
244                             fmtw[i + 1] = L'S';
245                             break;
246                         case L'S':
247                             fmtw[i + 1] = L's';
248                             break;
249                         case L'c':
250                             fmtw[i + 1] = L'C';
251                             break;
252                         case L'C':
253                             fmtw[i + 1] = L'c';
254                             break;
255                         }
256                     } while (keepgoing);
257             }
258             fmt = (const TCHAR *)fmtw;
259         } while (0);
260
261     va_start(ap, fmta);
262     _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap);
263     buf[OSSL_NELEM(buf) - 1] = _T('\0');
264     va_end(ap);
265
266 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
267     /* this -------------v--- guards NT-specific calls */
268     if (check_winnt() && OPENSSL_isservice() > 0) {
269         HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL"));
270
271         if (hEventLog != NULL) {
272             const TCHAR *pmsg = buf;
273
274             if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL,
275                              1, 0, &pmsg, NULL)) {
276 #if defined(DEBUG)
277                 /*
278                  * We are in a situation where we tried to report a critical
279                  * error and this failed for some reason. As a last resort,
280                  * in debug builds, send output to the debugger or any other
281                  * tool like DebugView which can monitor the output.
282                  */
283                 OutputDebugString(pmsg);
284 #endif
285             }
286
287             (void)DeregisterEventSource(hEventLog);
288         }
289     } else
290 # endif
291         MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
292 }
293 #else
294 void OPENSSL_showfatal(const char *fmta, ...)
295 {
296 #ifndef OPENSSL_NO_STDIO
297     va_list ap;
298
299     va_start(ap, fmta);
300     vfprintf(stderr, fmta, ap);
301     va_end(ap);
302 #endif
303 }
304
305 int OPENSSL_isservice(void)
306 {
307     return 0;
308 }
309 #endif
310
311 void OPENSSL_die(const char *message, const char *file, int line)
312 {
313     OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n",
314                       file, line, message);
315 #if !defined(_WIN32)
316     abort();
317 #else
318     /*
319      * Win32 abort() customarily shows a dialog, but we just did that...
320      */
321 # if !defined(_WIN32_WCE)
322     raise(SIGABRT);
323 # endif
324     _exit(3);
325 #endif
326 }
327
328 #if !defined(OPENSSL_CPUID_OBJ)
329 /* volatile unsigned char* pointers are there because
330  * 1. Accessing a variable declared volatile via a pointer
331  *    that lacks a volatile qualifier causes undefined behavior.
332  * 2. When the variable itself is not volatile the compiler is
333  *    not required to keep all those reads and can convert
334  *    this into canonical memcmp() which doesn't read the whole block.
335  * Pointers to volatile resolve the first problem fully. The second
336  * problem cannot be resolved in any Standard-compliant way but this
337  * works the problem around. Compilers typically react to
338  * pointers to volatile by preserving the reads and writes through them.
339  * The latter is not required by the Standard if the memory pointed to
340  * is not volatile.
341  * Pointers themselves are volatile in the function signature to work
342  * around a subtle bug in gcc 4.6+ which causes writes through
343  * pointers to volatile to not be emitted in some rare,
344  * never needed in real life, pieces of code.
345  */
346 int CRYPTO_memcmp(const volatile void * volatile in_a,
347                   const volatile void * volatile in_b,
348                   size_t len)
349 {
350     size_t i;
351     const volatile unsigned char *a = in_a;
352     const volatile unsigned char *b = in_b;
353     unsigned char x = 0;
354
355     for (i = 0; i < len; i++)
356         x |= a[i] ^ b[i];
357
358     return x;
359 }
360 #endif