~ubuntu-branches/ubuntu/saucy/vmware-view-open-client/saucy

« back to all changes in this revision

Viewing changes to lib/bora/ssl/ssl.c

  • Committer: Bazaar Package Importer
  • Author(s): Daniel Baumann
  • Date: 2010-06-04 17:45:04 UTC
  • mfrom: (1.1.9 upstream)
  • Revision ID: james.westby@ubuntu.com-20100604174504-zjltuc0hdp4mv7de
Tags: 4.5.0-264434+dfsg-1
* Merging upstream version 4.5.0-264434+dfsg.
* Updating date and version header in manpage.
* Rediffing doc-pdf.patch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*********************************************************
2
 
 * Copyright (C) 1998 VMware, Inc. All rights reserved.
3
 
 *
4
 
 * This file is part of VMware View Open Client.
5
 
 *
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.
9
 
 *
10
 
 * This program is released with an additional exemption that
11
 
 * compiling, linking, and/or using the OpenSSL libraries with this
12
 
 * program is allowed.
13
 
 *
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.
18
 
 *
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.
22
 
 *
23
 
 *********************************************************/
24
 
 
25
 
#ifdef __linux__
26
 
#define _GNU_SOURCE /* dladdr */
27
 
#endif
28
 
#include <stdlib.h>
29
 
#include <string.h>
30
 
#if !_WIN32
31
 
#include <fcntl.h>
32
 
#include <unistd.h>
33
 
#else
34
 
#include <windows.h>
35
 
#include <winsock.h>
36
 
#include <wincrypt.h>
37
 
#include "win32util.h"
38
 
#include "win32auth.h"
39
 
#endif
40
 
#include <errno.h> 
41
 
#include <stdio.h>
42
 
#include <stddef.h>
43
 
 
44
 
#include "vmware.h"
45
 
#include "ssl.h"
46
 
#include "vm_version.h"
47
 
#include "file.h"
48
 
#include "posix.h"
49
 
#if defined(_WIN32)
50
 
#include "win32u.h"
51
 
#endif
52
 
#include "su.h"
53
 
#include "safetime.h"
54
 
#include "syncRecMutex.h"
55
 
#include "err.h"
56
 
#include "util.h"
57
 
#include "crypto.h"
58
 
#include "str.h"
59
 
#include "unicode.h"
60
 
 
61
 
#define LOGLEVEL_MODULE none
62
 
#include "loglevel_user.h"
63
 
 
64
 
#include "mallocTracker.h"
65
 
 
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>
79
 
 
80
 
#if defined(__APPLE__) && !defined(BORA_LINK_SSL_DIRECTLY)
81
 
#define BORA_LINK_SSL_DIRECTLY
82
 
#endif
83
 
 
84
 
// #define USE_SSL_DEBUG
85
 
 
86
 
#include "sslFunctionList.h"
87
 
 
88
 
struct SSLSockStruct {
89
 
   SSL *sslCnx;
90
 
   int fd;
91
 
   Bool encrypted;
92
 
   Bool closeFdOnShutdown;
93
 
   Bool connectionFailed;
94
 
#ifdef VMX86_DEVEL
95
 
   int initialized;
96
 
#endif /*VMX86_DEVEL */
97
 
#ifdef __APPLE__
98
 
   Bool loggedKernelReadBug;
99
 
#endif
100
 
 
101
 
#ifdef __APPLE_READ_BUG_WORKAROUND__
102
 
   SSLLibHandleErrorHookFn *errorHook;
103
 
   void *errorHookContext;
104
 
#endif
105
 
 
106
 
   IOState ioState;
107
 
   int sslIOError;
108
 
   SyncRecMutex spinlock;
109
 
};
110
 
 
111
 
#ifndef _WIN32
112
 
#include <dlfcn.h>
113
 
#endif
114
 
 
115
 
/*
116
 
 * The SSL wrapper functions
117
 
 *
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
122
 
 *      invalid.
123
 
 *
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
128
 
 *      wrappers.
129
 
 *
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.
133
 
 */
134
 
 
135
 
/*
136
 
 * Declare the global function pointers
137
 
 *
138
 
 *      Define and use a list operator to generate function pointers of the
139
 
 *      form SSL_newFn, BIO_readFn, etc.
140
 
 */
141
 
#define VMW_SSL_FUNC(_lib, _rettype, _func, _args, _argnames) \
142
 
   _rettype (* _func##Fn) _args;
143
 
VMW_SSL_FUNCTIONS
144
 
#undef VMW_SSL_FUNC
145
 
 
146
 
/*
147
 
 * Template for the wrapper function body. Just checks if the pointer is
148
 
 * valid; if not, Panic(), otherwise, call through.
149
 
 */
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"); \
154
 
      } \
155
 
      _retstmt _func##Fn _argnames; \
156
 
   }
157
 
 
158
 
/*
159
 
 * Bring in sslWrapper.h to generate the wrapper bodies
160
 
 */
161
 
#include "sslWrapper.h"
162
 
 
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 };
169
 
 
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"
174
 
 
175
 
#ifdef USE_SSL_DEBUG
176
 
#define SSL_LOG(x) LOG_DEVEL(x)
177
 
#else
178
 
#define SSL_LOG(x)
179
 
#endif /*USE_SSL_DEBUG*/
180
 
 
181
 
/* How long (ms) to wait before retrying a SSL_connect operation */
182
 
#define SSL_WAIT_TIME 100
183
 
 
184
 
/* How long (sec) to wait for data to be available on a socket during connect */
185
 
#define SSL_CONNECT_WAIT_TIMEOUT  120 
186
 
 
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;
192
 
#endif
193
 
 
194
 
/* XXX: Cleanup SSL library configuration at some point. */
195
 
 
196
 
/* 
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
199
 
 * privacy is.
200
 
 */
201
 
static Bool requireCertificates = TRUE;
202
 
 
203
 
/* Used only for Windows. Don't care on other platforms. */
204
 
static Bool loadCertificatesFromFile = FALSE;
205
 
 
206
 
/*
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'
210
 
 */
211
 
#define SSL_CIPHER_LIST "AES256-SHA,AES128-SHA"
212
 
 
213
 
 
214
 
#ifndef SOCKET_ERROR
215
 
#define SOCKET_ERROR (-1)
216
 
#endif
217
 
 
218
 
enum {
219
 
   SSL_SOCK_WANT_RETRY,
220
 
   SSL_SOCK_LOST_CONNECTION,
221
 
};
222
 
 
223
 
// XXX temporary hack for Win32 SCONS build
224
 
#ifdef _WIN32
225
 
#ifndef FIPS_SIGS_NAME
226
 
#define FIPS_SIGS_NAME "fipsSigs.dat"
227
 
#endif
228
 
#endif
229
 
 
230
 
#ifdef __APPLE__
231
 
   /*
232
 
    * Mac OS provides a crypto lib, so use the SDK's version
233
 
    * unless explicitly overriden.
234
 
    */
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"
238
 
 
239
 
#else /* __APPLE__ */
240
 
   /*
241
 
    * Ensure that the filenames for SSL libs are provided
242
 
    * for Windows or Linux, and make sure they are quoted correctly.
243
 
    */
244
 
#   ifndef LIBCRYPTO_SO
245
 
#      error Must provide LIBCRYPTO_SO filename
246
 
#   endif
247
 
#   ifndef LIBSSL_SO
248
 
#      error Must provide LIBSSL_SO filename
249
 
#   endif
250
 
#   define LIBCRYPTO_SO_QUOTED XSTR(LIBCRYPTO_SO)
251
 
#   define LIBSSL_SO_QUOTED XSTR(LIBSSL_SO)
252
 
#endif /* __APPLE__ */
253
 
 
254
 
/*
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
259
 
 * has to know!)
260
 
 */
261
 
#ifdef __linux__
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"
266
 
#else
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
271
 
#endif
272
 
 
273
 
static SSL_CTX *SSLNewDefaultContext(void);
274
 
 
275
 
 
276
 
/*
277
 
 *----------------------------------------------------------------------
278
 
 *
279
 
 * SSLPrintErrors
280
 
 *
281
 
 *    Print out all the errors in the SSL error stack.
282
 
 *
283
 
 * Results:
284
 
 *    None
285
 
 *
286
 
 * Side effects:
287
 
 *    Clears out the SSL error stack
288
 
 *
289
 
 *----------------------------------------------------------------------
290
 
 */
291
 
 
292
 
static void
293
 
SSLPrintErrors(void)
294
 
{
295
 
   int errNum;
296
 
   while ((errNum = ERR_get_error())) {
297
 
      Warning("SSL Error: %s\n", ERR_error_string(errNum, NULL));
298
 
   }
299
 
}
300
 
 
301
 
 
302
 
/*
303
 
 *----------------------------------------------------------------------
304
 
 *
305
 
 * SSLPrintCipher
306
 
 *
307
 
 *    Prints out the cipher that is currently being used by
308
 
 *    the ssl connection.
309
 
 *
310
 
 * Results:
311
 
 *    None
312
 
 *
313
 
 * Side effects:
314
 
 *    None
315
 
 *----------------------------------------------------------------------
316
 
 */
317
 
 
318
 
static void
319
 
SSLPrintCipher(SSL *ssl)
320
 
{
321
 
   int bits = 0;
322
 
   SSL_CIPHER *cipher;
323
 
   const char* cipher_name;
324
 
 
325
 
   cipher = SSL_get_current_cipher(ssl);
326
 
   SSL_CIPHER_get_bits(cipher, &bits);
327
 
 
328
 
   /*
329
 
    * if cipher is null, OpenSSL dies!
330
 
    */
331
 
   if (cipher != NULL) {
332
 
      cipher_name = SSL_CIPHER_get_name(cipher);
333
 
   } else {
334
 
      cipher_name = "undefined";
335
 
   }
336
 
   
337
 
   SSL_LOG(("Using cipher %s with %u bits\n", cipher_name, bits));
338
 
}
339
 
 
340
 
 
341
 
/*
342
 
 *----------------------------------------------------------------------
343
 
 *
344
 
 * SSLSetSystemError
345
 
 *
346
 
 *    Maps the ssl error state into an appropriate errno / WSA error. 
347
 
 *
348
 
 * Results:
349
 
 *    None
350
 
 *
351
 
 * Side effects:
352
 
 *    None
353
 
 *----------------------------------------------------------------------
354
 
 */
355
 
 
356
 
static void
357
 
SSLSetSystemError(int err)
358
 
{
359
 
   switch (err) {
360
 
      case SSL_SOCK_WANT_RETRY:
361
 
#ifdef _WIN32
362
 
         WSASetLastError(WSAEWOULDBLOCK);
363
 
#else
364
 
         errno = EAGAIN;
365
 
#endif
366
 
         break;
367
 
      case SSL_SOCK_LOST_CONNECTION:
368
 
         /*
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
371
 
          * something generic.
372
 
          */
373
 
#ifdef _WIN32
374
 
         WSASetLastError(WSAEACCES);
375
 
#else
376
 
         errno = EPERM;
377
 
#endif
378
 
         break;
379
 
      default:
380
 
         NOT_REACHED();
381
 
   }
382
 
}
383
 
 
384
 
 
385
 
/*
386
 
 *----------------------------------------------------------------------
387
 
 *
388
 
 * SSLSetErrorState
389
 
 *
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.
394
 
 *
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.
400
 
 *
401
 
 * Results:
402
 
 *    None
403
 
 *
404
 
 * Side effects:
405
 
 *    errno / windows error might be set.
406
 
 *
407
 
 *----------------------------------------------------------------------
408
 
 */
409
 
 
410
 
static int
411
 
SSLSetErrorState(SSL *ssl,
412
 
                 int result)
413
 
{
414
 
   int sslError = SSL_get_error(ssl, result);
415
 
   switch(sslError) {
416
 
      case SSL_ERROR_NONE:
417
 
         SSL_LOG(("SSL: action success, %d bytes\n", result));
418
 
         break;
419
 
      case SSL_ERROR_ZERO_RETURN:
420
 
         SSL_LOG(("SSL: Zero return\n"));
421
 
         break;
422
 
      case SSL_ERROR_WANT_READ:
423
 
         SSL_LOG(("SSL: Want read\n"));
424
 
         SSLSetSystemError(SSL_SOCK_WANT_RETRY);
425
 
         break;
426
 
      case SSL_ERROR_WANT_WRITE:
427
 
         SSL_LOG(("SSL: Want write\n"));
428
 
         SSLSetSystemError(SSL_SOCK_WANT_RETRY);
429
 
         break;
430
 
      case SSL_ERROR_WANT_X509_LOOKUP:
431
 
         SSL_LOG(("SSL: want x509 lookup\n"));
432
 
         break;
433
 
      case SSL_ERROR_SYSCALL:
434
 
         SSL_LOG(("SSL: syscall error\n"));
435
 
         break;
436
 
      case SSL_ERROR_SSL:
437
 
         Warning("SSL: Unknown SSL Error\n");
438
 
         break;
439
 
   }
440
 
   return sslError;
441
 
}
442
 
 
443
 
/*
444
 
 * Generic DLOPEN, DLSYM, and DLCLOSE macroes.
445
 
 */
446
 
 
447
 
#if defined(_WIN32)
448
 
#define DLOPEN(x) (void *) Win32U_LoadLibrary(x)
449
 
#define DLCLOSE(x) FreeLibrary(x)
450
 
#define DLSYM(name, dllHandle)                                          \
451
 
do {                                                                    \
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())); \
455
 
   }                                                                    \
456
 
} while (0)
457
 
#else
458
 
