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