a9f9697c70eda0ccae8e9ef7888fdc486f0f6068
[openssl.git] / crypto / cryptlib.c
1 /* crypto/cryptlib.c */
2 /* ====================================================================
3  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    openssl-core@openssl.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
56  * All rights reserved.
57  *
58  * This package is an SSL implementation written
59  * by Eric Young (eay@cryptsoft.com).
60  * The implementation was written so as to conform with Netscapes SSL.
61  *
62  * This library is free for commercial and non-commercial use as long as
63  * the following conditions are aheared to.  The following conditions
64  * apply to all code found in this distribution, be it the RC4, RSA,
65  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
66  * included with this distribution is covered by the same copyright terms
67  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
68  *
69  * Copyright remains Eric Young's, and as such any Copyright notices in
70  * the code are not to be removed.
71  * If this package is used in a product, Eric Young should be given attribution
72  * as the author of the parts of the library used.
73  * This can be in the form of a textual message at program startup or
74  * in documentation (online or textual) provided with the package.
75  *
76  * Redistribution and use in source and binary forms, with or without
77  * modification, are permitted provided that the following conditions
78  * are met:
79  * 1. Redistributions of source code must retain the copyright
80  *    notice, this list of conditions and the following disclaimer.
81  * 2. Redistributions in binary form must reproduce the above copyright
82  *    notice, this list of conditions and the following disclaimer in the
83  *    documentation and/or other materials provided with the distribution.
84  * 3. All advertising materials mentioning features or use of this software
85  *    must display the following acknowledgement:
86  *    "This product includes cryptographic software written by
87  *     Eric Young (eay@cryptsoft.com)"
88  *    The word 'cryptographic' can be left out if the rouines from the library
89  *    being used are not cryptographic related :-).
90  * 4. If you include any Windows specific code (or a derivative thereof) from
91  *    the apps directory (application code) you must include an acknowledgement:
92  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
93  *
94  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
95  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
96  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
97  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
98  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
99  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
100  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
101  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
102  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
103  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
104  * SUCH DAMAGE.
105  *
106  * The licence and distribution terms for any publically available version or
107  * derivative of this code cannot be changed.  i.e. this code cannot simply be
108  * copied and put under another distribution licence
109  * [including the GNU Public Licence.]
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECDH support in OpenSSL originally developed by
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116
117 #include "internal/cryptlib.h"
118 #include <openssl/safestack.h>
119
120 #if     defined(__i386)   || defined(__i386__)   || defined(_M_IX86) || \
121         defined(__INTEL__) || \
122         defined(__x86_64) || defined(__x86_64__) || \
123         defined(_M_AMD64) || defined(_M_X64)
124
125 extern unsigned int OPENSSL_ia32cap_P[4];
126 unsigned int *OPENSSL_ia32cap_loc(void)
127 {
128     return OPENSSL_ia32cap_P;
129 }
130
131 # if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
132 #include <stdio.h>
133 #  define OPENSSL_CPUID_SETUP
134 typedef uint64_t IA32CAP;
135 void OPENSSL_cpuid_setup(void)
136 {
137     static int trigger = 0;
138     IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
139     IA32CAP vec;
140     char *env;
141
142     if (trigger)
143         return;
144
145     trigger = 1;
146     if ((env = getenv("OPENSSL_ia32cap"))) {
147         int off = (env[0] == '~') ? 1 : 0;
148 #  if defined(_WIN32)
149         if (!sscanf(env + off, "%I64i", &vec))
150             vec = strtoul(env + off, NULL, 0);
151 #  else
152         if (!sscanf(env + off, "%lli", (long long *)&vec))
153             vec = strtoul(env + off, NULL, 0);
154 #  endif
155         if (off)
156             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~vec;
157         else if (env[0] == ':')
158             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
159
160         OPENSSL_ia32cap_P[2] = 0;
161         if ((env = strchr(env, ':'))) {
162             unsigned int vecx;
163             env++;
164             off = (env[0] == '~') ? 1 : 0;
165             vecx = strtoul(env + off, NULL, 0);
166             if (off)
167                 OPENSSL_ia32cap_P[2] &= ~vecx;
168             else
169                 OPENSSL_ia32cap_P[2] = vecx;
170         }
171     } else
172         vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
173
174     /*
175      * |(1<<10) sets a reserved bit to signal that variable
176      * was initialized already... This is to avoid interference
177      * with cpuid snippets in ELF .init segment.
178      */
179     OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10);
180     OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32);
181 }
182 # else
183 unsigned int OPENSSL_ia32cap_P[4];
184 # endif
185
186 #else
187 unsigned int *OPENSSL_ia32cap_loc(void)
188 {
189     return NULL;
190 }
191 #endif
192 int OPENSSL_NONPIC_relocated = 0;
193 #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ)
194 void OPENSSL_cpuid_setup(void)
195 {
196 }
197 #endif
198
199 #if (defined(_WIN32) || defined(__CYGWIN__)) && defined(_WINDLL)
200 # ifdef __CYGWIN__
201 /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
202 #  include <windows.h>
203 /*
204  * this has side-effect of _WIN32 getting defined, which otherwise is
205  * mutually exclusive with __CYGWIN__...
206  */
207 # endif
208
209 /*
210  * All we really need to do is remove the 'error' state when a thread
211  * detaches
212  */
213
214 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
215 {
216     switch (fdwReason) {
217     case DLL_PROCESS_ATTACH:
218         OPENSSL_cpuid_setup();
219 # if defined(_WIN32_WINNT)
220         {
221             IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *) hinstDLL;
222             IMAGE_NT_HEADERS *nt_headers;
223
224             if (dos_header->e_magic == IMAGE_DOS_SIGNATURE) {
225                 nt_headers = (IMAGE_NT_HEADERS *) ((char *)dos_header
226                                                    + dos_header->e_lfanew);
227                 if (nt_headers->Signature == IMAGE_NT_SIGNATURE &&
228                     hinstDLL !=
229                     (HINSTANCE) (nt_headers->OptionalHeader.ImageBase))
230                     OPENSSL_NONPIC_relocated = 1;
231             }
232         }
233 # endif
234         break;
235     case DLL_THREAD_ATTACH:
236         break;
237     case DLL_THREAD_DETACH:
238         break;
239     case DLL_PROCESS_DETACH:
240         break;
241     }
242     return (TRUE);
243 }
244 #endif
245
246 #if defined(_WIN32) && !defined(__CYGWIN__)
247 # include <tchar.h>
248 # include <signal.h>
249 # ifdef __WATCOMC__
250 #  if defined(_UNICODE) || defined(__UNICODE__)
251 #   define _vsntprintf _vsnwprintf
252 #  else
253 #   define _vsntprintf _vsnprintf
254 #  endif
255 # endif
256 # ifdef _MSC_VER
257 #  define alloca _alloca
258 # endif
259
260 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
261 int OPENSSL_isservice(void)
262 {
263     HWINSTA h;
264     DWORD len;
265     WCHAR *name;
266     static union {
267         void *p;
268         FARPROC f;
269     } _OPENSSL_isservice = {
270         NULL
271     };
272
273     if (_OPENSSL_isservice.p == NULL) {
274         HANDLE mod = GetModuleHandle(NULL);
275         if (mod != NULL)
276             _OPENSSL_isservice.f = GetProcAddress(mod, "_OPENSSL_isservice");
277         if (_OPENSSL_isservice.p == NULL)
278             _OPENSSL_isservice.p = (void *)-1;
279     }
280
281     if (_OPENSSL_isservice.p != (void *)-1)
282         return (*_OPENSSL_isservice.f) ();
283
284     h = GetProcessWindowStation();
285     if (h == NULL)
286         return -1;
287
288     if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
289         GetLastError() != ERROR_INSUFFICIENT_BUFFER)
290         return -1;
291
292     if (len > 512)
293         return -1;              /* paranoia */
294     len++, len &= ~1;           /* paranoia */
295     name = (WCHAR *)alloca(len + sizeof(WCHAR));
296     if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
297         return -1;
298
299     len++, len &= ~1;           /* paranoia */
300     name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
301 #  if 1
302     /*
303      * This doesn't cover "interactive" services [working with real
304      * WinSta0's] nor programs started non-interactively by Task Scheduler
305      * [those are working with SAWinSta].
306      */
307     if (wcsstr(name, L"Service-0x"))
308         return 1;
309 #  else
310     /* This covers all non-interactive programs such as services. */
311     if (!wcsstr(name, L"WinSta0"))
312         return 1;
313 #  endif
314     else
315         return 0;
316 }
317 # else
318 int OPENSSL_isservice(void)
319 {
320     return 0;
321 }
322 # endif
323
324 void OPENSSL_showfatal(const char *fmta, ...)
325 {
326     va_list ap;
327     TCHAR buf[256];
328     const TCHAR *fmt;
329 # ifdef STD_ERROR_HANDLE        /* what a dirty trick! */
330     HANDLE h;
331
332     if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
333         GetFileType(h) != FILE_TYPE_UNKNOWN) {
334         /* must be console application */
335         int len;
336         DWORD out;
337
338         va_start(ap, fmta);
339         len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
340         WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
341         va_end(ap);
342         return;
343     }
344 # endif
345
346     if (sizeof(TCHAR) == sizeof(char))
347         fmt = (const TCHAR *)fmta;
348     else
349         do {
350             int keepgoing;
351             size_t len_0 = strlen(fmta) + 1, i;
352             WCHAR *fmtw;
353
354             fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
355             if (fmtw == NULL) {
356                 fmt = (const TCHAR *)L"no stack?";
357                 break;
358             }
359             if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
360                 for (i = 0; i < len_0; i++)
361                     fmtw[i] = (WCHAR)fmta[i];
362             for (i = 0; i < len_0; i++) {
363                 if (fmtw[i] == L'%')
364                     do {
365                         keepgoing = 0;
366                         switch (fmtw[i + 1]) {
367                         case L'0':
368                         case L'1':
369                         case L'2':
370                         case L'3':
371                         case L'4':
372                         case L'5':
373                         case L'6':
374                         case L'7':
375                         case L'8':
376                         case L'9':
377                         case L'.':
378                         case L'*':
379                         case L'-':
380                             i++;
381                             keepgoing = 1;
382                             break;
383                         case L's':
384                             fmtw[i + 1] = L'S';
385                             break;
386                         case L'S':
387                             fmtw[i + 1] = L's';
388                             break;
389                         case L'c':
390                             fmtw[i + 1] = L'C';
391                             break;
392                         case L'C':
393                             fmtw[i + 1] = L'c';
394                             break;
395                         }
396                     } while (keepgoing);
397             }
398             fmt = (const TCHAR *)fmtw;
399         } while (0);
400
401     va_start(ap, fmta);
402     _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap);
403     buf[OSSL_NELEM(buf) - 1] = _T('\0');
404     va_end(ap);
405
406 # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
407     /* this -------------v--- guards NT-specific calls */
408     if (check_winnt() && OPENSSL_isservice() > 0) {
409         HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL"));
410
411         if (hEventLog != NULL) {
412             const TCHAR *pmsg = buf;
413
414             if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL,
415                              1, 0, &pmsg, NULL)) {
416 #if defined(DEBUG)
417                 /*
418                  * We are in a situation where we tried to report a critical
419                  * error and this failed for some reason. As a last resort,
420                  * in debug builds, send output to the debugger or any other
421                  * tool like DebugView which can monitor the output.
422                  */
423                 OutputDebugString(pmsg);
424 #endif
425             }
426
427             (void)DeregisterEventSource(hEventLog);
428         }
429     } else
430 # endif
431         MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
432 }
433 #else
434 void OPENSSL_showfatal(const char *fmta, ...)
435 {
436 #ifndef OPENSSL_NO_STDIO
437     va_list ap;
438
439     va_start(ap, fmta);
440     vfprintf(stderr, fmta, ap);
441     va_end(ap);
442 #endif
443 }
444
445 int OPENSSL_isservice(void)
446 {
447     return 0;
448 }
449 #endif
450
451 void OpenSSLDie(const char *file, int line, const char *assertion)
452 {
453     OPENSSL_showfatal
454         ("%s(%d): OpenSSL internal error, assertion failed: %s\n", file, line,
455          assertion);
456 #if !defined(_WIN32) || defined(__CYGWIN__)
457     abort();
458 #else
459     /*
460      * Win32 abort() customarily shows a dialog, but we just did that...
461      */
462 # if !defined(_WIN32_WCE)
463     raise(SIGABRT);
464 # endif
465     _exit(3);
466 #endif
467 }
468
469 int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len)
470 {
471     size_t i;
472     const unsigned char *a = in_a;
473     const unsigned char *b = in_b;
474     unsigned char x = 0;
475
476     for (i = 0; i < len; i++)
477         x |= a[i] ^ b[i];
478
479     return x;
480 }