#define DLOPEN(x) Posix_Dlopen(x, RTLD_LAZY | RTLD_GLOBAL)
459
 
#define DLCLOSE(x) dlclose(x)
460
 
#define DLSYM(name, dllHandle)                                          \
461
 
do {                                                                    \
462
 
   char *error;                                                         \
463
 
   name ## Fn = dlsym(dllHandle, #name);                                \
464
 
   if ((error = dlerror()) != NULL) {                                   \
465
 
      SSL_LOG(("DLSYM: Failed to resolve %s: %s\n", #name, error));     \
466
 
   }                                                                    \
467
 
} while (0)
468
 
#endif
469
 
 
470
 
 
471
 
#ifndef BORA_LINK_SSL_DIRECTLY
472
 
/*
473
 
 *----------------------------------------------------------------------
474
 
 *
475
 
 * SSLGetModulePath --
476
 
 *
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
479
 
 *      fails otherwise.
480
 
 *
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 
484
 
 *        -wchien 03/13/03
485
 
 *   
486
 
 * Results:
487
 
 *      The full path or NULL on failure.
488
 
 *
489
 
 * Side effects:
490
 
 *      Memory is allocated.
491
 
 *
492
 
 *----------------------------------------------------------------------
493
 
 */
494
 
 
495
 
static char *
496
 
SSLGetModulePath(void)
497
 
{
498
 
   char *path;
499
 
 
500
 
#if defined(_WIN32)
501
 
   path = Win32U_GetModuleFileName(NULL);
502
 
 
503
 
   if (path == NULL) {
504
 
      Warning("%s: GetModuleFileName failed: %d\n", __FUNCTION__,
505
 
              GetLastError());
506
 
   }
507
 
#else
508
 
   uid_t uid;
509
 
 
510
 
   uid = Id_BeginSuperUser();
511
 
   path = Posix_ReadLink("/proc/self/exe");
512
 
   Id_EndSuperUser(uid);
513
 
 
514
 
   if (path == NULL) {
515
 
      Warning("%s: readlink failed: %s\n", __FUNCTION__, strerror(errno));
516
 
   }
517
 
#endif
518
 
 
519
 
   return path;
520
 
}
521
 
 
522
 
 
523
 
/*
524
 
 *----------------------------------------------------------------------
525
 
 *
526
 
 * SSLGetLibraryPath --
527
 
 *
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
530
 
 *      need this.
531
 
 *
532
 
 * Results:
533
 
 *      The full path or NULL on failure.
534
 
 *
535
 
 * Side effects:
536
 
 *      Memory is allocated.
537
 
 *
538
 
 *----------------------------------------------------------------------
539
 
 */
540
 
 
541
 
static Unicode
542
 
SSLGetLibraryPath(void)
543
 
{
544
 
#ifdef __linux__
545
 
   Dl_info info;
546
 
 
547
 
   if (dladdr(SSLGetLibraryPath, &info)) {
548
 
      return Unicode_Alloc(info.dli_fname, STRING_ENCODING_DEFAULT);
549
 
   }
550
 
   return NULL;
551
 
#else
552
 
   return NULL;
553
 
#endif
554
 
}
555
 
 
556
 
 
557
 
/* 
558
 
 *----------------------------------------------------------------------
559
 
 *
560
 
 *  SSLOpenSystemLibrary --
561
 
 *
562
 
 *     Tries to open system library - either libcrypto or libssl.
563
 
 *
564
 
 * Results:
565
 
 *     The library handle on success, NULL on failure.
566
 
 *
567
 
 * Side effects:
568
 
 *     Library loaded & verified.
569
 
 *
570
 
 *----------------------------------------------------------------------
571
 
 */
572
 
 
573
 
static void *
574
 
SSLOpenSystemLibrary(const char *libname,   // IN: library name
575
 
                     Bool doVersionCheck)   // IN: is libcrypto and wants new version
576
 
{
577
 
   void *libHandle;
578
 
 
579
 
   /*
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.
583
 
    */
584
 
 
585
 
   libHandle = DLOPEN(libname);
586
 
   if (libHandle) {
587
 
      long (*SSLeayFn)(void);
588
 
 
589
 
      if (!doVersionCheck) {
590
 
         return libHandle;
591
 
      }
592
 
 
593
 
      DLSYM(SSLeay, libHandle);
594
 
      if (SSLeayFn) {
595
 
         long ver;
596
 
 
597
 
         /*
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.
603
 
          */
604
 
 
605
 
         ver = SSLeayFn();
606
 
         if (ver >= OPENSSL_VERSION_NUMBER) {
607
 
            Log("Using system libcrypto, version %lX\n", ver);
608
 
            return libHandle;
609
 
         }
610
 
         Log("System %s library is older than our library (%lX < %lX)\n",
611
 
             libname, ver, OPENSSL_VERSION_NUMBER);
612
 
      }
613
 
      DLCLOSE(libHandle);
614
 
   }
615
 
   return NULL;
616
 
}
617
 
 
618
 
 
619
 
/* 
620
 
 *----------------------------------------------------------------------
621
 
 *
622
 
 *  SSLOpenLibraryWithPath --
623
 
 *
624
 
 *     Tries to open libcrypto/libssl library in directory where argument
625
 
 *     lives.
626
 
 *
627
 
 * Results:
628
 
 *     The library handle on success, NULL on failure.
629
 
 *
630
 
 * Side effects:
631
 
 *     Library loaded.
632
 
 *
633
 
 *----------------------------------------------------------------------
634
 
 */
635
 
 
636
 
static void *
637
 
SSLOpenLibraryWithPath(const char *fullPath,  // IN: path
638
 
                       const char *libname)   // IN: library name
639
 
{
640
 
   char *libLocation;
641
 
   void *libHandle;
642
 
   char *pathEnd;
643
 
   unsigned int sublen;
644
 
 
645
 
   /* Broken on Windows... */
646
 
   pathEnd = strrchr(fullPath, DIRSEPC);
647
 
   if (!pathEnd) {
648
 
      /*
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....
652
 
       */
653
 
      return NULL;
654
 
   }
655
 
   sublen = pathEnd - fullPath;
656
 
 
657
 
   libLocation = Str_Asprintf(NULL, "%*.*s%c%s", sublen, sublen, fullPath,
658
 
                              DIRSEPC, libname);
659
 
 
660
 
   ASSERT_MEM_ALLOC(libLocation);
661
 
 
662
 
   libHandle = DLOPEN(libLocation);
663
 
 
664
 
   free(libLocation);
665
 
 
666
 
   if (libHandle) {
667
 
      return libHandle;
668
 
   }
669
 
 
670
 
   libLocation = Str_Asprintf(NULL, "%*.*s%clibdir%clib%c%s%c%s", sublen,
671
 
                              sublen, fullPath, DIRSEPC, DIRSEPC, DIRSEPC,
672
 
                              libname, DIRSEPC, libname);
673
 
 
674
 
   ASSERT_MEM_ALLOC(libLocation);
675
 
 
676
 
   libHandle = DLOPEN(libLocation);
677
 
 
678
 
   free(libLocation);
679
 
 
680
 
   if (libHandle) {
681
 
      return libHandle;
682
 
   }
683
 
   return NULL;
684
 
}
685
 
 
686
 
 
687
 
/* 
688
 
 *----------------------------------------------------------------------
689
 
 *
690
 
 *  SSLOpenLibrary --
691
 
 *
692
 
 *     Gets the directory and name of a library and returns a handle to 
693
 
 *     it.  Panics if it can't be found.
694
 
 *
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.
697
 
 * 
698
 
 * Results:
699
 
 *     The library handle on success.
700
 
 *     Panic() on failure.
701
 
 *
702
 
 * Side effects:
703
 
 *     Library loaded & verified.
704
 
 *
705
 
 *----------------------------------------------------------------------
706
 
 */
707
 
 
708
 
static void *
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
717
 
{
718
 
   char *libLocation;
719
 
   char *fullpath;
720
 
   void *libHandle;
721
 
 
722
 
   if (*system) {
723
 
      /*
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.
727
 
       */
728
 
 
729
 
      libHandle = SSLOpenSystemLibrary(libname, isLibCrypto && doVersionCheck);
730
 
      if (libHandle) {
731
 
         return libHandle;
732
 
      }
733
 
      if (altLibName) {
734
 
         libHandle = SSLOpenSystemLibrary(altLibName, isLibCrypto && doVersionCheck);
735
 
         if (libHandle) {
736
 
            return libHandle;
737
 
         }
738
 
      }
739
 
      if (altLibName2) {
740
 
         libHandle = SSLOpenSystemLibrary(altLibName2, isLibCrypto && doVersionCheck);
741
 
         if (libHandle) {
742
 
            return libHandle;
743
 
         }
744
 
      }
745
 
      /* System's libcrypto failed - do not attempt to use system's libssl */
746
 
      *system = FALSE;
747
 
   }
748
 
 
749
 
#ifdef __APPLE__
750
 
   /*
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__
756
 
    */
757
 
   NOT_IMPLEMENTED();
758
 
#endif
759
 
 
760
 
   /*
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 
763
 
    */
764
 
   if (libdir != NULL) {
765
 
      libLocation = Str_SafeAsprintf(NULL,
766
 
#ifdef VM_X86_64
767
 
                   "%s%clib%c%s-x86-64%c%s",
768
 
#else
769
 
                   "%s%clib%c%s-i386%c%s",
770
 
#endif
771
 
                   libdir, DIRSEPC, /* "lib" */ DIRSEPC, libname,
772
 
                   DIRSEPC, libname);
773
 
      libHandle = DLOPEN(libLocation);
774
 
      free(libLocation);
775
 
      if (libHandle) {
776
 
         return libHandle;
777
 
      }
778
 
 
779
 
      libLocation = Str_SafeAsprintf(NULL, "%s%clib%c%s%c%s", libdir, DIRSEPC,
780
 
                                     /* "lib" */ DIRSEPC, libname, DIRSEPC,
781
 
                                     libname);
782
 
      libHandle = DLOPEN(libLocation);
783
 
      free(libLocation);
784
 
      if (libHandle) {
785
 
         return libHandle;
786
 
      }
787
 
      
788
 
      libLocation = Str_SafeAsprintf(NULL, "%s%clib%c%s", libdir, DIRSEPC,
789
 
                                     /* "lib" */ DIRSEPC, libname);
790
 
      libHandle = DLOPEN(libLocation);
791
 
      free(libLocation);
792
 
      if (libHandle) {
793
 
        return libHandle;
794
 
      }
795
 
 
796
 
      libLocation = Str_SafeAsprintf(NULL, "%s%c%s", libdir, DIRSEPC, libname);
797
 
      libHandle = DLOPEN(libLocation);
798
 
      free(libLocation);
799
 
      if (libHandle) {
800
 
         return libHandle;
801
 
      }
802
 
   }
803
 
 
804
 
   fullpath = SSLGetLibraryPath();
805
 
   if (fullpath) {
806
 
      libHandle = SSLOpenLibraryWithPath(fullpath, libname);
807
 
      free(fullpath);
808
 
      if (libHandle) {
809
 
         return libHandle;
810
 
      }
811
 
   }
812
 
 
813
 
   fullpath = SSLGetModulePath();
814
 
   if (fullpath) {
815
 
      libHandle = SSLOpenLibraryWithPath(fullpath, libname);
816
 
      free(fullpath);
817
 
      if (libHandle) {
818
 
         return libHandle;
819
 
      }
820
 
   }
821
 
 
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);
826
 
   free(libLocation);
827
 
   if (libHandle) {
828
 
      return libHandle;
829
 
   }
830
 
#endif
831
 
 
832
 
#ifdef _WIN32
833
 
   Panic("SSLLoadSharedLibrary: Failed to load library %s:%d\n", 
834
 
         libname, GetLastError());
835
 
#else
836
 
   Panic("SSLLoadSharedLibrary: Failed to load library %s:%s\n", 
837
 
         libname, dlerror());
838
 
#endif
839
 
   return NULL;
840
 
}
841
 
 
842
 
 
843
 
/*
844
 
 *----------------------------------------------------------------------
845
 
 *
846
 
 * SSLLoadSharedLibrary--
847
 
 *
848
 
 *   Links in functions from the SSL library.
849
 
 *
850
 
 *----------------------------------------------------------------------
851
 
 */
852
 
 
853
 
static void
854
 
SSLLoadSharedLibrary(const char *libdir, 
855
 
                     Bool useSystem, 
856
 
                     Bool doVersionCheck)
857
 
{
858
 
   Bool system = useSystem;
859
 
 
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);
864
 
 
865
 
   /*
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
868
 
    * want.
869
 
    */
870
 
   #define VMW_SSL_FUNC(_lib, _rettype, _func, _args, _argnames) \
871
 
      DLSYM(_func, lib##_lib##Handle);
872
 
   VMW_SSL_FUNCTIONS
873
 
   #undef VMW_SSL_FUNC
874
 
}
875
 
#endif
876
 
 
877
 
 
878
 
/*
879
 
 *----------------------------------------------------------------------
880
 
 *
881
 
 * SSLAddLockCb --
882
 
 *
883
 
 *      Callback for adding two numbers atomically
884
 
 *
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
888
 
 *
889
 
 *      (see bug 105949 for more details)
890
 
 *
891
 
 * Results:
892
 
 *
893
 
 *      The new value of of *num.
894
 
 *
895
 
 *---------------------------------------------------------------------- 
896
 
 */
897
 
 
898
 
static int 
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)
904
 
{
905
 
   // XXX: This might not be 64-bit safe
906
 
   return Atomic_FetchAndAddUnfenced(Atomic_VolatileToAtomic(num), amount) +
907
 
          amount;
908
 
}
909
 
 
910
 
 
911
 
