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