1
/*********************************************************
2
* Copyright (C) 1998 VMware, Inc. All rights reserved.
4
* This file is part of VMware View Open Client.
6
* This program is free software; you can redistribute it and/or modify it
7
* under the terms of the GNU Lesser General Public License as published
8
* by the Free Software Foundation version 2.1 and no later version.
10
* This program is released with an additional exemption that
11
* compiling, linking, and/or using the OpenSSL libraries with this
14
* This program is distributed in the hope that it will be useful, but
15
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16
* or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public
17
* License for more details.
19
* You should have received a copy of the GNU Lesser General Public License
20
* along with this program; if not, write to the Free Software Foundation, Inc.,
21
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
23
*********************************************************/
26
#define _GNU_SOURCE /* dladdr */
37
#include "win32util.h"
38
#include "win32auth.h"
46
#include "vm_version.h"
54
#include "syncRecMutex.h"
61
#define LOGLEVEL_MODULE none
62
#include "loglevel_user.h"
64
#include "mallocTracker.h"
66
#include <openssl/err.h>
67
#include <openssl/ssl.h>
68
#include <openssl/rand.h>
69
#include <openssl/bio.h>
70
#include <openssl/pem.h>
71
#include <openssl/rsa.h>
72
#include <openssl/aes.h>
73
#include <openssl/des.h>
74
#include <openssl/crypto.h>
75
#include <openssl/md5.h>
76
#include <openssl/md4.h>
77
#include <openssl/pkcs12.h>
78
#include <openssl/x509v3.h>
80
#if defined(__APPLE__) && !defined(BORA_LINK_SSL_DIRECTLY)
81
#define BORA_LINK_SSL_DIRECTLY
84
// #define USE_SSL_DEBUG
86
#include "sslFunctionList.h"
88
struct SSLSockStruct {
92
Bool closeFdOnShutdown;
93
Bool connectionFailed;
96
#endif /*VMX86_DEVEL */
98
Bool loggedKernelReadBug;
101
#ifdef __APPLE_READ_BUG_WORKAROUND__
102
SSLLibHandleErrorHookFn *errorHook;
103
void *errorHookContext;
108
SyncRecMutex spinlock;
116
* The SSL wrapper functions
118
* This module loads all the SSL symbols we use at runtime from one of
119
* several possible locations. The symbols are stashed away in a set of
120
* function pointers, and exposed by static wrapper functions which call
121
* through these pointers and blow up semi-gracefully if the pointers are
124
* We use various tricks to make our wrapper functions appear to be the
125
* canonical SSL functions vis-a-vis the rest of the codebase. This gives
126
* us the best of both worlds: most code can happily call SSL functions
127
* by their normal names, but get invisibly redirected through our
130
* Unfortunately the implementation is somewhat complicated due to the
131
* differing conventions for symbol resolution on Windows vs. Linux,
132
* limitations of the C preprocessor for code generation, etc.
136
* Declare the global function pointers
138
* Define and use a list operator to generate function pointers of the
139
* form SSL_newFn, BIO_readFn, etc.
141
#define VMW_SSL_FUNC(_lib, _rettype, _func, _args, _argnames) \
142
_rettype (* _func##Fn) _args;
147
* Template for the wrapper function body. Just checks if the pointer is
148
* valid; if not, Panic(), otherwise, call through.
150
#define VMW_SSL_WRAPPER_BODY(_rettype, _retstmt, _func, _args, _argnames) \
151
_rettype VMW_SSL_WRAPPER_NAME(_func) _args { \
152
if (UNLIKELY(_func##Fn == NULL)) { \
153
Panic("SSL wrapper: invoked uninitialized function " #_func "!\n"); \
155
_retstmt _func##Fn _argnames; \
159
* Bring in sslWrapper.h to generate the wrapper bodies
161
#include "sslWrapper.h"
163
static char *SSLCertFile = NULL;
164
static char *SSLKeyFile = NULL;
165
static Bool SSLModuleInitialized = FALSE;
166
static int SSLVerifyParamIx = -1;
167
static SSLVerifyType SSLVerifySSLCertificates = SSL_VERIFY_CERTIFICATES_DEFAULT;
168
static char *SSLDHParamsFiles[2] = { NULL, NULL };
170
#define SERVER_CERT_FILE "rui.crt"
171
#define SERVER_KEY_FILE "rui.key"
172
#define SSL_DH512_FILE "dh512.pem"
173
#define SSL_DH1024_FILE "dh1024.pem"
176
#define SSL_LOG(x) LOG_DEVEL(x)
179
#endif /*USE_SSL_DEBUG*/
181
/* How long (ms) to wait before retrying a SSL_connect operation */
182
#define SSL_WAIT_TIME 100
184
/* How long (sec) to wait for data to be available on a socket during connect */
185
#define SSL_CONNECT_WAIT_TIMEOUT 120
187
static SSL_CTX *ssl_ctx = NULL;
188
static SyncMutex *ssl_locks = NULL;
189
#ifndef BORA_LINK_SSL_DIRECTLY
190
static void *libsslHandle;
191
static void *libcryptoHandle;
194
/* XXX: Cleanup SSL library configuration at some point. */
197
* Global config flag to control whether SSL_Accept fails if certificate loading
198
* fails. This is useful in cases where authentication is not required, but
201
static Bool requireCertificates = TRUE;
203
/* Used only for Windows. Don't care on other platforms. */
204
static Bool loadCertificatesFromFile = FALSE;
207
* OpenSSL cipher lists are colon, comma, or space delimited lists.
208
* To get a full list of ciphers:
209
* openssl ciphers | sed 's#:#\n#g'
211
#define SSL_CIPHER_LIST "AES256-SHA,AES128-SHA"
215
#define SOCKET_ERROR (-1)
220
SSL_SOCK_LOST_CONNECTION,
223
// XXX temporary hack for Win32 SCONS build
225
#ifndef FIPS_SIGS_NAME
226
#define FIPS_SIGS_NAME "fipsSigs.dat"
232
* Mac OS provides a crypto lib, so use the SDK's version
233
* unless explicitly overriden.
235
# include <openssl/opensslv.h>
236
# define LIBCRYPTO_SO_QUOTED "libcrypto." SHLIB_VERSION_NUMBER ".dylib"
237
# define LIBSSL_SO_QUOTED "libssl." SHLIB_VERSION_NUMBER ".dylib"
239
#else /* __APPLE__ */
241
* Ensure that the filenames for SSL libs are provided
242
* for Windows or Linux, and make sure they are quoted correctly.
244
# ifndef LIBCRYPTO_SO
245
# error Must provide LIBCRYPTO_SO filename
248
# error Must provide LIBSSL_SO filename
250
# define LIBCRYPTO_SO_QUOTED XSTR(LIBCRYPTO_SO)
251
# define LIBSSL_SO_QUOTED XSTR(LIBSSL_SO)
252
#endif /* __APPLE__ */
255
* On Linux we have either libXXX.so.0.9.8, or libXXX.so.6. 0.9.8
256
* is hidden somewhere in Makefiles and arrives here as
257
* LIBCRYPTO_SO on compiler command line (which is, BTW, completely
258
* broken as whole purpose of this file is to make sure nobody else
262
# define LIBCRYPTO_SO_ALT "libcrypto.so.6"
263
# define LIBCRYPTO_SO_ALT_2 "libcrypto.so"
264
# define LIBSSL_SO_ALT "libssl.so.6"
265
# define LIBSSL_SO_ALT_2 "libssl.so"
267
# define LIBCRYPTO_SO_ALT NULL
268
# define LIBCRYPTO_SO_ALT_2 NULL
269
# define LIBSSL_SO_ALT NULL
270
# define LIBSSL_SO_ALT_2 NULL
273
static SSL_CTX *SSLNewDefaultContext(void);
277
*----------------------------------------------------------------------
281
* Print out all the errors in the SSL error stack.
287
* Clears out the SSL error stack
289
*----------------------------------------------------------------------
296
while ((errNum = ERR_get_error())) {
297
Warning("SSL Error: %s\n", ERR_error_string(errNum, NULL));
303
*----------------------------------------------------------------------
307
* Prints out the cipher that is currently being used by
308
* the ssl connection.
315
*----------------------------------------------------------------------
319
SSLPrintCipher(SSL *ssl)
323
const char* cipher_name;
325
cipher = SSL_get_current_cipher(ssl);
326
SSL_CIPHER_get_bits(cipher, &bits);
329
* if cipher is null, OpenSSL dies!
331
if (cipher != NULL) {
332
cipher_name = SSL_CIPHER_get_name(cipher);
334
cipher_name = "undefined";
337
SSL_LOG(("Using cipher %s with %u bits\n", cipher_name, bits));
342
*----------------------------------------------------------------------
346
* Maps the ssl error state into an appropriate errno / WSA error.
353
*----------------------------------------------------------------------
357
SSLSetSystemError(int err)
360
case SSL_SOCK_WANT_RETRY:
362
WSASetLastError(WSAEWOULDBLOCK);
367
case SSL_SOCK_LOST_CONNECTION:
369
* no good way to know what the real error was (could have been
370
* a failure to load certificates in an accept), so return
374
WSASetLastError(WSAEACCES);
386
*----------------------------------------------------------------------
390
* Each ssl read / write could result in several reads and writes on
391
* the underlying socket. In this case the actual value for errno
392
* will not be correct. Manually setup the error value so that
393
* clients will do the right thing.
395
* XXX: Mapping the SSL_ERROR_WANT_<something> errors to a single error code
396
* is not good. Applications using non-blocking IO would not know whether
397
* they should put the FD in a read wait or a write wait. Note that SSL_read
398
* can return SSL_ERROR_WANT_WRITE and SSL_write may return
399
* SSL_ERROR_WANT_READ.
405
* errno / windows error might be set.
407
*----------------------------------------------------------------------
411
SSLSetErrorState(SSL *ssl,
414
int sslError = SSL_get_error(ssl, result);
417
SSL_LOG(("SSL: action success, %d bytes\n", result));
419
case SSL_ERROR_ZERO_RETURN:
420
SSL_LOG(("SSL: Zero return\n"));
422
case SSL_ERROR_WANT_READ:
423
SSL_LOG(("SSL: Want read\n"));
424
SSLSetSystemError(SSL_SOCK_WANT_RETRY);
426
case SSL_ERROR_WANT_WRITE:
427
SSL_LOG(("SSL: Want write\n"));
428
SSLSetSystemError(SSL_SOCK_WANT_RETRY);
430
case SSL_ERROR_WANT_X509_LOOKUP:
431
SSL_LOG(("SSL: want x509 lookup\n"));
433
case SSL_ERROR_SYSCALL:
434
SSL_LOG(("SSL: syscall error\n"));
437
Warning("SSL: Unknown SSL Error\n");
444
* Generic DLOPEN, DLSYM, and DLCLOSE macroes.
448
#define DLOPEN(x) (void *) Win32U_LoadLibrary(x)
449
#define DLCLOSE(x) FreeLibrary(x)
450
#define DLSYM(name, dllHandle) \
452
(FARPROC) name ## Fn = GetProcAddress((HMODULE)dllHandle, #name); \
453
if (name ## Fn == NULL) { \
454
SSL_LOG(("GetProcAddress: Failed to resolve %s: %d\n", #name, GetLastError())); \
458
#define DLOPEN(x) Posix_Dlopen(x, RTLD_LAZY | RTLD_GLOBAL)
459
#define DLCLOSE(x) dlclose(x)
460
#define DLSYM(name, dllHandle) \
463
name ## Fn = dlsym(dllHandle, #name); \
464
if ((error = dlerror()) != NULL) { \
465
SSL_LOG(("DLSYM: Failed to resolve %s: %s\n", #name, error)); \
471
#ifndef BORA_LINK_SSL_DIRECTLY
473
*----------------------------------------------------------------------
475
* SSLGetModulePath --
477
* Try and deduce the full path to the executable that is calling
478
* this function. Find it via /proc/ (2.2.x+ kernels). This call
481
* **NOTE: XXX This function is copied from bora/lib/user/hostinfo*.c
482
* in the main branch. This is the only function needed from
483
* lib/user so instead of linking that we copied the function
487
* The full path or NULL on failure.
490
* Memory is allocated.
492
*----------------------------------------------------------------------
496
SSLGetModulePath(void)
501
path = Win32U_GetModuleFileName(NULL);
504
Warning("%s: GetModuleFileName failed: %d\n", __FUNCTION__,
510
uid = Id_BeginSuperUser();
511
path = Posix_ReadLink("/proc/self/exe");
512
Id_EndSuperUser(uid);
515
Warning("%s: readlink failed: %s\n", __FUNCTION__, strerror(errno));
524
*----------------------------------------------------------------------
526
* SSLGetLibraryPath --
528
* Try and deduce the full path to the library in which we are.
529
* Implemented only on Linux, as it is only platform where we
533
* The full path or NULL on failure.
536
* Memory is allocated.
538
*----------------------------------------------------------------------
542
SSLGetLibraryPath(void)
547
if (dladdr(SSLGetLibraryPath, &info)) {
548
return Unicode_Alloc(info.dli_fname, STRING_ENCODING_DEFAULT);
558
*----------------------------------------------------------------------
560
* SSLOpenSystemLibrary --
562
* Tries to open system library - either libcrypto or libssl.
565
* The library handle on success, NULL on failure.
568
* Library loaded & verified.
570
*----------------------------------------------------------------------
574
SSLOpenSystemLibrary(const char *libname, // IN: library name
575
Bool doVersionCheck) // IN: is libcrypto and wants new version
580
* This doesn't actually load the system OpenSSL libraries on
581
* Windows since for LoadLibrary Windows always looks in the
582
* loading application's directory first.
585
libHandle = DLOPEN(libname);
587
long (*SSLeayFn)(void);
589
if (!doVersionCheck) {
593
DLSYM(SSLeay, libHandle);
598
* We require that the version is strictly equal to or greater than the
599
* one we compiled against - including the 'letter' version. The OpenSSL
600
* devs have a habit of breaking binary compatibility between minor releases.
601
* eg: BIO_clear_flags changed from a macro to a function at some point
602
* between 0.9.8b and 0.9.8g.
606
if (ver >= OPENSSL_VERSION_NUMBER) {
607
Log("Using system libcrypto, version %lX\n", ver);
610
Log("System %s library is older than our library (%lX < %lX)\n",
611
libname, ver, OPENSSL_VERSION_NUMBER);
620
*----------------------------------------------------------------------
622
* SSLOpenLibraryWithPath --
624
* Tries to open libcrypto/libssl library in directory where argument
628
* The library handle on success, NULL on failure.
633
*----------------------------------------------------------------------
637
SSLOpenLibraryWithPath(const char *fullPath, // IN: path
638
const char *libname) // IN: library name
645
/* Broken on Windows... */
646
pathEnd = strrchr(fullPath, DIRSEPC);
649
* No slash in path means that we will be loading
650
* system library. If you want that, do not pass
651
* no system library flag to SSLLoadSharedLIbrary....
655
sublen = pathEnd - fullPath;
657
libLocation = Str_Asprintf(NULL, "%*.*s%c%s", sublen, sublen, fullPath,
660
ASSERT_MEM_ALLOC(libLocation);
662
libHandle = DLOPEN(libLocation);
670
libLocation = Str_Asprintf(NULL, "%*.*s%clibdir%clib%c%s%c%s", sublen,
671
sublen, fullPath, DIRSEPC, DIRSEPC, DIRSEPC,
672
libname, DIRSEPC, libname);
674
ASSERT_MEM_ALLOC(libLocation);
676
libHandle = DLOPEN(libLocation);
688
*----------------------------------------------------------------------
692
* Gets the directory and name of a library and returns a handle to
693
* it. Panics if it can't be found.
695
* First try system library, then library in our libdir, then library
696
* in the app's directory, and finally (for devel builds only) bora-root.
699
* The library handle on success.
700
* Panic() on failure.
703
* Library loaded & verified.
705
*----------------------------------------------------------------------
709
SSLOpenLibrary(const char *libdir, // IN: directory with our libs
710
const char *libname, // IN: library name
711
const char *altLibName, // IN: alternative library name
712
const char *altLibName2, // IN: second alternative library name
713
Bool isLibCrypto, // IN: libname is libcrypto
714
Bool *system, // IN/OUT: TRUE => try system library
715
// FALSE => system library unusable
716
Bool doVersionCheck) // IN: Whether to version check the system library
724
* This doesn't actually load the system OpenSSL libraries on
725
* Windows since for LoadLibrary Windows always looks in the
726
* loading application's directory first.
729
libHandle = SSLOpenSystemLibrary(libname, isLibCrypto && doVersionCheck);
734
libHandle = SSLOpenSystemLibrary(altLibName, isLibCrypto && doVersionCheck);
740
libHandle = SSLOpenSystemLibrary(altLibName2, isLibCrypto && doVersionCheck);
745
/* System's libcrypto failed - do not attempt to use system's libssl */
751
* These fallback paths are not implemented on Mac OS because Apple
752
* guarantees that crypto libs are present (they are in the SDK).
753
* XXX It would be better to create a fallback in libdir
754
* XXX for crypto libs we ship. But for now stop here, because
755
* XXX SSLGetModulePath isn't implemented for __APPLE__
761
* try libdir/lib/libname-i386/libname or libdir/lib/libname-x86-64/libname
762
* and then libdir/lib/libname/libname then libdir/lib/libname
764
if (libdir != NULL) {
765
libLocation = Str_SafeAsprintf(NULL,
767
"%s%clib%c%s-x86-64%c%s",
769
"%s%clib%c%s-i386%c%s",
771
libdir, DIRSEPC, /* "lib" */ DIRSEPC, libname,
773
libHandle = DLOPEN(libLocation);
779
libLocation = Str_SafeAsprintf(NULL, "%s%clib%c%s%c%s", libdir, DIRSEPC,
780
/* "lib" */ DIRSEPC, libname, DIRSEPC,
782
libHandle = DLOPEN(libLocation);
788
libLocation = Str_SafeAsprintf(NULL, "%s%clib%c%s", libdir, DIRSEPC,
789
/* "lib" */ DIRSEPC, libname);
790
libHandle = DLOPEN(libLocation);
796
libLocation = Str_SafeAsprintf(NULL, "%s%c%s", libdir, DIRSEPC, libname);
797
libHandle = DLOPEN(libLocation);
804
fullpath = SSLGetLibraryPath();
806
libHandle = SSLOpenLibraryWithPath(fullpath, libname);
813
fullpath = SSLGetModulePath();
815
libHandle = SSLOpenLibraryWithPath(fullpath, libname);
822
#if defined(VMX86_DEVEL) && !defined(__APPLE__)
823
libLocation = Str_SafeAsprintf(NULL, "%s%s%s",
824
SSL_SRC_DIR, DIRSEPS, libname);
825
libHandle = DLOPEN(libLocation);
833
Panic("SSLLoadSharedLibrary: Failed to load library %s:%d\n",
834
libname, GetLastError());
836
Panic("SSLLoadSharedLibrary: Failed to load library %s:%s\n",
844
*----------------------------------------------------------------------
846
* SSLLoadSharedLibrary--
848
* Links in functions from the SSL library.
850
*----------------------------------------------------------------------
854
SSLLoadSharedLibrary(const char *libdir,
858
Bool system = useSystem;
860
libcryptoHandle = SSLOpenLibrary(libdir, LIBCRYPTO_SO_QUOTED, LIBCRYPTO_SO_ALT,
861
LIBCRYPTO_SO_ALT_2, TRUE, &system, doVersionCheck);
862
libsslHandle = SSLOpenLibrary(libdir, LIBSSL_SO_QUOTED, LIBSSL_SO_ALT,
863
LIBSSL_SO_ALT_2, FALSE, &system, doVersionCheck);
866
* Define a list operator to load each function we need and stash it in the
867
* appropriate function pointer. We Panic() if we can't load a symbol we
870
#define VMW_SSL_FUNC(_lib, _rettype, _func, _args, _argnames) \
871
DLSYM(_func, lib##_lib##Handle);
879
*----------------------------------------------------------------------
883
* Callback for adding two numbers atomically
885
* We need this so that SSL_new(ssl_ctx) can be
886
* re-entrant. Without this callback we would be unsafely
887
* incrementing the ref-count to the global ssl_ctx
889
* (see bug 105949 for more details)
893
* The new value of of *num.
895
*----------------------------------------------------------------------
899
SSLAddLockCb(int *num, // IN/OUT: number to be added
900
int amount, // IN: addend
901
int type, // IN: type of lock (ignored)
902
const char *file, // IN: file which called this method (for debugging)
903
int line) // IN: line in the file (for debugging)
905
// XXX: This might not be 64-bit safe
906
return Atomic_FetchAndAddUnfenced(Atomic_VolatileToAtomic(num), amount) +
912
*----------------------------------------------------------------------
916
* Callback invoked by SSL during a handshake in order to verify
917
* the peer certificate.
919
* Normally, the master SSL context would be given a certificate
920
* store with trusted certificates against which it would verify
921
* the peer certificate. Each time the peer certificate is
922
* checked, the callback will be invoked and the preverifyOk flag
923
* would be set to TRUE if the certificate was successfully
924
* verified. Otherwise the preverfyOk flag would be set to 0
925
* and the callback would be expected to do its own verification
926
* and decide whether to trust this certificate (by returning
929
* We employ two strategies to validate a certificate: 1)
930
* Thumbprint matching and 2) Signature checking.
932
* Thumbprint matching involves comparing the certificate's
933
* thumbprint to a client-specified thumbprint. If the two match,
934
* the certificate is validated, because the client already
935
* expected to see this certificate (this is the SSH model). If
936
* the thumbprints don't match we proceed to the second approach
937
* of checking the signer's signature.
939
* Signature checking is only implemented on Windows at the
942
* On Win32, rather than providing OpenSSL with the trusted
943
* certificates, we simply handle this callback and check the
944
* peer certificate against the default Win32 certificate store
945
* of trusted certifactes.
947
* The Posix implementation is at present omitted, but in the
948
* future it may or may not follow the same strategy as the Win32
951
*----------------------------------------------------------------------
955
SSLVerifyCb(int preverifyOk, X509_STORE_CTX *storeCtx)
958
SSLVerifyParam *verifyParam;
962
* Obtain the parameters we need in verification.
964
* Note that the current certificate that is being checked will
965
* always be the peer certificate, since we did not provide OpenSSL
966
* with a trusted certificate list
969
ssl = (SSL *) X509_STORE_CTX_get_ex_data(
970
storeCtx, SSL_get_ex_data_X509_STORE_CTX_idx());
972
verifyParam = (SSLVerifyParam *) SSL_get_ex_data(ssl, SSLVerifyParamIx);
973
cert = X509_STORE_CTX_get_current_cert(storeCtx);
975
return SSL_VerifyX509(verifyParam, cert) ? 1 : 0;
981
*----------------------------------------------------------------------
985
* Callback for locking for use by OpenSSL.
987
* OpenSSL requires setting of a locking callback function in
988
* multi-threaded applications.
989
* The SyncMutex_XXX calls can reset error numbers, so save
990
* them and restore back
992
*----------------------------------------------------------------------
996
SSLLockingCb(int mode, // indicates locking or unlocking
998
const char *file, // file name
999
int line) // line number
1002
int savederr = GetLastError();
1004
int savederr = errno;
1007
if (!SSLModuleInitialized) {
1011
if (CRYPTO_LOCK & mode) {
1012
SyncMutex_Lock(&ssl_locks[n]);
1013
} else if (CRYPTO_UNLOCK & mode) {
1014
SyncMutex_Unlock(&ssl_locks[n]);
1018
SetLastError(savederr);
1026
*----------------------------------------------------------------------
1028
* SSLTmpDHCallback --
1030
* Callback for DH key exchange. Initializes the DH parameters
1031
* from the configuration files, if not already initialized.
1034
* DH parameter for use by OpenSSL. NULL on failure.
1039
*----------------------------------------------------------------------
1043
SSLTmpDHCallback(SSL *ssl, // IN: unused
1044
int is_export, // IN: Export restricted?
1045
int keylength) // IN: Length of key to be returned.
1047
static DH *dh512 = NULL;
1048
static DH *dh1024 = NULL;
1050
if (!dh512 || !dh1024) {
1051
BIO *bio = SSL_BIO_new_file(SSLDHParamsFiles[0], "r");
1053
dh512 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1055
Warning("Error reading DH parameter file");
1059
Warning("Error opening DH parameter file");
1062
bio = SSL_BIO_new_file(SSLDHParamsFiles[1], "r");
1064
dh1024 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1066
Warning("Error reading DH parameter file");
1070
Warning("Error opening DH parameter file");
1074
return (keylength == 512) ? dh512 : dh1024;
1079
*----------------------------------------------------------------------
1083
* Callback for current thread id for use by OpenSSL.
1085
* OpenSSL requires setting of a thread id callback function in
1086
* multi-threaded applications.
1088
*----------------------------------------------------------------------
1091
static unsigned long
1094
return (unsigned long)Util_GetCurrentThreadId();
1099
*----------------------------------------------------------------------
1103
* Initializes the SSL library and prepares the session context.
1104
* getLibFn is a function which is able to return the location of
1105
* the SSL libraries. default and name are arguments to getLibFn.
1113
*----------------------------------------------------------------------
1117
SSL_InitEx(SSLLibFn *getLibFn,
1118
const char *defaultLib,
1121
Bool doVersionCheck,
1122
Bool disableLoading)
1125
/*Silently ignore any attempts to initialize module more than once*/
1126
if (!SSLModuleInitialized) {
1128
#ifdef BORA_LINK_SSL_DIRECTLY
1130
* On the Mac, we directly link the ssl libraries, so there's no
1131
* need to dlopen and load the symbols.
1133
BEGIN_NO_STACK_MALLOC_TRACKER;
1134
BEGIN_NO_MALLOC_TRACKER;
1137
BEGIN_NO_STACK_MALLOC_TRACKER;
1139
BEGIN_NO_MALLOC_TRACKER;
1140
if (disableLoading) {
1142
* If SSL libraries are already loaded, then setup the function
1146
libcryptoHandle = GetModuleHandle(LIBCRYPTO_SO_QUOTED);
1147
ASSERT(libcryptoHandle);
1148
libsslHandle = GetModuleHandle(LIBSSL_SO_QUOTED);
1149
ASSERT(libsslHandle);
1151
void *procHandle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
1152
void *thislibHandle = dlopen("libVICFbase.so", RTLD_LAZY | RTLD_GLOBAL);
1153
void *thisFn = dlsym(thislibHandle, "SSL_library_init");
1154
void *globalFn = dlsym(procHandle, "SSL_library_init");
1156
ASSERT(thislibHandle);
1160
if (thisFn == globalFn) {
1161
globalFn = dlsym(RTLD_NEXT, "SSL_library_init");
1162
libsslHandle = RTLD_NEXT;
1164
if (thisFn == globalFn || globalFn == NULL) {
1165
SSL_LOG(("Failed to locate libssl symbols.\n"));
1166
Panic("Failed to locate libssl symbols.\n");
1169
thisFn = dlsym(thislibHandle, "CRYPTO_num_locks");
1170
globalFn = dlsym(procHandle, "CRYPTO_num_locks");
1171
if (thisFn == globalFn) {
1172
thisFn = dlsym(RTLD_NEXT, "CRYPTO_num_locks");
1173
libcryptoHandle = RTLD_NEXT;
1175
if (thisFn == globalFn || globalFn == NULL) {
1176
SSL_LOG(("Failed to locate libcrypto symbols.\n"));
1177
Panic("Failed to locate libcrypto symbols.\n");
1180
dlclose(thislibHandle);
1183
* Define a list operator to load each function we need and stash it in the
1184
* appropriate function pointer. We Panic() if we can't load a symbol we
1187
#define VMW_SSL_FUNC(_lib, _rettype, _func, _args, _argnames) \
1188
DLSYM(_func, lib##_lib##Handle);
1193
libdir = (getLibFn)(defaultLib, name);
1195
libdir = defaultLib ? strdup(defaultLib) : NULL;
1197
// We check if libdir is valid in SSLLoadSharedLibrary
1198
SSLLoadSharedLibrary(libdir,
1199
CryptoFips_FipsModeEnabled() ? FALSE : useSystem,
1205
SSL_load_error_strings();
1206
END_NO_MALLOC_TRACKER;
1209
* Force the PRNG to be initialized early, as opposed to at the
1210
* time when the SSL connection is made. A call to RAND_status
1211
* forces this initialization to happen. Initializing the PRNG
1212
* as early as possible in the process makes it take much less
1213
* time (e.g. 1sec. vs. sometimes 20sec.) compared to
1214
* initializing it later in the process, as may be the case on
1215
* the first SSL_accept() or SSL_connect(). That's because the
1216
* PRNG initialization walks the process heap and the total heap
1217
* is smaller at startup.
1219
* If SSL_InitEx could not be called early enough in the
1220
* process, then the caller could just call RAND_status() by
1221
* itself. Only the first call to RAND_status will have the side
1222
* effect of initializing the PRNG, so calling it subsequently
1228
numSslLocks = CRYPTO_num_locks();
1229
ssl_locks = (SyncMutex *)malloc(sizeof(struct SyncMutex) * numSslLocks);
1230
for (i = 0;i < numSslLocks; ++i) {
1231
SyncMutex_Init(&ssl_locks[i], NULL);
1234
CRYPTO_set_locking_callback(SSLLockingCb);
1235
CRYPTO_set_id_callback(SSLThreadIdCb);
1239
* Only peform additional initialization tasks if not compiled
1240
* inside vmcryptolib, because vmcryptolib itself does not need
1241
* to set-up networking.
1244
if (!CryptoFips_InVmcryptolib()) {
1245
CRYPTO_set_add_lock_callback(SSLAddLockCb);
1249
* Force the initialization of ssl_ctx, in case anyone is using it without
1250
* going through one of our functions.
1253
ssl_ctx = SSLNewDefaultContext();
1255
SSL_LOG(("SSL: default ctx created\n"));
1256
SSL_LOG(("Initializing default ssl context: %p\n", ctx));
1259
SSLCertFile = W32Util_GetInstalledFilePath("\\ssl\\" SERVER_CERT_FILE);
1260
SSLKeyFile = W32Util_GetInstalledFilePath("\\ssl\\" SERVER_KEY_FILE);
1261
SSLDHParamsFiles[0] = W32Util_GetInstalledFilePath("\\ssl\\"
1263
SSLDHParamsFiles[1] = W32Util_GetInstalledFilePath("\\ssl\\"
1266
SSLCertFile = strdup(VMWARE_HOST_DIRECTORY "/ssl/" SERVER_CERT_FILE);
1267
SSLKeyFile = strdup(VMWARE_HOST_DIRECTORY "/ssl/" SERVER_KEY_FILE);
1268
SSLDHParamsFiles[0] = strdup(VMWARE_HOST_DIRECTORY "/ssl/"
1270
SSLDHParamsFiles[1] = strdup(VMWARE_HOST_DIRECTORY "/ssl/"
1273
ASSERT_MEM_ALLOC(SSLCertFile);
1274
ASSERT_MEM_ALLOC(SSLKeyFile);
1275
ASSERT_MEM_ALLOC(SSLDHParamsFiles[0]);
1276
ASSERT_MEM_ALLOC(SSLDHParamsFiles[1]);
1278
SSLModuleInitialized = TRUE;
1280
END_NO_STACK_MALLOC_TRACKER;
1286
*----------------------------------------------------------------------
1290
* Initializes the SSL library and prepares the session context.
1291
* getLibFn is a function which is able to return the location of
1292
* the SSL libraries. default and name are arguments to getLibFn.
1300
*----------------------------------------------------------------------
1304
SSL_Init(SSLLibFn *getLibFn, const char *defaultLib, const char *name)
1306
SSL_InitEx(getLibFn, defaultLib, name, TRUE, TRUE, FALSE);
1311
*----------------------------------------------------------------------
1312
* SSLNewDefaultContext --
1314
* Return an SSL context initialized with reasonable defaults.
1315
*----------------------------------------------------------------------
1319
SSLNewDefaultContext(void)
1323
ctx = SSL_CTX_new(CryptoFips_FipsModeEnabled() ?
1324
TLSv1_method() : SSLv23_method());
1328
Panic("Error Starting Up Default SSL context\n");
1333
* Disable SSLv2 and enable all known bug workarounds.
1335
SSL_CTX_set_options(ctx,
1336
SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_SINGLE_DH_USE);
1339
* Automatically retry an operation that failed with
1340
* SSL_WANT_{READ|WRITE} if blocking sockets are being used
1342
* This flag is ineffective for non-blocking sockets and the
1343
* application must retry the SSL IO operation that needs to be retried
1344
* until it succeeds, before it can perform any other IO on the
1347
SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, SSL_MODE_AUTO_RETRY, NULL);
1349
/* Don't cache sessions (client not smart enough to use them */
1350
SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SESS_CACHE_MODE,
1351
SSL_SESS_CACHE_OFF, NULL);
1353
* disable the bidirectional shutdown sequence. This is really
1354
* only useful when we want to use SSL session caching.
1355
* (a session will only be cached if it was shutdown properly,
1356
* using the full bidirectional method).
1358
SSL_CTX_set_quiet_shutdown(ctx, 1);
1361
* Set the cipher for the context. All sessions initiated from this
1362
* context will use the same cipher. Use the SSL_set_cipher_list to
1363
* change the cipher on a per session basis.
1365
SSL_CTX_set_cipher_list(ctx, SSL_CIPHER_LIST);
1368
* Initialize the callback for use with cipher suites using Diffie-Hellman.
1370
SSL_CTX_set_tmp_dh_callback(ctx, SSLTmpDHCallback);
1373
* Create a new slot (index) where we can store a pointer to the
1374
* SSLVerifyParam data structure
1376
SSLVerifyParamIx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1383
*----------------------------------------------------------------------
1384
* SSL_DefaultContext --
1386
* Returns the global default SSL context. SSL_Init[Ex] must have been
1387
* called before calling this.
1388
*----------------------------------------------------------------------
1392
SSL_DefaultContext(void)
1394
ASSERT(SSLModuleInitialized);
1395
return (void *)ssl_ctx;
1400
*----------------------------------------------------------------------
1402
* SSL_SetVerifySSLCertificates --
1404
* Sets a global option to verify or not verify peeer SSL
1407
*----------------------------------------------------------------------
1411
SSL_SetVerifySSLCertificates(SSLVerifyType verify)
1413
SSLVerifySSLCertificates = verify;
1418
*----------------------------------------------------------------------
1420
* SSL_GetVerifySSLCertificates --
1422
* Returns the global option that determines whether peer SSL
1423
* certificates should be verified
1425
*----------------------------------------------------------------------
1429
SSL_GetVerifySSLCertificates(void)
1431
return SSLVerifySSLCertificates;
1436
*----------------------------------------------------------------------
1438
* SSL_VerifyX509Cert --
1440
* Stock implementation for most of the SSLVerifyCb that is
1441
* passed to SSL_set_verify.
1443
* This function assumes that the second argument is of type
1444
* X509, however since the ssl.h header currently does not
1445
* include any OpenSSL headers, we cannot specify this type
1449
* TRUE - if the verification succeeded, and FALSE otherwise. The
1450
* verification error is stored in the SSLVerifyParam argument
1452
*----------------------------------------------------------------------
1456
SSL_VerifyX509(SSLVerifyParam *verifyParam, void *x509Cert)
1458
X509 *cert = (X509 *) x509Cert;
1459
unsigned char md[EVP_MAX_MD_SIZE];
1460
unsigned int mdLen = 0; /* initialize per bug 286415 */
1461
char thumbprintString[SSL_V_THUMBPRINT_STRING_SIZE] = {0};
1463
char *pp = thumbprintString;
1465
verifyParam->selfSigned =
1466
!X509_NAME_cmp(X509_get_subject_name(cert), X509_get_issuer_name(cert));
1467
verifyParam->hasError = FALSE;
1470
* Compute the thumbprint of the cert and convert it to a string.
1471
* Yes, we also have to check mdLen on "success", see 286415;
1472
* X509_digest has a bug whereby it doesn't check the return value
1473
* of functions it calls that are supposed to fill in mdLen, so it
1474
* could return TRUE without having touched mdLen.
1476
if (!X509_digest(cert, EVP_sha1(), md, &mdLen) || (0 == mdLen)) {
1480
for (ii = 0; ii < (int) mdLen; ii++) {
1481
if (pp - thumbprintString < SSL_V_THUMBPRINT_STRING_SIZE-3) {
1482
snprintf(pp, 4, (ii == 0) ? "%02X" : ":%02X", md[ii]);
1483
pp += (ii == 0) ? 2 : 3;
1488
* If there was a certificate thumbprint provided, we try to match
1489
* it with the thumbprint for cert. Otherwise we fall back to the
1490
* conventional way of verifying the certificate. In any case, we
1491
* store its thumbprint in verifyParam->thumbprintString
1493
if (strncmp(thumbprintString,
1494
verifyParam->thumbprintString,
1495
SSL_V_THUMBPRINT_STRING_SIZE) == 0) {
1497
* The request certificate signature matched the actual
1498
* certificate signature. The user already knew about this
1499
* certificate and was OK with it.
1505
* Copy the actual thumbprint into the SSL verify param and proceed
1506
* with regular certificate verification
1508
strncpy(verifyParam->thumbprintString, thumbprintString, SSL_V_THUMBPRINT_STRING_SIZE);
1512
unsigned char *certBytes = NULL;
1518
* Convert the OpenSSL certificate in 'currentCert' into a Win32
1519
* ceritificate context so we can use it with the Win32 CertXxx
1520
* APIs. We do this by first encoding the OpenSSL certificate into
1521
* a buffer of bytes and then we use that buffer to create a Win32
1522
* certificate context
1525
certLen = i2d_X509(cert, NULL);
1526
certBytes = pp = (unsigned char *) malloc(certLen);
1527
ASSERT_MEM_ALLOC(certBytes);
1528
i2d_X509(cert, &pp);
1530
verifyParam->hasError =
1531
!SSLVerifyCertAgainstSystemStore(certBytes, certLen, verifyParam);
1532
if (certBytes != NULL) {
1536
return !verifyParam->hasError;
1538
#else // #ifdef WIN32
1539
if (SSL_GetVerifySSLCertificates() == SSL_VERIFY_CERTIFICATES_ON) {
1541
* On Linux, we have not implemented yet a way to verify certificate
1542
* signatures against a set of trusted root CA certificates. However,
1543
* we could do certificate verification based on the certificate's
1546
* Therefore if SSL cert verification is turned on, we are using the
1547
* thumbprint matching approach to verify certs. Furthermore, if we got
1548
* this far, the thumbprints did not match, so we indicate that the
1549
* verification has failed
1554
X509_NAME_get_text_by_NID(X509_get_subject_name(cert), NID_commonName,
1555
peerCN, sizeof peerCN);
1557
Warning("SSL_VerifyX509: Thumbprint mismatch for certificate "
1558
"with subject name: %s, %s\n", peerCN, thumbprintString);
1563
* The default verification action on Linux is to not verify SSL
1564
* certificates, so we just return TRUE here.
1570
#endif // #ifdef WIN32
1575
*----------------------------------------------------------------------
1579
* Sets the ciphers to use for the default context. Overrides the
1580
* default cipher information. This function should be called after
1583
*----------------------------------------------------------------------
1587
SSL_SetCiphers(const char *ciphers) // IN: Cipher suite list
1589
ASSERT(ciphers != NULL);
1590
ASSERT(SSLModuleInitialized);
1592
SSL_CTX_set_cipher_list(SSL_DefaultContext(), ciphers);
1597
*----------------------------------------------------------------------
1601
* Sets the certificates and private key to use for the default
1602
* context. Overrides the default cert and key information. This
1603
* function should be called after SSL_Init.
1605
*----------------------------------------------------------------------
1609
SSL_SetCerts(const char *certFile, // IN: Certificate file
1610
const char *keyFile) // IN: Private Key File
1612
ASSERT(certFile != NULL || keyFile != NULL);
1613
ASSERT(SSLModuleInitialized);
1615
if (certFile != NULL) {
1617
SSLCertFile = strdup(certFile);
1618
ASSERT_MEM_ALLOC(SSLCertFile);
1621
if (keyFile != NULL) {
1623
SSLKeyFile = strdup(keyFile);
1624
ASSERT_MEM_ALLOC(SSLKeyFile);
1630
*----------------------------------------------------------------------
1634
* Destroys the default SSL session context.
1642
*----------------------------------------------------------------------
1648
if (SSLModuleInitialized) {
1649
int numSslLocks = CRYPTO_num_locks(), i;
1651
BEGIN_NO_STACK_MALLOC_TRACKER;
1653
CRYPTO_set_locking_callback(NULL);
1654
SSL_CTX_free(ssl_ctx);
1658
* Disable callbacks, or bad surprise happens when threads exit
1659
* after SSL gets shut down, even if these threads have nothing
1662
CRYPTO_set_add_lock_callback(NULL);
1663
CRYPTO_set_locking_callback(NULL);
1665
for (i = 0; i < numSslLocks; ++i) {
1666
SyncMutex_Destroy(&ssl_locks[i]);
1671
SSLModuleInitialized = FALSE;
1674
free(SSLDHParamsFiles[0]);
1675
free(SSLDHParamsFiles[1]);
1678
SSLDHParamsFiles[0] = NULL;
1679
SSLDHParamsFiles[1] = NULL;
1680
END_NO_STACK_MALLOC_TRACKER;
1687
*----------------------------------------------------------------------
1689
* SSLGetFileContents()
1691
* Given a file handle, allocate a buffer the size of the file and
1692
* reads the entire file contents into it.
1694
* On success, caller is responsible for deallocating the allocated
1698
* TRUE if successful, FALSE otherwise.
1703
*----------------------------------------------------------------------
1707
SSLGetFileContents(HANDLE hFile, // IN
1708
char **contents, // OUT
1711
int bytesRead, fileSize;
1714
fileSize = GetFileSize(hFile, NULL);
1715
if (fileSize == INVALID_FILE_SIZE) {
1719
buf = (char *)malloc(fileSize);
1721
Warning("Unable to allocate buffer.\n");
1725
if (!ReadFile(hFile, buf, fileSize, &bytesRead, NULL)) {
1729
ASSERT(bytesRead == fileSize);
1741
*----------------------------------------------------------------------
1743
* SSLCreateMemoryBIOFromFile --
1745
* Given a file handle, creates and memory BIO and populate it with
1746
* contents of the file.
1748
* On success, caller is responsible for deallocating the create
1752
* TRUE if successful, FALSE otherwise.
1757
*----------------------------------------------------------------------
1761
SSLCreateMemoryBIOFromFile(HANDLE hFile)
1767
bio = BIO_new(BIO_s_mem());
1769
Warning("Create BIO failed.\n");
1773
if (!SSLGetFileContents(hFile, &buf, &size)) {
1774
Warning("Unable to read file.\n");
1778
if (BIO_write(bio, buf, size) <= 0) { //VCV|C
1779
Warning("Unable to write to BIO.\n");
1786
Warning("Create Memory BIO succeeded.\n");
1795
*----------------------------------------------------------------------
1797
* SSLCreateMemoryBIOFromBuffer()
1799
* Given a buffer, creates and memory BIO and populate it with
1800
* contents of the buffer.
1802
* On success, caller is responsible for deallocating the create
1806
* TRUE if successful, FALSE otherwise.
1811
*----------------------------------------------------------------------
1815
SSLCreateMemoryBIOFromBuffer(char *buffer,
1820
bio = BIO_new(BIO_s_mem());
1822
Warning("Create BIO failed.\n");
1827
if (BIO_write(bio, buffer, size) <= 0) {
1828
Warning("Unable to write to BIO.\n");
1834
// SSL_LOG(("SSL: Create Memory BIO succeeded for buffer: %s\n", buffer));
1841
*----------------------------------------------------------------------
1843
* SSLLoadCertificatesFromFile()
1845
* Loads the server's certificate & private key from disk, setting
1846
* them up for use by the default context.
1847
* The ssl directory should be readable only by a privileged user,
1848
* so must become root / __vmware_user__.
1851
* TRUE on succes, FALSE on failure.
1855
*----------------------------------------------------------------------
1860
SSLLoadCertificatesFromFile(void)
1862
Bool success = FALSE;
1863
char *certFile = SSLCertFile;
1864
char *keyFile = SSLKeyFile;
1866
SSL_CTX *ctx = SSL_DefaultContext();
1868
uid = Id_BeginSuperUser();
1870
/* Loads certificate */
1871
SSL_LOG(("SSL: Loading certificate: '%s' ...\n", certFile));
1872
if (!SSL_CTX_use_certificate_file(ctx, certFile, SSL_FILETYPE_PEM)) {
1874
Warning("Error loading server certificate\n");
1877
SSL_LOG(("SSL: server certificate read\n"));
1879
/* Loads private key */
1880
SSL_LOG(("SSL: Loading private key: '%s' ...\n", keyFile));
1881
if (!SSL_CTX_use_PrivateKey_file(ctx, keyFile, SSL_FILETYPE_PEM)) {
1883
Warning("Error loading server certificate\n");
1886
SSL_LOG(("SSL: server private key read\n"));
1888
if (!SSL_CTX_check_private_key(ctx)) {
1890
Warning("Error verifying server certificate\n");
1893
SSL_LOG(("SSL: server certificate verified\n"));
1898
Id_EndSuperUser(uid);
1905
*----------------------------------------------------------------------
1907
* SSLLoadCertificatesFromStore()
1909
* Loads the server's certificate & private key from system certificate
1910
* store on Windows, setting them up for use by the default context.
1913
* TRUE on succes, FALSE on failure.
1917
*----------------------------------------------------------------------
1923
SSLLoadCertificatesFromStore(void)
1925
Bool success = FALSE;
1926
char *certFile = SSLCertFile;
1927
char *keyFile = SSLKeyFile;
1931
EVP_PKEY *pkey = NULL;
1932
SSL_CTX *ctx = SSL_DefaultContext();
1934
/* Loads certificate */
1935
SSL_LOG(("SSL: Loading certificate: '%s' ...\n", certFile));
1937
* Windows 2003 Server introduces the "Impersonate a client after
1938
* authentication right", which we don't have by default. So we go back
1939
* and ask authd to open the certificate and private key files for us.
1941
hFile = W32Auth_OpenSecurable(W32AuthSecurableFile, certFile,
1942
GENERIC_READ | GENERIC_WRITE, 0,
1943
OPEN_EXISTING, FILE_ATTRIBUTE_READONLY);
1944
if (hFile == INVALID_HANDLE_VALUE) {
1945
Warning("Error opening server certificate\n");
1949
bio = SSLCreateMemoryBIOFromFile(hFile);
1952
hFile = INVALID_HANDLE_VALUE;
1955
Warning("Error reading server certificate data\n");
1959
x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1961
Warning("Error reading server certificate from BIO\n");
1969
if (!SSL_CTX_use_certificate(ctx, x509)) {
1972
Warning("Error loading server certificate\n");
1976
SSL_LOG(("SSL: server certificate read\n"));
1978
/* Loads private key */
1979
SSL_LOG(("SSL: Loading private key: '%s' ...\n", keyFile));
1980
hFile = W32Auth_OpenSecurable(W32AuthSecurableFile, keyFile,
1981
GENERIC_READ | GENERIC_WRITE, 0,
1982
OPEN_EXISTING, FILE_ATTRIBUTE_READONLY);
1983
if (hFile == INVALID_HANDLE_VALUE) {
1984
Warning("Error opening server private key\n");
1989
bio = SSLCreateMemoryBIOFromFile(hFile);
1991
hFile = INVALID_HANDLE_VALUE;
1993
Warning("Error reading server private key data\n");
1997
pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
1999
Warning("Error reading server private key from BIO\n");
2006
if (!SSL_CTX_use_PrivateKey(ctx, pkey)) {
2007
EVP_PKEY_free(pkey);
2009
Warning("Error reading server private key\n");
2012
EVP_PKEY_free(pkey);
2013
SSL_LOG(("SSL: server private key read\n"));
2015
if (!SSL_CTX_check_private_key(ctx)) {
2017
Warning("Error verifying server certificate\n");
2020
SSL_LOG(("SSL: server certificate verified\n"));
2033
*----------------------------------------------------------------------
2035
* SSLLoadCertificates()
2036
* Loads the server SSL certificate and private key.
2039
* TRUE on success, FALSE otherwise
2043
*----------------------------------------------------------------------
2047
SSLLoadCertificates(Bool fromFile)
2051
return SSLLoadCertificatesFromStore();
2054
return SSLLoadCertificatesFromFile();
2059
*----------------------------------------------------------------------
2065
* Returns a freshly allocated SSLSock structure.
2069
*----------------------------------------------------------------------
2074
Bool closeFdOnShutdown)
2076
SSLSock sslConnection;
2079
sslConnection = (SSLSock)calloc(1, sizeof(struct SSLSockStruct));
2080
ASSERT_MEM_ALLOC(sslConnection);
2081
sslConnection->fd = fd;
2082
sslConnection->closeFdOnShutdown = closeFdOnShutdown;
2084
sslConnection->initialized = 12345;
2085
#endif /*VMX86_DEVEL*/
2086
ret = SyncRecMutex_Init(&sslConnection->spinlock, NULL);
2087
ASSERT_NOT_IMPLEMENTED(ret == TRUE);
2088
return sslConnection;
2093
*----------------------------------------------------------------------
2097
* Initiates an SSL connection using current SSL context.
2099
* XXX should modify callers of this to code to check for
2102
* Callers of this function don't expect an error, so cache failures
2103
* for later reporting during an SSL{Read|Write}.
2106
* Returns TRUE on success, FALSE on failure.
2110
*----------------------------------------------------------------------
2114
SSL_Connect(SSLSock sSock) // IN: SSL socket
2116
Warning("SSL_Connect: SECURITY WARNING: Should use SSL_ConnectAndVerify instead\n");
2117
return SSL_ConnectAndVerify(sSock, NULL);
2122
*----------------------------------------------------------------------
2124
* SSL_ConnectAndVerify()
2126
* Similar to SSL_Connect, but allows for verification of
2127
* peer-certificate. Verification is turned on if the verifyParam
2128
* is non-NULL, in which case the verifyParam data structure
2129
* stores input and output parameters for the verification. Uses
2130
* the default context.
2132
*----------------------------------------------------------------------
2136
SSL_ConnectAndVerify(SSLSock sSock, // IN: SSL socket
2137
SSLVerifyParam *verifyParam) // IN: Certificate validation parameters
2139
return SSL_ConnectAndVerifyWithContext(sSock, verifyParam, SSL_DefaultContext());
2144
*----------------------------------------------------------------------
2146
* SSL_ConnectAndVerifyWithContext()
2148
* Similar to SSL_Connect, but allows for verification of
2149
* peer-certificate. Verification is turned on if the verifyParam
2150
* is non-NULL, in which case the verifyParam data structure
2151
* stores input and output parameters for the verification.
2153
*----------------------------------------------------------------------
2156
Bool SSL_ConnectAndVerifyWithContext(SSLSock sSock, // IN: SSL socket
2157
SSLVerifyParam *verifyParam, // IN: Certification validation parameters
2158
void *ctx) // IN: OpenSSL context (SSL_CTX *)
2163
ASSERT_BUG(37562, SSLModuleInitialized);
2166
ASSERT_DEVEL(sSock->initialized == 12345);
2168
BEGIN_NO_STACK_MALLOC_TRACKER;
2170
sSock->sslCnx = SSL_new(ctx);
2171
if (!sSock->sslCnx) {
2173
Warning("Error creating sslCnx from ctx\n");
2174
sSock->connectionFailed = TRUE;
2178
SSL_set_connect_state(sSock->sslCnx);
2180
if (verifyParam != NULL) {
2181
// Verify server-side certificates:
2182
SSL_set_ex_data(sSock->sslCnx, SSLVerifyParamIx, verifyParam);
2183
SSL_set_verify(sSock->sslCnx, SSL_VERIFY_PEER, SSLVerifyCb);
2186
SSL_LOG(("SSL: connect, ssl created %d\n", sSock->fd));
2187
if (!SSL_set_fd(sSock->sslCnx, sSock->fd)) {
2189
Warning("Error setting fd for SSL connection\n");
2190
sSock->connectionFailed = TRUE;
2194
SSL_LOG(("SSL: connect fd set done\n"));
2196
/* XXX Because we use non blocking sockets, it could be that
2197
* SSL_connect will return without finishing (because either
2198
* a read or write on the socket couldn't complete). In this
2199
* case we wait a little bit and try again. In practive this
2200
* seems to only happen on windows (an we loop only a couple of times).
2202
retVal = SSL_connect(sSock->sslCnx);
2203
sSock->sslIOError = SSL_get_error(sSock->sslCnx, retVal);
2204
startTime = time(NULL);
2205
while((sSock->sslIOError == SSL_ERROR_WANT_WRITE ||
2206
sSock->sslIOError == SSL_ERROR_WANT_READ) &&
2207
time(NULL) - startTime < SSL_CONNECT_WAIT_TIMEOUT) {
2208
SSL_LOG(("SSL: connect busy waiting loop\n"));
2209
usleep(SSL_WAIT_TIME * 1000);
2210
retVal = SSL_connect(sSock->sslCnx);
2211
sSock->sslIOError = SSLSetErrorState(sSock->sslCnx, retVal);
2214
if (sSock->sslIOError != SSL_ERROR_NONE) {
2216
Warning("SSL: connect failed\n");
2217
sSock->connectionFailed = TRUE;
2221
SSL_LOG(("SSL: connect done\n"));
2223
SSLPrintCipher(sSock->sslCnx);
2225
sSock->encrypted = TRUE;
2228
if (sSock->sslCnx != NULL) {
2229
SSL_set_ex_data(sSock->sslCnx, SSLVerifyParamIx, NULL);
2232
END_NO_STACK_MALLOC_TRACKER;
2239
*----------------------------------------------------------------------
2241
* SSL_SetCertChain --
2243
* Adds the cert chain to the default SSL context. Will add the
2244
* first cert as a certificate, and the following certs as extra
2253
* New certs in SSL context
2256
*----------------------------------------------------------------------
2260
SSL_SetCertChain(char **certChain, // IN
2265
BIO *bioCert = NULL;
2267
SSL_CTX *ctx = SSL_DefaultContext();
2269
SSL_LOG(("SSL: Adding %d certs as a chain\n", numCerts));
2271
if (numCerts == 0) {
2276
ASSERT(certChain[0]);
2278
SSL_LOG(("SSL: Adding leaf cert\n%s\n", certChain[0]));
2280
/* The first cert is a certificate */
2281
bioCert = SSLCreateMemoryBIOFromBuffer(certChain[0],
2282
(int)(strlen(certChain[0]) + 1));
2283
if (bioCert == NULL) {
2284
Warning("SSL: Failed to create BIO");
2288
cert = PEM_read_bio_X509(bioCert, NULL, 0, NULL);
2291
Warning("SSL: Invalid certificate in chain (0):\n%s\n", certChain[0]);
2296
ret = SSL_CTX_use_certificate(ctx, cert);
2299
Warning("SSL: Failed to use certificate (0):\n%s\n", certChain[0]);
2305
* Add the rest of the certificates as part of the chain
2308
for (index = 1; index < numCerts; index++) {
2310
SSL_LOG(("SSL: Adding chain cert\n%s\n", certChain[index]));
2312
bioCert = SSLCreateMemoryBIOFromBuffer(certChain[index],
2313
(int)(strlen(certChain[index]) + 1));
2314
if (bioCert == NULL) {
2315
Warning("SSL: Failed to create BIO");
2319
cert = PEM_read_bio_X509(bioCert, NULL, 0, NULL);
2323
Warning("SSL: Invalid certificate in chain (%d):\n%s",
2324
index, certChain[index]);
2329
/* Call to SSL_CTX_add_extra_chain_cert */
2330
ret = SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, (char *)cert);
2333
Warning("SSL: Failed to use certificate (%d): %s",
2334
index, certChain[index]);
2338
} /* Loop over cert chain */
2340
SSL_LOG(("SSL: Done adding chain certs\n"));
2349
*----------------------------------------------------------------------
2353
* Checks that the common name of the peer cert matches
2358
* Returns TRUE on success, FALSE on failure.
2363
*----------------------------------------------------------------------
2367
SSL_CheckCert(SSLSock sSock, // IN
2369
Bool allowSelfSigned) // IN
2371
X509 *peerCert = NULL;
2377
ASSERT(sSock->sslCnx);
2379
SSL_LOG(("SSL: Peer Cert Check start\n"));
2380
rslt = SSL_get_verify_result(sSock->sslCnx);
2382
if (rslt != X509_V_OK) {
2383
if (allowSelfSigned &&
2384
((rslt == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) ||
2385
(rslt == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN))) {
2387
Warning("SSL: Self signed certificate in chain\n");
2389
Warning("SSL: Peer certificate does not verify (%d)\n", rslt);
2394
peerCert = SSL_get_peer_certificate(sSock->sslCnx);
2395
if (peerCert == NULL) {
2396
Warning("SSL: Could not get the peer certificate\n");
2400
X509_NAME_get_text_by_NID(X509_get_subject_name(peerCert),
2405
if (strcasecmp(peerCN, host)) {
2406
Warning("SSL: Peer common name does not match host (%s != %s)!\n",
2411
/* All checks passed */
2415
SSL_LOG(("SSL: Peer Cert Check end\n"));
2417
X509_free(peerCert);
2423
*----------------------------------------------------------------------
2427
* Accepts an SSL connection using default SSL context.
2429
* XXX should modify callers of this to code to check for
2432
* Callers of this function don't expect an error, so cache failures
2433
* for later reporting during an SSL{Read|Write}.
2435
* XXX: This is broken. SSL_accept must be retried until it succeeds, once it
2436
* returns SSL_ERROR_WANT_<something>. OpenSSL API requires that no other IO
2437
* operations be performed on the SSL until the IO operation that returned
2438
* the retry error on the SSL completes successfully. For blocking sockets,
2439
* simply setting the auto-retry mode flag takes care of this transparently
2440
* to the application. However for non-blocking sockets, the application must
2441
* expect and handle transient errors as required by OpenSSL.
2444
* Returns TRUE on success, FALSE on failure.
2447
* The server's certificate & private key may be loaded from disk.
2449
*----------------------------------------------------------------------
2453
SSL_Accept(SSLSock sSock) // IN: SSL socket
2455
return SSL_AcceptWithContext(sSock, SSL_DefaultContext());
2460
*----------------------------------------------------------------------
2462
* SSL_AcceptWithContext()
2464
* Accepts an SSL connection using the passed SSL context.
2466
* XXX should modify callers of this to code to check for
2469
* Callers of this function don't expect an error, so cache failures
2470
* for later reporting during an SSL{Read|Write}.
2472
* XXX: This is broken. SSL_accept must be retried until it succeeds, once it
2473
* returns SSL_ERROR_WANT_<something>. OpenSSL API requires that no other IO
2474
* operations be performed on the SSL until the IO operation that returned
2475
* the retry error on the SSL completes successfully. For blocking sockets,
2476
* simply setting the auto-retry mode flag takes care of this transparently
2477
* to the application. However for non-blocking sockets, the application must
2478
* expect and handle transient errors as required by OpenSSL.
2481
* Returns TRUE on success, FALSE on failure.
2484
* The server's certificate & private key may be loaded from disk.
2486
*----------------------------------------------------------------------
2489
Bool SSL_AcceptWithContext(SSLSock sSock, // IN: SSL socket
2490
void *ctx) // IN: OpenSSL context (SSL_CTX *)
2492
static Bool acceptInitialized = FALSE;
2496
ASSERT(SSLModuleInitialized);
2498
ASSERT_DEVEL(sSock->initialized == 12345);
2501
BEGIN_NO_STACK_MALLOC_TRACKER;
2503
if (!acceptInitialized) {
2504
if (!SSLLoadCertificates(loadCertificatesFromFile) && requireCertificates) {
2505
sSock->connectionFailed = TRUE;
2509
acceptInitialized = TRUE;
2512
sSock->sslCnx = SSL_new(ctx);
2513
if (!sSock->sslCnx) {
2515
Warning("Error Creating SSL connection structure\n");
2516
sSock->connectionFailed = TRUE;
2520
SSL_set_accept_state(sSock->sslCnx);
2522
SSL_LOG(("SSL: ssl created\n"));
2523
if (!SSL_set_fd(sSock->sslCnx, sSock->fd)) {
2525
Warning("Error setting fd for SSL connection\n");
2526
sSock->connectionFailed = TRUE;
2530
SSL_LOG(("SSL: fd set done\n"));
2533
* Because we use non-blocking sockets, this might not actually finish We
2534
* could wait for SSL_accept to finish, but that causes problems with a VM
2535
* trying to suspend itself using perlAPI. (SSL_Accept would then effectively
2536
* block -- which causes the VM to block, and deadlock ensues.
2540
* XXX: There needs to be a better solution for the above problem, that does
2541
* not violate OpenSSL API requirements as described in the function header.
2542
* Until this is properly fixed, applications may use SSL_CompleteAccept to
2543
* loop around until success.
2546
sslRet = SSL_accept(sSock->sslCnx);
2547
sSock->sslIOError = SSL_get_error(sSock->sslCnx, sslRet);
2548
sSock->encrypted = TRUE;
2551
END_NO_STACK_MALLOC_TRACKER;
2557
*----------------------------------------------------------------------
2561
* Functional equivalent of the read() syscall.
2562
* XXX should detect for packets that fail
2563
* the MAC verification & warn user that someone is being tricky.
2566
* Returns the number of bytes read, or -1 on error. The
2567
* data read will be placed in buf.
2572
*----------------------------------------------------------------------
2576
SSL_Read(SSLSock ssl,
2582
ASSERT_DEVEL(ssl->initialized == 12345);
2584
BEGIN_NO_STACK_MALLOC_TRACKER;
2586
if (ssl->connectionFailed) {
2587
SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
2592
if (ssl->encrypted) {
2593
int result = SSL_read(ssl->sslCnx, buf, (int)num);
2595
ssl->sslIOError = SSLSetErrorState(ssl->sslCnx, result);
2596
if (ssl->sslIOError != SSL_ERROR_NONE) {
2597
SSL_LOG(("SSL: Read(%d, %p, %d): %d\n",
2598
ssl->fd, buf, num, result));
2599
result = SOCKET_ERROR;
2606
ret = SSLGeneric_read(ssl->fd, buf, (int)num);
2610
* There is a bug on Mac OS 10.4.x where read(2) can return zero
2611
* even if the other end of the socket is not disconnected.
2612
* We verify this by calling write(ssl->fd, "", 0) and
2613
* see if it returns -1 with errno==EPIPE. If that doesn't
2614
* happen, the socket is okay. This has a side-effect where
2615
* a SIGPIPE signal will be sent to this process and
2616
* all apps that use this will need to handle that correctly.
2620
Bool ignoreError = FALSE;
2623
struct stat statBuffer;
2626
* Make sure we're using a socket.
2628
ASSERT((fstat(ssl->fd, &statBuffer) == 0) &&
2629
((statBuffer.st_mode & S_IFSOCK) == S_IFSOCK));
2632
writeRet = write(ssl->fd, "", 0);
2633
if (writeRet == 0) {
2634
char const *workaroundEnv;
2637
* The socket is still good. read(2) should not have
2640
if (! ssl->loggedKernelReadBug) {
2641
Log("Error: Encountered Apple bug #5202831. Disconnecting.\n");
2642
ssl->loggedKernelReadBug = TRUE;
2646
* One workaround is to let the caller function deal with this, such
2647
* as to remove the socket from poll for a little while. This doesn't
2648
* really fix the problem, but it removes the socket from Poll so we
2649
* don't spin on it. The caller is responsible for adding the socket
2650
* back to the Poll list in some time. That means we don't see any
2651
* activity on the socket while it is off poll, so the timeout should
2652
* be short. During that timeout, we miss any event on this socket like
2653
* new data or actually closing the socket.
2655
* Really, this is still just spinning on the socket, but it spins
2656
* more slowly. So, we tradeoff some responsiveness (we don't see socket
2657
* events promptly) for less performance impact on the overall system
2658
* by processing fewer false events on the socket.
2660
#if __APPLE_READ_BUG_WORKAROUND__
2661
if (ssl->errorHook) {
2662
ignoreError = (ssl->errorHook)(ssl, ssl->errorHookContext);
2667
* Another "workaround" keeps things running, but hogs the
2668
* CPU. So only enable it when a particular environment
2669
* variable is set (for QA or a customer with a specific
2673
workaroundEnv = Posix_Getenv("VMWARE_SOCKET_WORKAROUND");
2674
if (workaroundEnv != NULL &&
2675
Str_Strcasecmp(workaroundEnv, "YES") == 0) {
2683
fcntlFlags = fcntl(ssl->fd, F_GETFL, 0);
2684
if ((fcntlFlags & O_NONBLOCK) == O_NONBLOCK) {
2686
* The socket is not blocking, so let's pretend this
2687
* is EAGAIN to make everyone happy.
2693
* The socket is blocking. Spin until we get
2694
* real data or an end-of-stream where write(2) fails.
2705
END_NO_STACK_MALLOC_TRACKER;
2711
*----------------------------------------------------------------------
2715
* Functional equivalent of the write() syscall.
2719
* Returns the number of bytes written, or -1 on error.
2723
*----------------------------------------------------------------------
2727
SSL_Write(SSLSock ssl,
2733
ASSERT_DEVEL(ssl->initialized == 12345);
2735
BEGIN_NO_STACK_MALLOC_TRACKER;
2737
if (ssl->connectionFailed) {
2738
SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
2742
if (ssl->encrypted) {
2743
int result = SSL_write(ssl->sslCnx, buf, (int)num);
2745
ssl->sslIOError = SSLSetErrorState(ssl->sslCnx, result);
2746
if (ssl->sslIOError != SSL_ERROR_NONE) {
2747
SSL_LOG(("SSL: Write(%d)\n", ssl->fd));
2748
result = SOCKET_ERROR;
2752
ret = SSLGeneric_write(ssl->fd, buf, (int)num);
2756
END_NO_STACK_MALLOC_TRACKER;
2762
*----------------------------------------------------------------------
2766
* Functional equivalent of select when SSL is enabled
2769
* Obtain number of readable bytes buffered in an SSL object if SSL
2770
* is enabled, otherwise, return 0
2774
*----------------------------------------------------------------------
2778
SSL_Pending(SSLSock ssl) // IN
2782
ASSERT_DEVEL(ssl->initialized == 12345);
2784
BEGIN_NO_STACK_MALLOC_TRACKER;
2786
if (ssl->encrypted) {
2787
ret = SSL_pending(ssl->sslCnx);
2792
END_NO_STACK_MALLOC_TRACKER;
2798
*----------------------------------------------------------------------
2802
* Functional equivalent of the close() syscall. Does
2803
* not close the actual fd used for the connection.
2807
* 0 on success, -1 on failure.
2810
* closes the SSL connection, freeing up the memory associated
2811
* with the passed in ssl object
2813
*----------------------------------------------------------------------
2817
SSL_Shutdown(SSLSock ssl)
2821
ASSERT_DEVEL(ssl->initialized == 12345);
2823
ssl->initialized = 0;
2826
BEGIN_NO_STACK_MALLOC_TRACKER;
2828
SSL_LOG(("SSL: Starting shutdown for %d\n", ssl->fd));
2829
if (ssl->encrypted) {
2830
/* since quiet_shutdown is set, SSL_shutdown always succeeds */
2831
SSL_shutdown(ssl->sslCnx);
2832
SSL_free(ssl->sslCnx);
2835
if (ssl->closeFdOnShutdown) {
2836
SSL_LOG(("SSL: Trying to close %d\n", ssl->fd));
2837
retVal = SSLGeneric_close(ssl->fd);
2840
END_NO_STACK_MALLOC_TRACKER;
2842
SyncRecMutex_Destroy(&ssl->spinlock);
2845
SSL_LOG(("SSL: shutdown done\n"));
2851
*----------------------------------------------------------------------
2855
* Returns an SSL socket's file descriptor or handle.
2860
*----------------------------------------------------------------------
2864
SSL_GetFd(SSLSock ssl) // IN
2867
ASSERT_DEVEL(ssl->initialized == 12345);
2874
*----------------------------------------------------------------------
2878
* Wrapper around SSL_set_mode.
2881
* Return value of SSL_set_mode.
2886
*----------------------------------------------------------------------
2890
SSL_SetMode(SSLSock ssl, long mode)
2893
ASSERT_DEVEL(ssl->initialized == 12345);
2894
ASSERT(ssl->sslCnx);
2896
return SSL_set_mode(ssl->sslCnx, mode);
2901
*----------------------------------------------------------------------
2905
* Wrapper around SSL_want.
2913
*----------------------------------------------------------------------
2917
SSL_Want(const SSLSock ssl)
2920
ASSERT_DEVEL(ssl->initialized == 12345);
2921
ASSERT(ssl->sslCnx);
2923
return SSL_want(ssl->sslCnx);
2928
*----------------------------------------------------------------------
2932
* Wrapper around SSL_want_write.
2935
* That of SSL_want_write.
2940
*----------------------------------------------------------------------
2944
SSL_WantWrite(const SSLSock ssl)
2947
ASSERT_DEVEL(ssl->initialized == 12345);
2948
ASSERT(ssl->sslCnx);
2950
return SSL_want_write(ssl->sslCnx);
2955
*----------------------------------------------------------------------
2959
* Wrapper around SSL_want_read.
2962
* That of SSL_want_read.
2967
*----------------------------------------------------------------------
2971
SSL_WantRead(const SSLSock ssl)
2974
ASSERT_DEVEL(ssl->initialized == 12345);
2975
ASSERT(ssl->sslCnx);
2977
return SSL_want_read(ssl->sslCnx);
2982
*----------------------------------------------------------------------
2986
* Perform an SSL IO operation and store error information in the SSLSock
2987
* structure, for later use by subsequest SSLSafeIO calls.
2990
* - Once a retry condition is returned from an IO, then no other IO must be
2991
* performed on the SSL until the call that generated the retry condition
2992
* succeeds. We enforce this using the ioState member in SSLSock.
2994
* - Applications can reduce the likelihood of hitting retry errors by
2995
* ensuring that the underlying socket can actually perform the IO being
2996
* requested without blocking(or returning EWOULDBLOCK) before re/trying IO.
2998
* - Further, in the case of a read operation, SSL_pending may be used to
2999
* acertain if the SSL has any decrypted data in its buffer.
3001
* - SSLSafeIO should be used only for non-blocking IO. Blocking IO must use
3002
* SSL_Read and SSL_Write.
3006
* Returns < 0 on irrecoverable error.
3007
* Returns > 0 on success.
3008
* Returns 0 when the operation must be retried.
3012
*----------------------------------------------------------------------
3016
SSLSafeIO(SSLSock ssl,
3021
IOState thisInprogress, otherInprogress;
3027
ASSERT(ssl->sslCnx);
3028
ASSERT_DEVEL(ssl->initialized == 12345);
3029
ASSERT(ssl->encrypted);
3031
BEGIN_NO_STACK_MALLOC_TRACKER;
3033
if (ssl->connectionFailed) {
3034
SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
3040
thisInprogress = IOSTATE_READ_INPROGRESS;
3041
otherInprogress = IOSTATE_WRITE_INPROGRESS;
3043
thisInprogress = IOSTATE_WRITE_INPROGRESS;
3044
otherInprogress = IOSTATE_READ_INPROGRESS;
3047
if (!SyncRecMutex_Trylock(&ssl->spinlock)) {
3048
/* Another thread has locked this SSLSock. Caller should retry. */
3052
if (ssl->ioState != otherInprogress) {
3055
ioState = ssl->ioState;
3058
/* Safe to proceed with IO operation. */
3060
ret = (ssize_t)(sslread ?
3061
SSL_read(ssl->sslCnx, buf, (int)num) :
3062
SSL_write(ssl->sslCnx, buf, (int)num));
3063
ssl->sslIOError = SSLSetErrorState(ssl->sslCnx, (int)ret);
3065
switch (ssl->sslIOError) {
3066
case SSL_ERROR_NONE:
3067
if (ioState != IOSTATE_READY) {
3068
/* Clear the SSLSock state so that other IO can proceed. */
3069
ssl->ioState = IOSTATE_READY;
3072
case SSL_ERROR_WANT_READ:
3073
case SSL_ERROR_WANT_WRITE:
3074
/* Retry. Block other IO operations. */
3075
if (ioState == IOSTATE_READY) {
3076
ssl->ioState = thisInprogress;
3081
/* Irrecoverable error. */
3082
/* XXX: SSL_ERROR_WANT_X509_LOOKUP is not handled yet. */
3083
SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
3085
ssl->connectionFailed = TRUE;
3090
SyncRecMutex_Unlock(&ssl->spinlock);
3093
END_NO_STACK_MALLOC_TRACKER;
3098
*----------------------------------------------------------------------
3102
* Perform a single-shot non-blocking read.
3103
* If 0 is returned, then SSL_SafeRead must be retried before another IO
3104
* (SSL_SafeWrite) can proceed on this SSL.
3107
* Returns number of bytes read into the given buffer, which may be 0.
3108
* Returns < 0 on irrecoverable error.
3113
*----------------------------------------------------------------------
3117
SSL_SafeRead(SSLSock ssl,
3121
return SSLSafeIO(ssl, buf, num, TRUE);
3126
*----------------------------------------------------------------------
3130
* Perform a single shot, non-blocking write.
3131
* If 0 is returned, then SSL_SafeWrite must be retried before another IO
3132
* (SSL_SafeRead) can proceed on this SSL.
3135
* Return the number of bytes written, which may be 0, if none were written.
3136
* On irrecoverable error, returns < 0.
3141
*----------------------------------------------------------------------
3145
SSL_SafeWrite(SSLSock ssl,
3149
return SSLSafeIO(ssl, buf, num, FALSE);
3154
*----------------------------------------------------------------------
3156
* SSL_CompleteAccept()
3158
* Sleep and loop until the SSL_accept succeeds. SSL_Accept must
3159
* have been called before this so that sslIOError reflects the
3160
* outcome of the last SSL_accept.
3162
* XXX: SSL_Accept is broken - OpenSSL requires that the IO operation
3163
* (read/write/connect/accept), that needs to be retried, be retried until it
3164
* succeeds, and no other IO operation be attempted on the same SSL in the
3165
* meantime. So we must retry SSL_accept until it succeeds, and we must not
3166
* call any other IO operation on the SSL until the SSL_accept completes.
3168
* XXX: The better way to fix this API is to rename SSL_Accept to
3169
* SSL_AcceptInit and move the call to SSL_accept from there to a
3170
* new wrapper function called SSL_Accept. Applications can then call
3171
* SSL_AcceptInit once, and loop around SSL_Accept until it succeeds.
3172
* Leaving this for another day, since all the call sites would need
3176
* TRUE if the SSL_accept completed successfully. FALSE otherwise.
3181
*----------------------------------------------------------------------
3185
SSL_CompleteAccept(SSLSock ssl)
3188
ASSERT(ssl->sslCnx);
3190
if (ssl->connectionFailed) {
3191
SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
3198
switch (ssl->sslIOError) {
3199
case SSL_ERROR_NONE:
3201
case SSL_ERROR_WANT_READ:
3202
case SSL_ERROR_WANT_WRITE:
3203
usleep(SSL_WAIT_TIME * 1000);
3206
ssl->connectionFailed = TRUE;
3209
sslRet = SSL_accept(ssl->sslCnx);
3210
ssl->sslIOError = SSL_get_error(ssl->sslCnx, sslRet);
3218
*----------------------------------------------------------------------
3220
* SSL_SetRequireCerts()
3222
* Sets the global flag to the input parameter. Must be called after
3223
* SSL_InitEx. By default, certificates are required. So the client must
3224
* explicitly choose to disable enforcement.
3232
*----------------------------------------------------------------------
3236
SSL_SetRequireCerts(Bool required) // IN
3238
ASSERT(SSLModuleInitialized);
3239
requireCertificates = required;
3244
*----------------------------------------------------------------------
3246
* SSL_SetLoadCertificatesFromFile()
3248
* This is useful only for Windows. Sets the global flag to the input
3249
* parameter. Must be called after SSL_InitEx. By default, certificate and
3250
* private key are loaded from system certificate store. This flag makes
3251
* SSLLoadCertificates load them from files instead.
3259
*----------------------------------------------------------------------
3263
SSL_SetLoadCertificatesFromFile(Bool value)
3265
ASSERT(SSLModuleInitialized);
3266
loadCertificatesFromFile = value;
3271
*----------------------------------------------------------------------
3273
* SSL_SetDHParamFiles()
3275
* Sets the DH parameter file paths.
3283
*----------------------------------------------------------------------
3287
SSL_SetDHParamFiles(const char *dh512File, // IN
3288
const char *dh1024File) // IN
3290
ASSERT(dh512File || dh1024File);
3293
free(SSLDHParamsFiles[0]);
3294
SSLDHParamsFiles[0] = strdup(dh512File);
3295
ASSERT_MEM_ALLOC(SSLDHParamsFiles[0]);
3298
free(SSLDHParamsFiles[1]);
3299
SSLDHParamsFiles[1] = strdup(dh1024File);
3300
ASSERT_MEM_ALLOC(SSLDHParamsFiles[1]);
3306
*----------------------------------------------------------------------
3310
* Wrapper around BIO_new_file that converts "filename" from UTF-8
3311
* to the local encoding.
3314
* New BIO object. Return value is "void *" because we can't
3315
* include bio.h in ssl.h, or define BIO there, reliably.
3320
*----------------------------------------------------------------------
3324
SSL_BIO_new_file(const char *filename, // IN
3325
const char *mode) // IN
3332
if (!CodeSet_Utf8ToCurrent(filename, strlen(filename), &path2, NULL)) {
3336
res = BIO_new_file(path2, mode);
3344
#ifdef __APPLE_READ_BUG_WORKAROUND__
3346
*----------------------------------------------------------------------
3350
* Register a hook function that can handle read errors on the socket.
3351
* This allows higher levels of code to provide a workaround for the Apple bug 5202831.
3353
*----------------------------------------------------------------------
3357
SSL_SetErrorHook(SSLSock ssl, // IN
3358
SSLLibHandleErrorHookFn *hookProc, // IN
3359
void *context) // IN
3362
ASSERT_DEVEL(ssl->errorHook == NULL);
3364
ssl->errorHook = hookProc;
3365
ssl->errorHookContext = context;
3367
#endif // __APPLE_READ_BUG_WORKAROUND__