/*
912
 
 *----------------------------------------------------------------------
913
 
 *
914
 
 * SSLVerifyCb --
915
 
 *
916
 
 *      Callback invoked by SSL during a handshake in order to verify
917
 
 *      the peer certificate. 
918
 
 *
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
927
 
 *      1) or not.
928
 
 *
929
 
 *      We employ two strategies to validate a certificate: 1)
930
 
 *      Thumbprint matching and 2) Signature checking.
931
 
 *
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.
938
 
 *
939
 
 *      Signature checking is only implemented on Windows at the
940
 
 *      moment.
941
 
 *
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.
946
 
 *
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
949
 
 *      implementation.
950
 
 *
951
 
 *---------------------------------------------------------------------- 
952
 
 */
953
 
 
954
 
static int
955
 
SSLVerifyCb(int preverifyOk, X509_STORE_CTX *storeCtx)
956
 
{
957
 
   SSL *ssl;
958
 
   SSLVerifyParam *verifyParam;
959
 
   X509 *cert;
960
 
 
961
 
   /*
962
 
    * Obtain the parameters we need in verification.
963
 
    *
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
967
 
    */
968
 
 
969
 
   ssl = (SSL *) X509_STORE_CTX_get_ex_data(
970
 
      storeCtx, SSL_get_ex_data_X509_STORE_CTX_idx());
971
 
 
972
 
   verifyParam = (SSLVerifyParam *) SSL_get_ex_data(ssl, SSLVerifyParamIx);
973
 
   cert = X509_STORE_CTX_get_current_cert(storeCtx);
974
 
 
975
 
   return SSL_VerifyX509(verifyParam, cert) ? 1 : 0;
976
 
}
977
 
 
978
 
 
979
 
 
980
 
/*
981
 
 *----------------------------------------------------------------------
982
 
 *
983
 
 * SSLLockingCb --
984
 
 *
985
 
 *      Callback for locking for use by OpenSSL.
986
 
 *
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
991
 
 *
992
 
 *---------------------------------------------------------------------- 
993
 
 */
994
 
 
995
 
static void 
996
 
SSLLockingCb(int mode,           // indicates locking or unlocking
997
 
             int n,              // lock index 
998
 
             const char *file,   // file name
999
 
             int line)           // line number
1000
 
{
1001
 
#ifdef WIN32
1002
 
   int savederr = GetLastError();
1003
 
#else
1004
 
   int savederr = errno;
1005
 
#endif
1006
 
 
1007
 
if (!SSLModuleInitialized) { 
1008
 
        return;
1009
 
}
1010
 
 
1011
 
   if (CRYPTO_LOCK & mode) {
1012
 
      SyncMutex_Lock(&ssl_locks[n]);
1013
 
   } else if (CRYPTO_UNLOCK & mode) {
1014
 
      SyncMutex_Unlock(&ssl_locks[n]);
1015
 
   }
1016
 
 
1017
 
#ifdef WIN32
1018
 
   SetLastError(savederr);
1019
 
#else
1020
 
   errno = savederr;
1021
 
#endif
1022
 
}
1023
 
 
1024
 
 
1025
 
/*
1026
 
 *---------------------------------------------------------------------- 
1027
 
 * 
1028
 
 * SSLTmpDHCallback --
1029
 
 *
1030
 
 *    Callback for DH key exchange. Initializes the DH parameters
1031
 
 *    from the configuration files, if not already initialized.
1032
 
 *
1033
 
 * Results:
1034
 
 *    DH parameter for use by OpenSSL. NULL on failure.
1035
 
 *
1036
 
 * Side Effects:
1037
 
 *    None.
1038
 
 *
1039
 
 *---------------------------------------------------------------------- 
1040
 
 */
1041
 
 
1042
 
static DH *
1043
 
SSLTmpDHCallback(SSL *ssl,       // IN: unused
1044
 
                 int is_export,  // IN: Export restricted?
1045
 
                 int keylength)  // IN: Length of key to be returned.
1046
 
{
1047
 
   static DH *dh512 = NULL;
1048
 
   static DH *dh1024 = NULL;
1049
 
 
1050
 
   if (!dh512 || !dh1024) {
1051
 
      BIO *bio = SSL_BIO_new_file(SSLDHParamsFiles[0], "r");
1052
 
      if (bio) {
1053
 
         dh512 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1054
 
         if (!dh512) {
1055
 
            Warning("Error reading DH parameter file");
1056
 
         }
1057
 
         BIO_free(bio);
1058
 
      } else {
1059
 
         Warning("Error opening DH parameter file");
1060
 
      }
1061
 
 
1062
 
      bio = SSL_BIO_new_file(SSLDHParamsFiles[1], "r");
1063
 
      if (bio) {
1064
 
         dh1024 = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1065
 
         if (!dh1024) {
1066
 
            Warning("Error reading DH parameter file");
1067
 
         }
1068
 
         BIO_free(bio);
1069
 
      } else {
1070
 
         Warning("Error opening DH parameter file");
1071
 
      }
1072
 
   }
1073
 
 
1074
 
   return (keylength == 512) ? dh512 : dh1024;
1075
 
}
1076
 
 
1077
 
 
1078
 
/*
1079
 
 *----------------------------------------------------------------------
1080
 
 *
1081
 
 * SSLThreadIdCb --
1082
 
 *
1083
 
 *      Callback for current thread id for use by OpenSSL.
1084
 
 *
1085
 
 *      OpenSSL requires setting of a thread id callback function in
1086
 
 *      multi-threaded applications.
1087
 
 *
1088
 
 *---------------------------------------------------------------------- 
1089
 
 */
1090
 
 
1091
 
static unsigned long
1092
 
SSLThreadIdCb(void)
1093
 
{
1094
 
   return (unsigned long)Util_GetCurrentThreadId();
1095
 
}
1096
 
 
1097
 
 
1098
 
/*
1099
 
 *----------------------------------------------------------------------
1100
 
 *
1101
 
 * SSL_InitEx --
1102
 
 *
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.
1106
 
 *
1107
 
 * Results:
1108
 
 *      None.
1109
 
 *
1110
 
 * Side effects:
1111
 
 *      Lots.
1112
 
 
1113
 
 *----------------------------------------------------------------------
1114
 
 */
1115
 
 
1116
 
void
1117
 
SSL_InitEx(SSLLibFn *getLibFn, 
1118
 
           const char *defaultLib, 
1119
 
           const char *name,
1120
 
           Bool useSystem,
1121
 
           Bool doVersionCheck,
1122
 
           Bool disableLoading)
1123
 
 
1124
 
{
1125
 
   /*Silently ignore any attempts to initialize module more than once*/
1126
 
   if (!SSLModuleInitialized) {
1127
 
      int numSslLocks, i;
1128
 
#ifdef BORA_LINK_SSL_DIRECTLY
1129
 
      /*
1130
 
       * On the Mac, we directly link the ssl libraries, so there's no
1131
 
       * need to dlopen and load the symbols.
1132
 
       */
1133
 
      BEGIN_NO_STACK_MALLOC_TRACKER;
1134
 
      BEGIN_NO_MALLOC_TRACKER;
1135
 
#else
1136
 
      char *libdir;
1137
 
      BEGIN_NO_STACK_MALLOC_TRACKER;
1138
 
 
1139
 
      BEGIN_NO_MALLOC_TRACKER;
1140
 
      if (disableLoading) {
1141
 
         /* 
1142
 
          * If SSL libraries are already loaded, then setup the function
1143
 
          * pointers.
1144
 
          */
1145
 
#ifdef WIN32
1146
 
         libcryptoHandle = GetModuleHandle(LIBCRYPTO_SO_QUOTED);
1147
 
         ASSERT(libcryptoHandle);
1148
 
         libsslHandle = GetModuleHandle(LIBSSL_SO_QUOTED);
1149
 
         ASSERT(libsslHandle);
1150
 
#else 
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");
1155
 
 
1156
 
         ASSERT(thislibHandle);
1157
 
         ASSERT(thisFn);
1158
 
         ASSERT(globalFn);
1159
 
 
1160
 
         if (thisFn == globalFn) {
1161
 
            globalFn = dlsym(RTLD_NEXT, "SSL_library_init");
1162
 
            libsslHandle = RTLD_NEXT;
1163
 
         }
1164
 
         if (thisFn == globalFn || globalFn == NULL) {
1165
 
            SSL_LOG(("Failed to locate libssl symbols.\n"));
1166
 
            Panic("Failed to locate libssl symbols.\n");
1167
 
         }
1168
 
 
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;
1174
 
         }
1175
 
         if (thisFn == globalFn || globalFn == NULL) {
1176
 
            SSL_LOG(("Failed to locate libcrypto symbols.\n"));
1177
 
            Panic("Failed to locate libcrypto symbols.\n");
1178
 
         }
1179
 
 
1180
 
         dlclose(thislibHandle);
1181
 
#endif
1182
 
         /*
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
1185
 
          * want.
1186
 
          */
1187
 
         #define VMW_SSL_FUNC(_lib, _rettype, _func, _args, _argnames) \
1188
 
            DLSYM(_func, lib##_lib##Handle);
1189
 
         VMW_SSL_FUNCTIONS
1190
 
         #undef VMW_SSL_FUNC
1191
 
      } else {
1192
 
         if (getLibFn) {
1193
 
            libdir = (getLibFn)(defaultLib, name);      
1194
 
         } else {
1195
 
            libdir = defaultLib ? strdup(defaultLib) : NULL;
1196
 
         }
1197
 
         // We check if libdir is valid in SSLLoadSharedLibrary
1198
 
         SSLLoadSharedLibrary(libdir,
1199
 
                              CryptoFips_FipsModeEnabled() ? FALSE : useSystem,
1200
 
                              doVersionCheck);
1201
 
         free(libdir);
1202
 
      }
1203
 
#endif
1204
 
      SSL_library_init();
1205
 
      SSL_load_error_strings();
1206
 
      END_NO_MALLOC_TRACKER;
1207
 
 
1208
 
      /*
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.
1218
 
       *
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
1223
 
       * would be a NOOP. 
1224
 
       */
1225
 
      RAND_status();
1226
 
 
1227
 
 
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);
1232
 
      }
1233
 
 
1234
 
      CRYPTO_set_locking_callback(SSLLockingCb);
1235
 
      CRYPTO_set_id_callback(SSLThreadIdCb); 
1236
 
 
1237
 
 
1238
 
      /*
1239
 
       * Only peform additional initialization tasks if not compiled
1240
 
       * inside vmcryptolib, because vmcryptolib itself does not need
1241
 
       * to set-up networking.
1242
 
       */
1243
 
 
1244
 
      if (!CryptoFips_InVmcryptolib()) {
1245
 
         CRYPTO_set_add_lock_callback(SSLAddLockCb);
1246
 
      }
1247
 
 
1248
 
      /*
1249
 
       * Force the initialization of ssl_ctx, in case anyone is using it without
1250
 
       * going through one of our functions.
1251
 
       */
1252
 
 
1253
 
      ssl_ctx = SSLNewDefaultContext();
1254
 
 
1255
 
      SSL_LOG(("SSL: default ctx created\n"));
1256
 
      SSL_LOG(("Initializing default ssl context: %p\n", ctx));
1257
 
 
1258
 
#ifdef _WIN32
1259
 
      SSLCertFile = W32Util_GetInstalledFilePath("\\ssl\\" SERVER_CERT_FILE);
1260
 
      SSLKeyFile = W32Util_GetInstalledFilePath("\\ssl\\" SERVER_KEY_FILE);
1261
 
      SSLDHParamsFiles[0] = W32Util_GetInstalledFilePath("\\ssl\\"
1262
 
                                                         SSL_DH512_FILE);
1263
 
      SSLDHParamsFiles[1] = W32Util_GetInstalledFilePath("\\ssl\\"
1264
 
                                                         SSL_DH1024_FILE);
1265
 
#else
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/"
1269
 
                                   SSL_DH512_FILE);
1270
 
      SSLDHParamsFiles[1] = strdup(VMWARE_HOST_DIRECTORY "/ssl/"
1271
 
                                   SSL_DH1024_FILE);
1272
 
#endif //
1273
 
      ASSERT_MEM_ALLOC(SSLCertFile);
1274
 
      ASSERT_MEM_ALLOC(SSLKeyFile);
1275
 
      ASSERT_MEM_ALLOC(SSLDHParamsFiles[0]);
1276
 
      ASSERT_MEM_ALLOC(SSLDHParamsFiles[1]);
1277
 
 
1278
 
      SSLModuleInitialized = TRUE;
1279
 
 
1280
 
      END_NO_STACK_MALLOC_TRACKER;
1281
 
   }
1282
 
}
1283
 
 
1284
 
 
1285
 
/*
1286
 
 *----------------------------------------------------------------------
1287
 
 *
1288
 
 * SSL_Init --
1289
 
 *
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.
1293
 
 *
1294
 
 * Results:
1295
 
 *      None.
1296
 
 *
1297
 
 * Side effects:
1298
 
 *      Lots.
1299
 
 *
1300
 
 *----------------------------------------------------------------------
1301
 
 */
1302
 
 
1303
 
void
1304
 
SSL_Init(SSLLibFn *getLibFn, const char *defaultLib, const char *name)
1305
 
{
1306
 
   SSL_InitEx(getLibFn, defaultLib, name, TRUE, TRUE, FALSE);
1307
 
}
1308
 
 
1309
 
 
1310
 
/*
1311
 
 *----------------------------------------------------------------------
1312
 
 * SSLNewDefaultContext --
1313
 
 *
1314
 
 *      Return an SSL context initialized with reasonable defaults.
1315
 
 *----------------------------------------------------------------------
1316
 
 */
1317
 
 
1318
 
static SSL_CTX *
1319
 
SSLNewDefaultContext(void)
1320
 
{
1321
 
   SSL_CTX *ctx;
1322
 
 
1323
 
   ctx = SSL_CTX_new(CryptoFips_FipsModeEnabled() ?
1324
 
                     TLSv1_method() : SSLv23_method());
1325
 
 
1326
 
   if (!ctx) {
1327
 
      SSLPrintErrors();
1328
 
      Panic("Error Starting Up Default SSL context\n");
1329
 
      NOT_REACHED();
1330
 
   }
1331
 
 
1332
 
   /* 
1333
 
    * Disable SSLv2 and enable all known bug workarounds.
1334
 
    */
1335
 
   SSL_CTX_set_options(ctx,
1336
 
                       SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_SINGLE_DH_USE);
1337
 
 
1338
 
   /*
1339
 
    * Automatically retry an operation that failed with
1340
 
    * SSL_WANT_{READ|WRITE} if blocking sockets are being used
1341
 
    *
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
1345
 
    * SSL.
1346
 
    */
1347
 
   SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, SSL_MODE_AUTO_RETRY, NULL);
1348
 
 
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);
1352
 
   /* 
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).
1357
 
    * */
1358
 
   SSL_CTX_set_quiet_shutdown(ctx, 1);
1359
 
 
1360
 
   /*
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.
1364
 
    */
1365
 
   SSL_CTX_set_cipher_list(ctx, SSL_CIPHER_LIST);
1366
 
 
1367
 
   /* 
1368
 
    * Initialize the callback for use with cipher suites using Diffie-Hellman.
1369
 
    */
1370
 
   SSL_CTX_set_tmp_dh_callback(ctx, SSLTmpDHCallback);
1371
 
 
1372
 
   /*
1373
 
    * Create a new slot (index) where we can store a pointer to the
1374
 
    * SSLVerifyParam data structure
1375
 
    */
1376
 
   SSLVerifyParamIx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1377
 
   
1378
 
   return ctx;
1379
 
}
1380
 
 
1381
 
 
1382
 
/*
1383
 
 *----------------------------------------------------------------------
1384
 
 * SSL_DefaultContext --
1385
 
 *
1386
 
 *      Returns the global default SSL context. SSL_Init[Ex] must have been
1387
 
 *      called before calling this.
1388
 
 *----------------------------------------------------------------------
1389
 
 */
1390
 
 
1391
 
void *
1392
 
SSL_DefaultContext(void)
1393
 
{
1394
 
   ASSERT(SSLModuleInitialized);
1395
 
   return (void *)ssl_ctx;
1396
 
}
1397
 
 
1398
 
 
1399
 
/*
1400
 
 *----------------------------------------------------------------------
1401
 
 *
1402
 
 * SSL_SetVerifySSLCertificates --
1403
 
 *
1404
 
 *      Sets a global option to verify or not verify peeer SSL
1405
 
 *      certificates.
1406
 
 *
1407
 
 *---------------------------------------------------------------------- 
1408
 
 */
1409
 
 
1410
 
void
1411
 
SSL_SetVerifySSLCertificates(SSLVerifyType verify)
1412
 
{
1413
 
   SSLVerifySSLCertificates = verify;
1414
 
}
1415
 
 
1416
 
 
1417
 
/*
1418
 
 *----------------------------------------------------------------------
1419
 
 *
1420
 
 * SSL_GetVerifySSLCertificates --
1421
 
 *
1422
 
 *      Returns the global option that determines whether peer SSL
1423
 
 *      certificates should be verified
1424
 
 *
1425
 
 *---------------------------------------------------------------------- 
1426
 
 */
1427
 
 
1428
 
SSLVerifyType
1429
 
SSL_GetVerifySSLCertificates(void)
1430
 
{
1431
 
   return SSLVerifySSLCertificates;
1432
 
}
1433
 
 
1434
 
 
1435
 
/*
1436
 
 *----------------------------------------------------------------------
1437
 
 *
1438
 
 * SSL_VerifyX509Cert --
1439
 
 *
1440
 
 *      Stock implementation for most of the SSLVerifyCb that is
1441
 
 *      passed to SSL_set_verify.
1442
 
 *
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
1446
 
 *      safely.
1447
 
 *
1448
 
 * Result:
1449
 
 *      TRUE - if the verification succeeded, and FALSE otherwise. The
1450
 
 *      verification error is stored in the SSLVerifyParam argument
1451
 
 *
1452
 
 *---------------------------------------------------------------------- 
1453
 
 */
1454
 
 
1455
 
Bool
1456
 
SSL_VerifyX509(SSLVerifyParam *verifyParam, void *x509Cert)
1457
 
{
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};
1462
 
   int ii;
1463
 
   char *pp = thumbprintString;
1464
 
 
1465
 
   verifyParam->selfSigned = 
1466
 
      !X509_NAME_cmp(X509_get_subject_name(cert), X509_get_issuer_name(cert));
1467
 
   verifyParam->hasError = FALSE;
1468
 
 
1469
 
   /*
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.
1475
 
    */
1476
 
   if (!X509_digest(cert, EVP_sha1(), md, &mdLen) || (0 == mdLen)) {
1477
 
      return FALSE;
1478
 
   }
1479
 
 
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;
1484
 
      }
1485
 
   }
1486
 
 
1487
 
   /*
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 
1492
 
    */
1493
 
   if (strncmp(thumbprintString, 
1494
 
               verifyParam->thumbprintString, 
1495
 
               SSL_V_THUMBPRINT_STRING_SIZE) == 0) {
1496
 
      /* 
1497
 
       * The request certificate signature matched the actual
1498
 
       * certificate signature. The user already knew about this
1499
 
       * certificate and was OK with it.
1500
 
       */
1501
 
      return TRUE;
1502
 
   }
1503
 
 
1504
 
   /*
1505
 
    * Copy the actual thumbprint into the SSL verify param and proceed
1506
 
    * with regular certificate verification 
1507
 
    */
1508
 
   strncpy(verifyParam->thumbprintString, thumbprintString, SSL_V_THUMBPRINT_STRING_SIZE);
1509
 
 
1510
 
#ifdef WIN32
1511
 
   {
1512
 
      unsigned char *certBytes = NULL;
1513
 
      unsigned char *pp;
1514
 
      int certLen;
1515
 
   
1516
 
 
1517
 
      /*
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 
1523
 
       */
1524
 
 
1525
 
      certLen = i2d_X509(cert, NULL);
1526
 
      certBytes = pp = (unsigned char *) malloc(certLen);
1527
 
      ASSERT_MEM_ALLOC(certBytes);
1528
 
      i2d_X509(cert, &pp);
1529
 
   
1530
 
      verifyParam->hasError = 
1531
 
         !SSLVerifyCertAgainstSystemStore(certBytes, certLen, verifyParam);
1532
 
      if (certBytes != NULL) {
1533
 
         free(certBytes);
1534
 
      }
1535
 
 
1536
 
      return !verifyParam->hasError;
1537
 
   }
1538
 
#else // #ifdef WIN32
1539
 
   if (SSL_GetVerifySSLCertificates() == SSL_VERIFY_CERTIFICATES_ON) {
1540
 
      /*
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
1544
 
       * thumbprint.
1545
 
       *
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
1550
 
       */
1551
 
 
1552
 
      char peerCN[0x200];
1553
 
 
1554
 
      X509_NAME_get_text_by_NID(X509_get_subject_name(cert), NID_commonName,
1555
 
                                peerCN, sizeof peerCN);             
1556
 
 
1557
 
      Warning("SSL_VerifyX509: Thumbprint mismatch for certificate "
1558
 
              "with subject name: %s, %s\n", peerCN, thumbprintString);
1559
 
 
1560
 
      return FALSE;                                                                       
1561
 
   } else {
1562
 
      /*
1563
 
       * The default verification action on Linux is to not verify SSL
1564
 
       * certificates, so we just return TRUE here.
1565
 
       */
1566
 
 
1567
 
      return TRUE;
1568
 
   }
1569
 
 
1570
 
#endif // #ifdef WIN32
1571
 
}
1572
 
 
1573
 
 
1574
 
/*
1575
 
 *----------------------------------------------------------------------
1576
 
 *
1577
 
 * SSL_SetCiphers --
1578
 
 *
1579
 
 *    Sets the ciphers to use for the default context. Overrides the
1580
 
 *    default cipher information.  This function should be called after
1581
 
 *    SSL_Init.
1582
 
 *
1583
 
 *----------------------------------------------------------------------
1584
 
 */
1585
 
 
1586
 
void
1587
 
SSL_SetCiphers(const char *ciphers) // IN: Cipher suite list
1588
 
{
1589
 
   ASSERT(ciphers != NULL);
1590
 
   ASSERT(SSLModuleInitialized);
1591
 
 
1592
 
   SSL_CTX_set_cipher_list(SSL_DefaultContext(), ciphers);
1593
 
}
1594
 
 
1595
 
 
1596
 
/*
1597
 
 *----------------------------------------------------------------------
1598
 
 *
1599
 
 * SSL_SetCerts --
1600
 
 *
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.
1604
 
 *
1605
 
 *----------------------------------------------------------------------
1606
 
 */
1607
 
 
1608
 
void
1609
 
SSL_SetCerts(const char *certFile, // IN: Certificate file
1610
 
             const char *keyFile)  // IN: Private Key File
1611
 
{
1612
 
   ASSERT(certFile != NULL || keyFile != NULL);
1613
 
   ASSERT(SSLModuleInitialized);
1614
 
 
1615
 
   if (certFile != NULL) {
1616
 
      free(SSLCertFile);
1617
 
      SSLCertFile = strdup(certFile);
1618
 
      ASSERT_MEM_ALLOC(SSLCertFile);
1619
 
   }
1620
 
 
1621
 
   if (keyFile != NULL) {
1622
 
      free(SSLKeyFile);
1623
 
      SSLKeyFile = strdup(keyFile);
1624
 
      ASSERT_MEM_ALLOC(SSLKeyFile);
1625
 
   }
1626
 
}
1627
 
 
1628
 
 
1629
 
/*
1630
 
 *----------------------------------------------------------------------
1631
 
 *
1632
 
 * SSL_Exit --
1633
 
 *
1634
 
 *      Destroys the default SSL session context.
1635
 
 *
1636
 
 * Results:
1637
 
 *      None.
1638
 
 *
1639
 
 * Side effects:
1640
 
 *      Stuff.
1641
 
 *
1642
 
 *----------------------------------------------------------------------
1643
 
 */
1644
 
 
1645
 
void
1646
 
SSL_Exit(void)
1647
 
{
1648
 
   if (SSLModuleInitialized) {
1649
 
      int numSslLocks = CRYPTO_num_locks(), i;
1650
 
 
1651
 
      BEGIN_NO_STACK_MALLOC_TRACKER;
1652
 
 
1653
 
      CRYPTO_set_locking_callback(NULL);
1654
 
      SSL_CTX_free(ssl_ctx);
1655
 
      ssl_ctx = NULL;
1656
 
 
1657
 
      /*
1658
 
       * Disable callbacks, or bad surprise happens when threads exit
1659
 
       * after SSL gets shut down, even if these threads have nothing
1660
 
       * common with SSL.
1661
 
       */
1662
 
      CRYPTO_set_add_lock_callback(NULL);
1663
 
      CRYPTO_set_locking_callback(NULL);
1664
 
 
1665
 
      for (i = 0; i < numSslLocks; ++i) {
1666
 
         SyncMutex_Destroy(&ssl_locks[i]);
1667
 
      }
1668
 
      free(ssl_locks);
1669
 
      ssl_locks = NULL;
1670
 
 
1671
 
      SSLModuleInitialized = FALSE;
1672
 
      free(SSLCertFile);
1673
 
      free(SSLKeyFile);
1674
 
      free(SSLDHParamsFiles[0]);
1675
 
      free(SSLDHParamsFiles[1]);
1676
 
      SSLCertFile = NULL;
1677
 
      SSLKeyFile = NULL;
1678
 
      SSLDHParamsFiles[0] = NULL;
1679
 
      SSLDHParamsFiles[1] = NULL;
1680
 
      END_NO_STACK_MALLOC_TRACKER;
1681
 
   }
1682
 
}
1683
 
 
1684
 
 
1685
 
#ifdef _WIN32
1686
 
/*
1687
 
 *----------------------------------------------------------------------
1688
 
 *
1689
 
 * SSLGetFileContents()
1690
 
 *
1691
 
 *    Given a file handle, allocate a buffer the size of the file and 
1692
 
 *    reads the entire file contents into it. 
1693
 
 *
1694
 
 *    On success, caller is responsible for deallocating the allocated 
1695
 
 *    buffer. 
1696
 
 *
1697
 
 * Results:
1698
 
 *    TRUE if successful, FALSE otherwise.
1699
 
 *
1700
 
 * Side effects:
1701
 
 *    None
1702
 
 *
1703
 
 *----------------------------------------------------------------------
1704
 
 */
1705
 
 
1706
 
static Bool
1707
 
SSLGetFileContents(HANDLE hFile,       // IN
1708
 
                   char **contents,    // OUT
1709
 
                   int *size)          // OUT
1710
 
{
1711
 
   int bytesRead, fileSize;
1712
 
   char *buf = NULL;
1713
 
 
1714
 
   fileSize = GetFileSize(hFile, NULL);
1715
 
   if (fileSize == INVALID_FILE_SIZE) {
1716
 
      goto error;
1717
 
   }
1718
 
 
1719
 
   buf = (char *)malloc(fileSize);
1720
 
   if (buf == NULL) {
1721
 
      Warning("Unable to allocate buffer.\n");
1722
 
      goto error;
1723
 
   }
1724
 
 
1725
 
   if (!ReadFile(hFile, buf, fileSize, &bytesRead, NULL)) {
1726
 
      goto error;
1727
 
   }
1728
 
 
1729
 
   ASSERT(bytesRead == fileSize);
1730
 
   *size = fileSize;
1731
 
   *contents = buf;
1732
 
   return TRUE;
1733
 
 
1734
 
error:
1735
 
   free(buf);
1736
 
   return FALSE;
1737
 
}  
1738
 
 
1739
 
 
1740
 
/*
1741
 
 *----------------------------------------------------------------------
1742
 
 *
1743
 
 * SSLCreateMemoryBIOFromFile --
1744
 
 *
1745
 
 *    Given a file handle, creates and memory BIO and populate it with
1746
 
 *    contents of the file.
1747
 
 *
1748
 
 *    On success, caller is responsible for deallocating the create 
1749
 
 *    BIO object.
1750
 
 *
1751
 
 * Results:
1752
 
 *    TRUE if successful, FALSE otherwise.
1753
 
 *
1754
 
 * Side effects:
1755
 
 *    None
1756
 
 *
1757
 
 *----------------------------------------------------------------------
1758
 
 */
1759
 
 
1760
 
static BIO *
1761
 
SSLCreateMemoryBIOFromFile(HANDLE hFile) 
1762
 
{
1763
 
   BIO *bio = NULL;
1764
 
   char *buf = NULL;
1765
 
   int size;
1766
 
 
1767
 
   bio = BIO_new(BIO_s_mem());
1768
 
   if (bio == NULL) {
1769
 
      Warning("Create BIO failed.\n");
1770
 
      return NULL;
1771
 
   }
1772
 
 
1773
 
   if (!SSLGetFileContents(hFile, &buf, &size)) {
1774
 
      Warning("Unable to read file.\n");
1775
 
      BIO_free(bio);
1776
 
      return NULL;
1777
 
   } else {
1778
 
      if (BIO_write(bio, buf, size) <= 0) { //VCV|C
1779
 
         Warning("Unable to write to BIO.\n");
1780
 
         free(buf);
1781
 
         BIO_free(bio);
1782
 
         return NULL;
1783
 
      }
1784
 
   }
1785
 
 
1786
 
   Warning("Create Memory BIO succeeded.\n");
1787
 
   free(buf);
1788
 
   return bio;
1789
 
}
1790
 
 
1791
 
#endif // WIN32
1792
 
 
1793
 
 
1794
 
/*
1795
 
 *----------------------------------------------------------------------
1796
 
 *
1797
 
 * SSLCreateMemoryBIOFromBuffer()
1798
 
 *
1799
 
 *    Given a buffer, creates and memory BIO and populate it with
1800
 
 *    contents of the buffer.
1801
 
 *
1802
 
 *    On success, caller is responsible for deallocating the create 
1803
 
 *    BIO object.
1804
 
 *
1805
 
 * Results:
1806
 
 *    TRUE if successful, FALSE otherwise.
1807
 
 *
1808
 
 * Side effects:
1809
 
 *    None
1810
 
 *
1811
 
 *----------------------------------------------------------------------
1812
 
 */
1813
 
 
1814
 
static BIO *
1815
 
SSLCreateMemoryBIOFromBuffer(char *buffer,
1816
 
                             int size) 
1817
 
{
1818
 
   BIO *bio = NULL;
1819
 
 
1820
 
   bio = BIO_new(BIO_s_mem());
1821
 
   if (bio == NULL) {
1822
 
      Warning("Create BIO failed.\n");
1823
 
      return NULL;
1824
 
   }
1825
 
 
1826
 
   if (buffer) {
1827
 
      if (BIO_write(bio, buffer, size) <= 0) {
1828
 
         Warning("Unable to write to BIO.\n");
1829
 
         BIO_free(bio);
1830
 
         return NULL;
1831
 
      }
1832
 
   }
1833
 
 
1834
 
//   SSL_LOG(("SSL: Create Memory BIO succeeded for buffer: %s\n", buffer));
1835
 
 
1836
 
   return bio;
1837
 
}
1838
 
 
1839
 
 
1840
 
/*
1841
 
 *----------------------------------------------------------------------
1842
 
 *
1843
 
 * SSLLoadCertificatesFromFile()
1844
 
 *
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__. 
1849
 
 *    
1850
 
 * Results:
1851
 
 *    TRUE on succes, FALSE on failure.
1852
 
 *
1853
 
 * Side effects:
1854
 
 *
1855
 
 *----------------------------------------------------------------------
1856
 
 */
1857
 
 
1858
 
 
1859
 
static Bool
1860
 
SSLLoadCertificatesFromFile(void)
1861
 
{
1862
 
   Bool success = FALSE;
1863
 
   char *certFile = SSLCertFile;
1864
 
   char *keyFile = SSLKeyFile;
1865
 
   uid_t uid;
1866
 
   SSL_CTX *ctx = SSL_DefaultContext();
1867
 
 
1868
 
   uid = Id_BeginSuperUser();
1869
 
 
1870
 
   /* Loads certificate */
1871
 
   SSL_LOG(("SSL: Loading certificate: '%s' ...\n", certFile));
1872
 
   if (!SSL_CTX_use_certificate_file(ctx, certFile, SSL_FILETYPE_PEM)) {
1873
 
      SSLPrintErrors();
1874
 
      Warning("Error loading server certificate\n");
1875
 
      goto cleanup;
1876
 
   }
1877
 
   SSL_LOG(("SSL: server certificate read\n"));
1878
 
 
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)) {
1882
 
      SSLPrintErrors();
1883
 
      Warning("Error loading server certificate\n");
1884
 
      goto cleanup;
1885
 
   }
1886
 
   SSL_LOG(("SSL: server private key read\n"));
1887
 
 
1888
 
   if (!SSL_CTX_check_private_key(ctx)) {
1889
 
      SSLPrintErrors();
1890
 
      Warning("Error verifying server certificate\n");
1891
 
      goto cleanup;
1892
 
   }
1893
 
   SSL_LOG(("SSL: server certificate verified\n"));
1894
 
 
1895
 
   success = TRUE;
1896
 
 
1897
 
cleanup:
1898
 
   Id_EndSuperUser(uid);
1899
 
 
1900
 
   return success;
1901
 
}
1902
 
 
1903
 
 
1904
 
/*
1905
 
 *----------------------------------------------------------------------
1906
 
 *
1907
 
 * SSLLoadCertificatesFromStore()
1908
 
 *
1909
 
 *    Loads the server's certificate & private key from system certificate
1910
 
 *    store on Windows, setting them up for use by the default context.
1911
 
 *
1912
 
 * Results:
1913
 
 *    TRUE on succes, FALSE on failure.
1914
 
 *
1915
 
 * Side effects:
1916
 
 *
1917
 
 *----------------------------------------------------------------------
1918
 
 */
1919
 
 
1920
 
#if _WIN32
1921
 
 
1922
 
static Bool
1923
 
SSLLoadCertificatesFromStore(void)
1924
 
{
1925
 
   Bool success = FALSE;
1926
 
   char *certFile = SSLCertFile;
1927
 
   char *keyFile = SSLKeyFile;
1928
 
   HANDLE hFile;
1929
 
   BIO *bio;
1930
 
   X509 *x509 = NULL;
1931
 
   EVP_PKEY *pkey = NULL;
1932
 
   SSL_CTX *ctx = SSL_DefaultContext();
1933
 
 
1934
 
   /* Loads certificate */
1935
 
   SSL_LOG(("SSL: Loading certificate: '%s' ...\n", certFile));
1936
 
   /*
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.
1940
 
    */
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");
1946
 
      goto cleanup;
1947
 
   }
1948
 
 
1949
 
   bio = SSLCreateMemoryBIOFromFile(hFile);
1950
 
 
1951
 
   CloseHandle(hFile);
1952
 
   hFile = INVALID_HANDLE_VALUE;
1953
 
 
1954
 
   if (bio == NULL) {
1955
 
      Warning("Error reading server certificate data\n");
1956
 
      goto cleanup;
1957
 
   }
1958
 
 
1959
 
   x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1960
 
   if (x509 == NULL) {
1961
 
      Warning("Error reading server certificate from BIO\n");
1962
 
      BIO_free(bio);
1963
 
      goto cleanup;
1964
 
   }
1965
 
 
1966
 
   BIO_free(bio);
1967
 
   bio = NULL;
1968
 
 
1969
 
   if (!SSL_CTX_use_certificate(ctx, x509)) {
1970
 
      X509_free(x509);
1971
 
      SSLPrintErrors();
1972
 
      Warning("Error loading server certificate\n");
1973
 
      goto cleanup;
1974
 
   }
1975
 
   X509_free(x509);
1976
 
   SSL_LOG(("SSL: server certificate read\n"));
1977
 
 
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");
1985
 
      success = FALSE;
1986
 
      goto cleanup;
1987
 
   }
1988
 
 
1989
 
   bio = SSLCreateMemoryBIOFromFile(hFile);
1990
 
   CloseHandle(hFile);
1991
 
   hFile = INVALID_HANDLE_VALUE;
1992
 
   if (bio == NULL) {
1993
 
      Warning("Error reading server private key data\n");
1994
 
      goto cleanup;
1995
 
   }
1996
 
 
1997
 
   pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
1998
 
   if (pkey == NULL) {
1999
 
      Warning("Error reading server private key from BIO\n");
2000
 
      BIO_free(bio);
2001
 
      goto cleanup;
2002
 
   }
2003
 
 
2004
 
   BIO_free(bio);
2005
 
 
2006
 
   if (!SSL_CTX_use_PrivateKey(ctx, pkey)) {
2007
 
      EVP_PKEY_free(pkey);
2008
 
      SSLPrintErrors();
2009
 
      Warning("Error reading server private key\n");
2010
 
      goto cleanup;
2011
 
   }
2012
 
   EVP_PKEY_free(pkey);
2013
 
   SSL_LOG(("SSL: server private key read\n"));
2014
 
 
2015
 
   if (!SSL_CTX_check_private_key(ctx)) {
2016
 
      SSLPrintErrors();
2017
 
      Warning("Error verifying server certificate\n");
2018
 
      goto cleanup;
2019
 
   }
2020
 
   SSL_LOG(("SSL: server certificate verified\n"));
2021
 
 
2022
 
   success = TRUE;
2023
 
 
2024
 
cleanup:
2025
 
   return success;
2026
 
}
2027
 
 
2028
 
 
2029
 
#endif
2030
 
 
2031
 
 
2032
 
/*
2033
 
 *----------------------------------------------------------------------
2034
 
 *
2035
 
 * SSLLoadCertificates()
2036
 
 *    Loads the server SSL certificate and private key.
2037
 
 *    
2038
 
 * Results:
2039
 
 *    TRUE on success, FALSE otherwise
2040
 
 *
2041
 
 * Side effects:
2042
 
 *
2043
 
 *----------------------------------------------------------------------
2044
 
 */
2045
 
 
2046
 
static Bool
2047
 
SSLLoadCertificates(Bool fromFile)
2048
 
{
2049
 
#if _WIN32
2050
 
   if (!fromFile) {
2051
 
      return SSLLoadCertificatesFromStore();
2052
 
   }
2053
 
#endif
2054
 
   return SSLLoadCertificatesFromFile();
2055
 
   
2056
 
}
2057
 
 
2058
 
/*
2059
 
 *----------------------------------------------------------------------
2060
 
 *
2061
 
 * SSL_New()
2062
 
 *
2063
 
 *    
2064
 
 * Results:
2065
 
 *    Returns a freshly allocated SSLSock structure.
2066
 
 *
2067
 
 * Side effects:
2068
 
 *
2069
 
 *----------------------------------------------------------------------
2070
 
 */
2071
 
 
2072
 
 SSLSock 
2073
 
SSL_New(int fd,
2074
 
        Bool closeFdOnShutdown)
2075
 
{
2076
 
   SSLSock sslConnection;
2077
 
   Bool ret;
2078
 
 
2079
 
   sslConnection = (SSLSock)calloc(1, sizeof(struct SSLSockStruct));
2080
 
   ASSERT_MEM_ALLOC(sslConnection);
2081
 
   sslConnection->fd = fd;
2082
 
   sslConnection->closeFdOnShutdown = closeFdOnShutdown;
2083
 
#ifdef VMX86_DEVEL
2084
 
   sslConnection->initialized = 12345;
2085
 
#endif /*VMX86_DEVEL*/
2086
 
   ret = SyncRecMutex_Init(&sslConnection->spinlock, NULL);
2087
 
   ASSERT_NOT_IMPLEMENTED(ret == TRUE);
2088
 
   return sslConnection;
2089
 
}
2090
 
 
2091
 
 
2092
 
/*
2093
 
 *----------------------------------------------------------------------
2094
 
 *
2095
 
 * SSL_Connect()
2096
 
 *
2097
 
 *    Initiates an SSL connection using current SSL context.
2098
 
 *
2099
 
 *    XXX should modify callers of this to code to check for
2100
 
 *    failure.  
2101
 
 *
2102
 
 *    Callers of this function don't expect an error, so cache failures
2103
 
 *    for later reporting during an SSL{Read|Write}.
2104
 
 *
2105
 
 * Results:
2106
 
 *    Returns TRUE on success, FALSE on failure.
2107
 
 *
2108
 
 * Side effects:
2109
 
 *
2110
 
 *----------------------------------------------------------------------
2111
 
 */
2112
 
 
2113
 
Bool
2114
 
SSL_Connect(SSLSock sSock) // IN: SSL socket
2115
 
{
2116
 
   Warning("SSL_Connect: SECURITY WARNING: Should use SSL_ConnectAndVerify instead\n");
2117
 
   return SSL_ConnectAndVerify(sSock, NULL);
2118
 
}
2119
 
 
2120
 
 
2121
 
/*
2122
 
 *----------------------------------------------------------------------
2123
 
 *
2124
 
 * SSL_ConnectAndVerify()
2125
 
 *
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.
2131
 
 *
2132
 
 *---------------------------------------------------------------------- 
2133
 
 */
2134
 
 
2135
 
Bool
2136
 
SSL_ConnectAndVerify(SSLSock sSock,               // IN: SSL socket
2137
 
                     SSLVerifyParam *verifyParam) // IN: Certificate validation parameters
2138
 
{
2139
 
   return SSL_ConnectAndVerifyWithContext(sSock, verifyParam, SSL_DefaultContext());
2140
 
}
2141
 
 
2142
 
 
2143
 
/*
2144
 
 *----------------------------------------------------------------------
2145
 
 *
2146
 
 * SSL_ConnectAndVerifyWithContext()
2147
 
 *
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.
2152
 
 *
2153
 
 *---------------------------------------------------------------------- 
2154
 
 */
2155
 
 
2156
 
Bool SSL_ConnectAndVerifyWithContext(SSLSock sSock,               // IN: SSL socket
2157
 
                                     SSLVerifyParam *verifyParam, // IN: Certification validation parameters
2158
 
                                     void *ctx)                   // IN: OpenSSL context (SSL_CTX *)
2159
 
{
2160
 
   int retVal;
2161
 
   Bool ret = TRUE;
2162
 
   time_t startTime;
2163
 
   ASSERT_BUG(37562, SSLModuleInitialized);
2164
 
   ASSERT(sSock);
2165
 
   ASSERT(ctx);
2166
 
   ASSERT_DEVEL(sSock->initialized == 12345);
2167
 
 
2168
 
   BEGIN_NO_STACK_MALLOC_TRACKER;
2169
 
 
2170
 
   sSock->sslCnx = SSL_new(ctx);
2171
 
   if (!sSock->sslCnx) {
2172
 
      SSLPrintErrors();
2173
 
      Warning("Error creating sslCnx from ctx\n");
2174
 
      sSock->connectionFailed = TRUE;
2175
 
      ret = FALSE;
2176
 
      goto end;
2177
 
   }
2178
 
   SSL_set_connect_state(sSock->sslCnx);
2179
 
 
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);
2184
 
   }
2185
 
 
2186
 
   SSL_LOG(("SSL: connect, ssl created %d\n", sSock->fd));
2187
 
   if (!SSL_set_fd(sSock->sslCnx, sSock->fd)) {
2188
 
      SSLPrintErrors();
2189
 
      Warning("Error setting fd for SSL connection\n");
2190
 
      sSock->connectionFailed = TRUE;
2191
 
      ret = FALSE;
2192
 
      goto end;
2193
 
   }
2194
 
   SSL_LOG(("SSL: connect fd set done\n"));
2195
 
 
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).
2201
 
    */
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);
2212
 
   }
2213
 
   
2214
 
   if (sSock->sslIOError != SSL_ERROR_NONE) {
2215
 
      SSLPrintErrors();
2216
 
      Warning("SSL: connect failed\n");
2217
 
      sSock->connectionFailed = TRUE;
2218
 
      ret = FALSE;
2219
 
      goto end;
2220
 
   }
2221
 
   SSL_LOG(("SSL: connect done\n"));
2222
 
 
2223
 
   SSLPrintCipher(sSock->sslCnx);
2224
 
    
2225
 
   sSock->encrypted = TRUE;
2226
 
 
2227
 
  end:
2228
 
   if (sSock->sslCnx != NULL) {
2229
 
      SSL_set_ex_data(sSock->sslCnx, SSLVerifyParamIx, NULL);
2230
 
   }
2231
 
 
2232
 
   END_NO_STACK_MALLOC_TRACKER;
2233
 
 
2234
 
   return ret;
2235
 
}
2236
 
 
2237
 
 
2238
 
/*
2239
 
 *----------------------------------------------------------------------
2240
 
 *
2241
 
 * SSL_SetCertChain --
2242
 
 *
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
2245
 
 *    chain certs.
2246
 
 *
2247
 
 *
2248
 
 * Results:
2249
 
 *    None
2250
 
 *
2251
 
 *
2252
 
 * Side effects:
2253
 
 *    New certs in SSL context
2254
 
 *
2255
 
 *
2256
 
 *----------------------------------------------------------------------
2257
 
 */
2258
 
 
2259
 
void
2260
 
SSL_SetCertChain(char **certChain,        // IN
2261
 
                 int numCerts)            // IN
2262
 
{
2263
 
   int index;
2264
 
   int ret;
2265
 
   BIO *bioCert = NULL;
2266
 
   X509 *cert = NULL;
2267
 
   SSL_CTX *ctx = SSL_DefaultContext();
2268
 
 
2269
 
   SSL_LOG(("SSL: Adding %d certs as a chain\n", numCerts));
2270
 
 
2271
 
   if (numCerts == 0) {
2272
 
      goto end;
2273
 
   }
2274
 
 
2275
 
   ASSERT(certChain);
2276
 
   ASSERT(certChain[0]);
2277
 
 
2278
 
   SSL_LOG(("SSL: Adding leaf cert\n%s\n", certChain[0]));
2279
 
 
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");
2285
 
      goto end;
2286
 
   }
2287
 
 
2288
 
   cert = PEM_read_bio_X509(bioCert, NULL, 0, NULL);
2289
 
   BIO_free(bioCert);
2290
 
   if (cert == NULL) {
2291
 
      Warning("SSL: Invalid certificate in chain (0):\n%s\n", certChain[0]);
2292
 
      SSLPrintErrors();
2293
 
      goto end;
2294
 
   }
2295
 
 
2296
 
   ret = SSL_CTX_use_certificate(ctx, cert);
2297
 
   X509_free(cert);
2298
 
   if (!ret) {
2299
 
      Warning("SSL: Failed to use certificate (0):\n%s\n", certChain[0]);
2300
 
      SSLPrintErrors();
2301
 
      goto end;
2302
 
   }
2303
 
   
2304
 
   /*
2305
 
    * Add the rest of the certificates as part of the chain
2306
 
    */
2307
 
 
2308
 
   for (index = 1; index < numCerts; index++) {
2309
 
 
2310
 
      SSL_LOG(("SSL: Adding chain cert\n%s\n", certChain[index]));
2311
 
 
2312
 
      bioCert = SSLCreateMemoryBIOFromBuffer(certChain[index],
2313
 
                                             (int)(strlen(certChain[index]) + 1));
2314
 
      if (bioCert == NULL) {
2315
 
         Warning("SSL: Failed to create BIO");
2316
 
         goto end;
2317
 
      }
2318
 
 
2319
 
      cert = PEM_read_bio_X509(bioCert, NULL, 0, NULL);
2320
 
      BIO_free(bioCert);
2321
 
 
2322
 
      if (cert == NULL) {
2323
 
         Warning("SSL: Invalid certificate in chain (%d):\n%s",
2324
 
                 index, certChain[index]);
2325
 
         SSLPrintErrors();
2326
 
         goto end;
2327
 
      }
2328
 
 
2329
 
      /* Call to SSL_CTX_add_extra_chain_cert */
2330
 
      ret = SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, (char *)cert);
2331
 
      X509_free(cert);
2332
 
      if (!ret) {
2333
 
         Warning("SSL: Failed to use certificate (%d): %s",
2334
 
                 index, certChain[index]);
2335
 
         SSLPrintErrors();
2336
 
         goto end;
2337
 
      }
2338
 
   } /* Loop over cert chain */
2339
 
 
2340
 
   SSL_LOG(("SSL: Done adding chain certs\n"));
2341
 
 
2342
 
end:
2343
 
 
2344
 
   return;
2345
 
}
2346
 
 
2347
 
 
2348
 
/*
2349
 
 *----------------------------------------------------------------------
2350
 
 *
2351
 
 * SSL_CheckCert --
2352
 
 *
2353
 
 *    Checks that the common name of the peer cert matches
2354
 
 *    the hostname
2355
 
 *
2356
 
 *
2357
 
 * Results:
2358
 
 *    Returns TRUE on success, FALSE on failure.
2359
 
 *
2360
 
 *
2361
 
 * Side effects:
2362
 
 *
2363
 
 *----------------------------------------------------------------------
2364
 
 */
2365
 
 
2366
 
Bool
2367
 
SSL_CheckCert(SSLSock sSock,         // IN
2368
 
              char *host,            // IN
2369
 
              Bool allowSelfSigned)  // IN
2370
 
{
2371
 
   X509 *peerCert = NULL;
2372
 
   char peerCN[256];
2373
 
   Bool ret = FALSE;
2374
 
   int rslt = 0;
2375
 
 
2376
 
   ASSERT(sSock);
2377
 
   ASSERT(sSock->sslCnx);
2378
 
 
2379
 
   SSL_LOG(("SSL: Peer Cert Check start\n"));
2380
 
   rslt = SSL_get_verify_result(sSock->sslCnx);
2381
 
 
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))) {
2386
 
         
2387
 
         Warning("SSL: Self signed certificate in chain\n");
2388
 
      } else {
2389
 
         Warning("SSL: Peer certificate does not verify (%d)\n", rslt);
2390
 
         goto end;
2391
 
      }
2392
 
   }
2393
 
 
2394
 
   peerCert = SSL_get_peer_certificate(sSock->sslCnx);
2395
 
   if (peerCert == NULL) {
2396
 
      Warning("SSL: Could not get the peer certificate\n");
2397
 
      goto end;
2398
 
   }
2399
 
 
2400
 
   X509_NAME_get_text_by_NID(X509_get_subject_name(peerCert),
2401
 
                               NID_commonName,
2402
 
                               peerCN,
2403
 
                               256);
2404
 
 
2405
 
   if (strcasecmp(peerCN, host)) {
2406
 
      Warning("SSL: Peer common name does not match host (%s != %s)!\n",
2407
 
              peerCN, host);
2408
 
      goto end;
2409
 
   }
2410
 
 
2411
 
   /* All checks passed */
2412
 
   ret = TRUE;
2413
 
 
2414
 
end:
2415
 
   SSL_LOG(("SSL: Peer Cert Check end\n"));
2416
 
 
2417
 
   X509_free(peerCert);
2418
 
   return ret;
2419
 
}
2420
 
 
2421
 
 
2422
 
/*
2423
 
 *----------------------------------------------------------------------
2424
 
 *
2425
 
 * SSL_Accept()
2426
 
 *
2427
 
 *    Accepts an SSL connection using default SSL context.
2428
 
 *    
2429
 
 *    XXX should modify callers of this to code to check for
2430
 
 *    failure.
2431
 
 *
2432
 
 *    Callers of this function don't expect an error, so cache failures
2433
 
 *    for later reporting during an SSL{Read|Write}.
2434
 
 *
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.
2442
 
 *
2443
 
 * Results:
2444
 
 *    Returns TRUE on success, FALSE on failure.  
2445
 
 *
2446
 
 * Side effects:
2447
 
 *    The server's certificate & private key may be loaded from disk.
2448
 
 *
2449
 
 *----------------------------------------------------------------------
2450
 
 */
2451
 
 
2452
 
Bool
2453
 
SSL_Accept(SSLSock sSock) // IN: SSL socket
2454
 
{
2455
 
   return SSL_AcceptWithContext(sSock, SSL_DefaultContext());
2456
 
}
2457
 
 
2458
 
 
2459
 
/*
2460
 
 *----------------------------------------------------------------------
2461
 
 *
2462
 
 * SSL_AcceptWithContext()
2463
 
 *
2464
 
 *    Accepts an SSL connection using the passed SSL context.
2465
 
 *    
2466
 
 *    XXX should modify callers of this to code to check for
2467
 
 *    failure.
2468
 
 *
2469
 
 *    Callers of this function don't expect an error, so cache failures
2470
 
 *    for later reporting during an SSL{Read|Write}.
2471
 
 *
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.
2479
 
 *
2480
 
 * Results:
2481
 
 *    Returns TRUE on success, FALSE on failure.  
2482
 
 *
2483
 
 * Side effects:
2484
 
 *    The server's certificate & private key may be loaded from disk.
2485
 
 *
2486
 
 *----------------------------------------------------------------------
2487
 
 */
2488
 
 
2489
 
Bool SSL_AcceptWithContext(SSLSock sSock, // IN: SSL socket
2490
 
                           void *ctx)     // IN: OpenSSL context (SSL_CTX *)
2491
 
{
2492
 
   static Bool acceptInitialized = FALSE; 
2493
 
   Bool ret = TRUE;
2494
 
   int sslRet;
2495
 
 
2496
 
   ASSERT(SSLModuleInitialized);
2497
 
   ASSERT(sSock);
2498
 
   ASSERT_DEVEL(sSock->initialized == 12345);
2499
 
   ASSERT(ctx);
2500
 
 
2501
 
   BEGIN_NO_STACK_MALLOC_TRACKER;
2502
 
 
2503
 
   if (!acceptInitialized) {
2504
 
      if (!SSLLoadCertificates(loadCertificatesFromFile) && requireCertificates) {
2505
 
         sSock->connectionFailed = TRUE;
2506
 
         ret = FALSE;
2507
 
         goto end;
2508
 
      }
2509
 
      acceptInitialized = TRUE;
2510
 
   }
2511
 
 
2512
 
   sSock->sslCnx = SSL_new(ctx);
2513
 
   if (!sSock->sslCnx) {
2514
 
      SSLPrintErrors();
2515
 
      Warning("Error Creating SSL connection structure\n");
2516
 
      sSock->connectionFailed = TRUE;
2517
 
      ret = FALSE;
2518
 
      goto end;
2519
 
   }
2520
 
   SSL_set_accept_state(sSock->sslCnx);
2521
 
 
2522
 
   SSL_LOG(("SSL: ssl created\n"));
2523
 
   if (!SSL_set_fd(sSock->sslCnx, sSock->fd)) {
2524
 
      SSLPrintErrors();
2525
 
      Warning("Error setting fd for SSL connection\n");
2526
 
      sSock->connectionFailed = TRUE;
2527
 
      ret = FALSE;
2528
 
      goto end;
2529
 
   }
2530
 
   SSL_LOG(("SSL: fd set done\n"));
2531
 
 
2532
 
  /*
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.
2537
 
   */
2538
 
 
2539
 
   /*
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.
2544
 
    */
2545
 
 
2546
 
   sslRet = SSL_accept(sSock->sslCnx);
2547
 
   sSock->sslIOError = SSL_get_error(sSock->sslCnx, sslRet);
2548
 
   sSock->encrypted = TRUE;
2549
 
 
2550
 
  end:
2551
 
   END_NO_STACK_MALLOC_TRACKER;
2552
 
 
2553
 
   return ret;
2554
 
}
2555
 
 
2556
 
/*
2557
 
 *----------------------------------------------------------------------
2558
 
 *
2559
 
 * SSL_Read --
2560
 
 *
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.
2564
 
 *
2565
 
 * Results:
2566
 
 *    Returns the number of bytes read, or -1 on error.  The
2567
 
 *    data read will be placed in buf.
2568
 
 *
2569
 
 * Side effects:
2570
 
 *
2571
 
 *
2572
 
 *----------------------------------------------------------------------
2573
 
 */
2574
 
 
2575
 
ssize_t 
2576
 
SSL_Read(SSLSock ssl,
2577
 
         char *buf,
2578
 
         size_t num)
2579
 
{
2580
 
   int ret;
2581
 
   ASSERT(ssl);
2582
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2583
 
 
2584
 
   BEGIN_NO_STACK_MALLOC_TRACKER;
2585
 
 
2586
 
   if (ssl->connectionFailed) {
2587
 
      SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
2588
 
      ret = SOCKET_ERROR;
2589
 
      goto end;
2590
 
   }
2591
 
 
2592
 
   if (ssl->encrypted) {
2593
 
      int result = SSL_read(ssl->sslCnx, buf, (int)num);
2594
 
 
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;
2600
 
      }
2601
 
      ret = result;
2602
 
   } else {
2603
 
#ifdef __APPLE__
2604
 
blocking:
2605
 
#endif
2606
 
      ret = SSLGeneric_read(ssl->fd, buf, (int)num);
2607
 
 
2608
 
#ifdef __APPLE__
2609
 
      /*
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.
2617
 
       */
2618
 
      if (ret == 0) {
2619
 
         ssize_t writeRet;
2620
 
         Bool ignoreError = FALSE;
2621
 
 
2622
 
#ifdef VMX86_DEBUG
2623
 
         struct stat statBuffer;
2624
 
 
2625
 
         /*
2626
 
          * Make sure we're using a socket.
2627
 
          */
2628
 
         ASSERT((fstat(ssl->fd, &statBuffer) == 0) &&
2629
 
                ((statBuffer.st_mode & S_IFSOCK) == S_IFSOCK));
2630
 
         
2631
 
#endif
2632
 
         writeRet = write(ssl->fd, "", 0);
2633
 
         if (writeRet == 0) {
2634
 
            char const *workaroundEnv;
2635
 
 
2636
 
            /*
2637
 
             * The socket is still good.  read(2) should not have
2638
 
             * returned zero.
2639
 
             */
2640
 
            if (! ssl->loggedKernelReadBug) {
2641
 
               Log("Error: Encountered Apple bug #5202831.  Disconnecting.\n");
2642
 
               ssl->loggedKernelReadBug = TRUE;
2643
 
            }
2644
 
 
2645
 
            /*
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.
2654
 
             *
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.
2659
 
             */
2660
 
#if __APPLE_READ_BUG_WORKAROUND__
2661
 
            if (ssl->errorHook) {
2662
 
               ignoreError = (ssl->errorHook)(ssl, ssl->errorHookContext);
2663
 
            }
2664
 
#endif
2665
 
 
2666
 
            /*
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
2670
 
             * need).
2671
 
             */
2672
 
            if (!ignoreError) {
2673
 
               workaroundEnv = Posix_Getenv("VMWARE_SOCKET_WORKAROUND");
2674
 
               if (workaroundEnv != NULL &&
2675
 
                   Str_Strcasecmp(workaroundEnv, "YES") == 0) {
2676
 
                  ignoreError = TRUE;
2677
 
               }
2678
 
            }
2679
 
 
2680
 
            if (ignoreError) {
2681
 
               int fcntlFlags;
2682
 
 
2683
 
               fcntlFlags = fcntl(ssl->fd, F_GETFL, 0);
2684
 
               if ((fcntlFlags & O_NONBLOCK) == O_NONBLOCK) {
2685
 
                  /*
2686
 
                   * The socket is not blocking, so let's pretend this
2687
 
                   * is EAGAIN to make everyone happy.
2688
 
                   */
2689
 
                  ret = -1;
2690
 
                  errno = EAGAIN;
2691
 
               } else {
2692
 
                  /*
2693
 
                   * The socket is blocking.  Spin until we get
2694
 
                   * real data or an end-of-stream where write(2) fails.
2695
 
                   */
2696
 
                  goto blocking;
2697
 
               }
2698
 
            }
2699
 
         }
2700
 
      }
2701
 
#endif
2702
 
   }
2703
 
 
2704
 
  end:
2705
 
   END_NO_STACK_MALLOC_TRACKER;
2706
 
   return ret;
2707
 
}
2708
 
 
2709
 
 
2710
 
/*
2711
 
 *----------------------------------------------------------------------
2712
 
 *
2713
 
 * SSL_Write()
2714
 
 *
2715
 
 *    Functional equivalent of the write() syscall. 
2716
 
 *    
2717
 
 *
2718
 
 * Results:
2719
 
 *    Returns the number of bytes written, or -1 on error.  
2720
 
 *
2721
 
 * Side effects:
2722
 
 *
2723
 
 *----------------------------------------------------------------------
2724
 
 */
2725
 
 
2726
 
ssize_t 
2727
 
SSL_Write(SSLSock ssl,
2728
 
          const char *buf,
2729
 
          size_t num)
2730
 
{
2731
 
   int ret;
2732
 
   ASSERT(ssl);
2733
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2734
 
 
2735
 
   BEGIN_NO_STACK_MALLOC_TRACKER;
2736
 
 
2737
 
   if (ssl->connectionFailed) {
2738
 
      SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
2739
 
      ret = SOCKET_ERROR;
2740
 
      goto end;
2741
 
   }
2742
 
   if (ssl->encrypted) {
2743
 
      int result = SSL_write(ssl->sslCnx, buf, (int)num);
2744
 
 
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;
2749
 
      }
2750
 
      ret = result;
2751
 
   } else {
2752
 
      ret = SSLGeneric_write(ssl->fd, buf, (int)num);
2753
 
   }
2754
 
 
2755
 
  end:
2756
 
   END_NO_STACK_MALLOC_TRACKER;
2757
 
   return ret;
2758
 
}
2759
 
 
2760
 
 
2761
 
/*
2762
 
 *----------------------------------------------------------------------
2763
 
 *
2764
 
 * SSL_Pending()
2765
 
 *      
2766
 
 *      Functional equivalent of select when SSL is enabled
2767
 
 *      
2768
 
 * Results:
2769
 
 *      Obtain number of readable bytes buffered in an SSL object if SSL
2770
 
 *      is enabled, otherwise, return 0
2771
 
 *
2772
 
 * Side effects:
2773
 
 *
2774
 
 *----------------------------------------------------------------------
2775
 
 */
2776
 
 
2777
 
int 
2778
 
SSL_Pending(SSLSock ssl) // IN
2779
 
{
2780
 
   int ret;
2781
 
   ASSERT(ssl);
2782
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2783
 
 
2784
 
   BEGIN_NO_STACK_MALLOC_TRACKER;
2785
 
 
2786
 
   if (ssl->encrypted) {
2787
 
      ret = SSL_pending(ssl->sslCnx);
2788
 
   } else {
2789
 
      ret = 0;
2790
 
   }
2791
 
 
2792
 
   END_NO_STACK_MALLOC_TRACKER;
2793
 
   return ret;
2794
 
}
2795
 
 
2796
 
 
2797
 
/*
2798
 
 *----------------------------------------------------------------------
2799
 
 *
2800
 
 * SSL_Shutdown()
2801
 
 *
2802
 
 *    Functional equivalent of the close() syscall.  Does
2803
 
 *    not close the actual fd used for the connection.
2804
 
 *    
2805
 
 *
2806
 
 * Results:
2807
 
 *    0 on success, -1 on failure.
2808
 
 *
2809
 
 * Side effects:
2810
 
 *    closes the SSL connection, freeing up the memory associated
2811
 
 *    with the passed in ssl object
2812
 
 *
2813
 
 *----------------------------------------------------------------------
2814
 
 */
2815
 
 
2816
 
int 
2817
 
SSL_Shutdown(SSLSock ssl)
2818
 
{
2819
 
   int retVal = 0;
2820
 
   ASSERT(ssl);
2821
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2822
 
#ifdef VMX86_DEVEL
2823
 
   ssl->initialized = 0;
2824
 
#endif 
2825
 
 
2826
 
   BEGIN_NO_STACK_MALLOC_TRACKER;
2827
 
 
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);
2833
 
   }
2834
 
 
2835
 
   if (ssl->closeFdOnShutdown) {
2836
 
      SSL_LOG(("SSL: Trying to close %d\n", ssl->fd));
2837
 
      retVal = SSLGeneric_close(ssl->fd);
2838
 
   }
2839
 
 
2840
 
   END_NO_STACK_MALLOC_TRACKER;
2841
 
 
2842
 
   SyncRecMutex_Destroy(&ssl->spinlock);
2843
 
 
2844
 
   free(ssl);
2845
 
   SSL_LOG(("SSL: shutdown done\n"));
2846
 
   return retVal;
2847
 
}
2848
 
 
2849
 
 
2850
 
/*
2851
 
 *----------------------------------------------------------------------
2852
 
 *
2853
 
 * SSL_GetFd()
2854
 
 *
2855
 
 *    Returns an SSL socket's file descriptor or handle.    
2856
 
 *
2857
 
 * Side effects:
2858
 
 *    None.
2859
 
 *
2860
 
 *----------------------------------------------------------------------
2861
 
 */
2862
 
 
2863
 
int 
2864
 
SSL_GetFd(SSLSock ssl) // IN
2865
 
{
2866
 
   ASSERT(ssl);
2867
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2868
 
 
2869
 
   return ssl->fd;
2870
 
}
2871
 
 
2872
 
 
2873
 
/*
2874
 
 *----------------------------------------------------------------------
2875
 
 *
2876
 
 * SSL_SetMode()
2877
 
 *   
2878
 
 *    Wrapper around SSL_set_mode.
2879
 
 *
2880
 
 * Results:
2881
 
 *    Return value of SSL_set_mode.
2882
 
 *
2883
 
 * Side effects:
2884
 
 *    None.
2885
 
 *
2886
 
 *----------------------------------------------------------------------
2887
 
 */
2888
 
 
2889
 
long
2890
 
SSL_SetMode(SSLSock ssl, long mode)
2891
 
{
2892
 
   ASSERT(ssl);
2893
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2894
 
   ASSERT(ssl->sslCnx);
2895
 
 
2896
 
   return SSL_set_mode(ssl->sslCnx, mode);
2897
 
}
2898
 
 
2899
 
 
2900
 
/*
2901
 
 *----------------------------------------------------------------------
2902
 
 *
2903
 
 * SSL_Want()
2904
 
 *   
2905
 
 *    Wrapper around SSL_want.
2906
 
 *
2907
 
 * Results:
2908
 
 *    That of SSL_want.
2909
 
 *
2910
 
 * Side effects:
2911
 
 *    None.
2912
 
 *
2913
 
 *----------------------------------------------------------------------
2914
 
 */
2915
 
 
2916
 
int
2917
 
SSL_Want(const SSLSock ssl)
2918
 
{
2919
 
   ASSERT(ssl);
2920
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2921
 
   ASSERT(ssl->sslCnx);
2922
 
 
2923
 
   return SSL_want(ssl->sslCnx);
2924
 
}
2925
 
 
2926
 
 
2927
 
/*
2928
 
 *----------------------------------------------------------------------
2929
 
 *
2930
 
 * SSL_WantWrite()
2931
 
 *   
2932
 
 *    Wrapper around SSL_want_write.
2933
 
 *
2934
 
 * Results:
2935
 
 *    That of SSL_want_write.
2936
 
 *
2937
 
 * Side effects:
2938
 
 *    None.
2939
 
 *
2940
 
 *----------------------------------------------------------------------
2941
 
 */
2942
 
 
2943
 
int
2944
 
SSL_WantWrite(const SSLSock ssl)
2945
 
{
2946
 
   ASSERT(ssl);
2947
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2948
 
   ASSERT(ssl->sslCnx);
2949
 
 
2950
 
   return SSL_want_write(ssl->sslCnx);
2951
 
}
2952
 
 
2953
 
 
2954
 
/*
2955
 
 *----------------------------------------------------------------------
2956
 
 *
2957
 
 * SSL_WantRead()
2958
 
 *   
2959
 
 *    Wrapper around SSL_want_read.
2960
 
 *
2961
 
 * Results:
2962
 
 *    That of SSL_want_read.
2963
 
 *
2964
 
 * Side effects:
2965
 
 *    None.
2966
 
 *
2967
 
 *----------------------------------------------------------------------
2968
 
 */
2969
 
 
2970
 
int
2971
 
SSL_WantRead(const SSLSock ssl)
2972
 
{
2973
 
   ASSERT(ssl);
2974
 
   ASSERT_DEVEL(ssl->initialized == 12345);
2975
 
   ASSERT(ssl->sslCnx);
2976
 
 
2977
 
   return SSL_want_read(ssl->sslCnx);
2978
 
}
2979
 
 
2980
 
 
2981
 
/*
2982
 
 *----------------------------------------------------------------------
2983
 
 *
2984
 
 * SSLSafeIO()
2985
 
 *
2986
 
 *    Perform an SSL IO operation and store error information in the SSLSock
2987
 
 *    structure, for later use by subsequest SSLSafeIO calls.
2988
 
 *
2989
 
 *    Best practices:
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.
2993
 
 *
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.
2997
 
 *
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.
3000
 
 *
3001
 
 *    - SSLSafeIO should be used only for non-blocking IO. Blocking IO must use
3002
 
 *      SSL_Read and SSL_Write.
3003
 
 *
3004
 
 *
3005
 
 * Results:
3006
 
 *    Returns < 0 on irrecoverable error.
3007
 
 *    Returns > 0 on success.
3008
 
 *    Returns 0 when the operation must be retried.
3009
 
 *
3010
 
 * Side effects:
3011
 
 *   None.
3012
 
 *----------------------------------------------------------------------
3013
 
 */
3014
 
 
3015
 
static ssize_t
3016
 
SSLSafeIO(SSLSock ssl,
3017
 
          void *buf,
3018
 
          size_t num,
3019
 
          Bool sslread)
3020
 
{
3021
 
   IOState thisInprogress, otherInprogress;
3022
 
   IOState ioState;
3023
 
   Bool safe = FALSE;
3024
 
   ssize_t ret = 0;
3025
 
 
3026
 
   ASSERT(ssl);
3027
 
   ASSERT(ssl->sslCnx);
3028
 
   ASSERT_DEVEL(ssl->initialized == 12345);
3029
 
   ASSERT(ssl->encrypted);
3030
 
 
3031
 
   BEGIN_NO_STACK_MALLOC_TRACKER;
3032
 
 
3033
 
   if (ssl->connectionFailed) {
3034
 
      SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
3035
 
      ret = SOCKET_ERROR;
3036
 
      goto end;
3037
 
   }
3038
 
 
3039
 
   if (sslread) {
3040
 
      thisInprogress = IOSTATE_READ_INPROGRESS;
3041
 
      otherInprogress = IOSTATE_WRITE_INPROGRESS;
3042
 
   } else {
3043
 
      thisInprogress = IOSTATE_WRITE_INPROGRESS;
3044
 
      otherInprogress = IOSTATE_READ_INPROGRESS;
3045
 
   }
3046
 
   
3047
 
   if (!SyncRecMutex_Trylock(&ssl->spinlock)) {
3048
 
      /* Another thread has locked this SSLSock. Caller should retry. */
3049
 
      goto end;
3050
 
   }
3051
 
 
3052
 
   if (ssl->ioState != otherInprogress) {
3053
 
      safe = TRUE;
3054
 
   }
3055
 
   ioState = ssl->ioState;
3056
 
 
3057
 
   if (safe) {
3058
 
      /* Safe to proceed with IO operation. */
3059
 
 
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);
3064
 
 
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;
3070
 
            }
3071
 
            break;
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;
3077
 
            }
3078
 
            ret = 0;
3079
 
            break;
3080
 
         default:
3081
 
            /* Irrecoverable error. */
3082
 
            /* XXX: SSL_ERROR_WANT_X509_LOOKUP is not handled yet. */
3083
 
            SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
3084
 
            ret = SOCKET_ERROR;
3085
 
            ssl->connectionFailed = TRUE;
3086
 
            break;
3087
 
      }
3088
 
   }
3089
 
 
3090
 
   SyncRecMutex_Unlock(&ssl->spinlock);
3091
 
 
3092
 
end:
3093
 
   END_NO_STACK_MALLOC_TRACKER;
3094
 
   return ret;
3095
 
}
3096
 
 
3097
 
/*
3098
 
 *----------------------------------------------------------------------
3099
 
 *
3100
 
 * SSL_SafeRead()
3101
 
 *
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.
3105
 
 *
3106
 
 * Results:
3107
 
 *    Returns number of bytes read into the given buffer, which may be 0.
3108
 
 *    Returns < 0 on irrecoverable error.
3109
 
 *
3110
 
 * Side effects:
3111
 
 *    None.
3112
 
 *
3113
 
 *----------------------------------------------------------------------
3114
 
 */
3115
 
 
3116
 
ssize_t
3117
 
SSL_SafeRead(SSLSock ssl,
3118
 
             void *buf,
3119
 
             size_t num)
3120
 
{
3121
 
   return SSLSafeIO(ssl, buf, num, TRUE);
3122
 
}
3123
 
 
3124
 
 
3125
 
/* 
3126
 
 *----------------------------------------------------------------------
3127
 
 *
3128
 
 * SSL_SafeWrite()
3129
 
 *
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.
3133
 
 *
3134
 
 * Results:
3135
 
 *    Return the number of bytes written, which may be 0, if none were written. 
3136
 
 *    On irrecoverable error, returns < 0.
3137
 
 *
3138
 
 * Side effects:
3139
 
 *    None.
3140
 
 *
3141
 
 *----------------------------------------------------------------------
3142
 
 */
3143
 
 
3144
 
ssize_t
3145
 
SSL_SafeWrite(SSLSock ssl,
3146
 
              void *buf,
3147
 
              size_t num)
3148
 
{
3149
 
   return SSLSafeIO(ssl, buf, num, FALSE);
3150
 
}
3151
 
 
3152
 
 
3153
 
/*
3154
 
 *----------------------------------------------------------------------
3155
 
 *
3156
 
 * SSL_CompleteAccept()
3157
 
 *
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.
3161
 
 *
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.
3167
 
 *
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
3173
 
 *    to change.
3174
 
 *
3175
 
 * Results:
3176
 
 *    TRUE if the SSL_accept completed successfully. FALSE otherwise.
3177
 
 *
3178
 
 * Side effects:
3179
 
 *    None.
3180
 
 *
3181
 
 *----------------------------------------------------------------------
3182
 
 */
3183
 
 
3184
 
Bool
3185
 
SSL_CompleteAccept(SSLSock ssl)
3186
 
{
3187
 
   ASSERT(ssl);
3188
 
   ASSERT(ssl->sslCnx);
3189
 
 
3190
 
   if (ssl->connectionFailed) {
3191
 
      SSLSetSystemError(SSL_SOCK_LOST_CONNECTION);
3192
 
      return FALSE;
3193
 
   }
3194
 
 
3195
 
   while (1) {
3196
 
      int sslRet;
3197
 
 
3198
 
      switch (ssl->sslIOError) {
3199
 
         case SSL_ERROR_NONE:
3200
 
            return TRUE;
3201
 
         case SSL_ERROR_WANT_READ:
3202
 
         case SSL_ERROR_WANT_WRITE:
3203
 
            usleep(SSL_WAIT_TIME * 1000);
3204
 
            break;
3205
 
         default:
3206
 
            ssl->connectionFailed = TRUE;
3207
 
            return FALSE;
3208
 
      }
3209
 
      sslRet = SSL_accept(ssl->sslCnx);
3210
 
      ssl->sslIOError = SSL_get_error(ssl->sslCnx, sslRet);
3211
 
   }
3212
 
 
3213
 
   return FALSE;
3214
 
}
3215
 
 
3216
 
 
3217
 
/*
3218
 
 *----------------------------------------------------------------------
3219
 
 *
3220
 
 * SSL_SetRequireCerts()
3221
 
 *    
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.
3225
 
 *
3226
 
 * Results:
3227
 
 *    Nothing.
3228
 
 *
3229
 
 * Side effects:
3230
 
 *    None.
3231
 
 *
3232
 
 *----------------------------------------------------------------------
3233
 
 */
3234
 
 
3235
 
void
3236
 
SSL_SetRequireCerts(Bool required) // IN
3237
 
{
3238
 
   ASSERT(SSLModuleInitialized);
3239
 
   requireCertificates = required;
3240
 
}
3241
 
 
3242
 
 
3243
 
/*
3244
 
 *----------------------------------------------------------------------
3245
 
 *
3246
 
 * SSL_SetLoadCertificatesFromFile()
3247
 
 *    
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.
3252
 
 *
3253
 
 * Results:
3254
 
 *    Nothing.
3255
 
 *
3256
 
 * Side effects:
3257
 
 *    None.
3258
 
 *
3259
 
 *----------------------------------------------------------------------
3260
 
 */
3261
 
 
3262
 
void
3263
 
SSL_SetLoadCertificatesFromFile(Bool value)
3264
 
{
3265
 
   ASSERT(SSLModuleInitialized);
3266
 
   loadCertificatesFromFile = value;
3267
 
}
3268
 
 
3269
 
 
3270
 
/*
3271
 
 *----------------------------------------------------------------------
3272
 
 *
3273
 
 * SSL_SetDHParamFiles()
3274
 
 *    
3275
 
 *    Sets the DH parameter file paths.
3276
 
 *
3277
 
 * Results:
3278
 
 *    Nothing.
3279
 
 *
3280
 
 * Side effects:
3281
 
 *    None.
3282
 
 *
3283
 
 *----------------------------------------------------------------------
3284
 
 */
3285
 
 
3286
 
void
3287
 
SSL_SetDHParamFiles(const char *dh512File,   // IN
3288
 
                    const char *dh1024File)  // IN
3289
 
{
3290
 
   ASSERT(dh512File || dh1024File);
3291
 
 
3292
 
   if (dh512File) {
3293
 
      free(SSLDHParamsFiles[0]);
3294
 
      SSLDHParamsFiles[0] = strdup(dh512File);
3295
 
      ASSERT_MEM_ALLOC(SSLDHParamsFiles[0]);
3296
 
   }
3297
 
   if (dh1024File) {
3298
 
      free(SSLDHParamsFiles[1]);
3299
 
      SSLDHParamsFiles[1] = strdup(dh1024File);
3300
 
      ASSERT_MEM_ALLOC(SSLDHParamsFiles[1]);
3301
 
   }
3302
 
}
3303
 
 
3304
 
 
3305
 
/*
3306
 
 *----------------------------------------------------------------------
3307
 
 *
3308
 
 * SSL_BIO_new_file
3309
 
 *    
3310
 
 *    Wrapper around BIO_new_file that converts "filename" from UTF-8
3311
 
 *    to the local encoding.
3312
 
 *
3313
 
 * Results:
3314
 
 *    New BIO object. Return value is "void *" because we can't
3315
 
 *    include bio.h in ssl.h, or define BIO there, reliably.
3316
 
 *
3317
 
 * Side effects:
3318
 
 *    None.
3319
 
 *
3320
 
 *----------------------------------------------------------------------
3321
 
 */
3322
 
 
3323
 
void *
3324
 
SSL_BIO_new_file(const char *filename, // IN
3325
 
                 const char *mode)     // IN
3326
 
{
3327
 
   BIO *res = NULL;
3328
 
   char *path2 = NULL;
3329
 
 
3330
 
   ASSERT(filename);
3331
 
 
3332
 
   if (!CodeSet_Utf8ToCurrent(filename, strlen(filename), &path2, NULL)) {
3333
 
      goto exit;
3334
 
   }
3335
 
 
3336
 
   res = BIO_new_file(path2, mode);
3337
 
 
3338
 
  exit:
3339
 
   free(path2);
3340
 
   return res;
3341
 
}
3342
 
 
3343
 
 
3344
 
#ifdef __APPLE_READ_BUG_WORKAROUND__
3345
 
/*
3346
 
 *----------------------------------------------------------------------
3347
 
 *
3348
 
 * SSL_SetErrorHook
3349
 
 *
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.
3352
 
 *
3353
 
 *---------------------------------------------------------------------- 
3354
 
 */
3355
 
 
3356
 
void
3357
 
SSL_SetErrorHook(SSLSock ssl,                         // IN
3358
 
                 SSLLibHandleErrorHookFn *hookProc,   // IN
3359
 
                 void *context)                       // IN
3360
 
{
3361
 
   ASSERT(ssl);
3362
 
   ASSERT_DEVEL(ssl->errorHook == NULL);
3363
 
 
3364
 
   ssl->errorHook = hookProc;
3365
 
   ssl->errorHookContext = context;
3366
 
}
3367
 
#endif // __APPLE_READ_BUG_WORKAROUND__
3368