summaryrefslogtreecommitdiff
path: root/vio/viossl.c
blob: e0708ca0a12c14e67dfc34055eebb2db72bfb714 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */

/*
  Note that we can't have assertion on file descriptors;  The reason for
  this is that during mysql shutdown, another thread can close a file
  we are working on.  In this case we should just return read errors from
  the file descriptior.
*/

#include "vio_priv.h"
#include "my_context.h"
#include <mysql_async.h>

#ifdef HAVE_OPENSSL

#ifdef HAVE_YASSL
/*
  yassl seem to be different here, SSL_get_error() value can be
  directly passed to ERR_error_string(), and these errors don't go
  into ERR_get_error() stack.
  in openssl, apparently, SSL_get_error() values live in a different
  namespace, one needs to use ERR_get_error() as an argument
  for ERR_error_string().
*/
#define SSL_errno(X,Y) SSL_get_error(X,Y)
#else
#define SSL_errno(X,Y) ERR_get_error()
#endif

/**
  Obtain the equivalent system error status for the last SSL I/O operation.

  @param ssl_error  The result code of the failed TLS/SSL I/O operation.
*/

static void ssl_set_sys_error(int ssl_error)
{
  int error= 0;

  switch (ssl_error)
  {
  case SSL_ERROR_ZERO_RETURN:
    error= SOCKET_ECONNRESET;
    break;
  case SSL_ERROR_WANT_READ:
  case SSL_ERROR_WANT_WRITE:
#ifdef SSL_ERROR_WANT_CONNECT
  case SSL_ERROR_WANT_CONNECT:
#endif
#ifdef SSL_ERROR_WANT_ACCEPT
  case SSL_ERROR_WANT_ACCEPT:
#endif
    error= SOCKET_EWOULDBLOCK;
    break;
  case SSL_ERROR_SSL:
    /* Protocol error. */
#ifdef EPROTO
    error= EPROTO;
#else
    error= SOCKET_ECONNRESET;
#endif
    break;
  case SSL_ERROR_SYSCALL:
  case SSL_ERROR_NONE:
  default:
    break;
  };

  /* Set error status to a equivalent of the SSL error. */
  if (error)
  {
#ifdef _WIN32
    WSASetLastError(error);
#else
    errno= error;
#endif
  }
}


/**
  Indicate whether a SSL I/O operation must be retried later.

  @param vio  VIO object representing a SSL connection.
  @param ret  Value returned by a SSL I/O function.
  @param event[out] The type of I/O event to wait/retry.

  @return Whether a SSL I/O operation should be deferred.
  @retval TRUE    Temporary failure, retry operation.
  @retval FALSE   Indeterminate failure.
*/

static my_bool ssl_should_retry(Vio *vio, int ret, enum enum_vio_io_event *event)
{
  int ssl_error;
  SSL *ssl= vio->ssl_arg;
  my_bool should_retry= TRUE;

  /* Retrieve the result for the SSL I/O operation. */
  ssl_error= SSL_get_error(ssl, ret);

  /* Retrieve the result for the SSL I/O operation. */
  switch (ssl_error)
  {
  case SSL_ERROR_WANT_READ:
    *event= VIO_IO_EVENT_READ;
    break;
  case SSL_ERROR_WANT_WRITE:
    *event= VIO_IO_EVENT_WRITE;
    break;
  default:
    should_retry= FALSE;
    ssl_set_sys_error(ssl_error);
#ifndef HAVE_YASSL
    ERR_clear_error();
#endif
    break;
  }

  return should_retry;
}


size_t vio_ssl_read(Vio *vio, uchar *buf, size_t size)
{
  int ret;
  SSL *ssl= vio->ssl_arg;
  DBUG_ENTER("vio_ssl_read");
  DBUG_PRINT("enter", ("sd: %d  buf: %p  size: %zu  ssl: %p",
		       (int)mysql_socket_getfd(vio->mysql_socket), buf, size,
                       vio->ssl_arg));

  if (vio->async_context && vio->async_context->active)
    ret= my_ssl_read_async(vio->async_context, (SSL *)vio->ssl_arg, buf, (int)size);
  else
  {
    while ((ret= SSL_read(ssl, buf, (int)size)) < 0)
    {
      enum enum_vio_io_event event;
      
      /* Process the SSL I/O error. */
      if (!ssl_should_retry(vio, ret, &event))
        break;
      /* Attempt to wait for an I/O event. */
      if (vio_socket_io_wait(vio, event))
        break;
    }
  }

  DBUG_PRINT("exit", ("%d", (int) ret));
  DBUG_RETURN(ret < 0 ? -1 : ret);

}


size_t vio_ssl_write(Vio *vio, const uchar *buf, size_t size)
{
  int ret;
  SSL *ssl= vio->ssl_arg;
  DBUG_ENTER("vio_ssl_write");
  DBUG_PRINT("enter", ("sd: %d  buf: %p  size: %zu",
                       (int)mysql_socket_getfd(vio->mysql_socket),
                       buf, size));

  if (vio->async_context && vio->async_context->active)
    ret= my_ssl_write_async(vio->async_context, (SSL *)vio->ssl_arg, buf,
                            (int)size);
  else
  {
    while ((ret= SSL_write(ssl, buf, (int)size)) < 0)
    {
      enum enum_vio_io_event event;

      /* Process the SSL I/O error. */
      if (!ssl_should_retry(vio, ret, &event))
        break;

      /* Attempt to wait for an I/O event. */
      if (vio_socket_io_wait(vio, event))
        break;
    }
  }

  DBUG_RETURN(ret < 0 ? -1 : ret);
}

#ifdef HAVE_YASSL

/* Emulate a blocking recv() call with vio_read(). */
static long yassl_recv(void *ptr, void *buf, size_t len,
                       int flag __attribute__((unused)))
{
  return (long)vio_read(ptr, buf, len);
}


/* Emulate a blocking send() call with vio_write(). */
static long yassl_send(void *ptr, const void *buf, size_t len,
                       int flag __attribute__((unused)))
{
  return (long)vio_write(ptr, buf, len);
}

#endif

int vio_ssl_close(Vio *vio)
{
  int r= 0;
  SSL *ssl= (SSL*)vio->ssl_arg;
  DBUG_ENTER("vio_ssl_close");

  if (ssl)
  {
    /*
    THE SSL standard says that SSL sockets must send and receive a close_notify
    alert on socket shutdown to avoid truncation attacks. However, this can
    cause problems since we often hold a lock during shutdown and this IO can
    take an unbounded amount of time to complete. Since our packets are self
    describing with length, we aren't vunerable to these attacks. Therefore,
    we just shutdown by closing the socket (quiet shutdown).
    */
    SSL_set_quiet_shutdown(ssl, 1); 
    
    switch ((r= SSL_shutdown(ssl))) {
    case 1:
      /* Shutdown successful */
      break;
    case 0:
      /*
        Shutdown not yet finished - since the socket is going to
        be closed there is no need to call SSL_shutdown() a second
        time to wait for the other side to respond
      */
      break;
    default: /* Shutdown failed */
      DBUG_PRINT("vio_error", ("SSL_shutdown() failed, error: %d",
                               SSL_get_error(ssl, r)));
      break;
    }
  }
  DBUG_RETURN(vio_close(vio));
}


void vio_ssl_delete(Vio *vio)
{
  if (!vio)
    return; /* It must be safe to delete null pointer */

  if (vio->type == VIO_TYPE_SSL)
    vio_ssl_close(vio); /* Still open, close connection first */

  if (vio->ssl_arg)
  {
    SSL_free((SSL*) vio->ssl_arg);
    vio->ssl_arg= 0;
  }

  vio_delete(vio);
}


/** SSL handshake handler. */
typedef int (*ssl_handshake_func_t)(SSL*);


/**
  Loop and wait until a SSL handshake is completed.

  @param vio    VIO object representing a SSL connection.
  @param ssl    SSL structure for the connection.
  @param func   SSL handshake handler.

  @return Return value is 1 on success.
*/

static int ssl_handshake_loop(Vio *vio, SSL *ssl, ssl_handshake_func_t func)
{
  int ret;

  vio->ssl_arg= ssl;

  /* Initiate the SSL handshake. */
  while ((ret= func(ssl)) < 1)
  {
    enum enum_vio_io_event event;

    /* Process the SSL I/O error. */
    if (!ssl_should_retry(vio, ret, &event))
      break;

    /* Wait for I/O so that the handshake can proceed. */
    if (vio_socket_io_wait(vio, event))
      break;
  }

  vio->ssl_arg= NULL;

  return ret;
}


static int ssl_do(struct st_VioSSLFd *ptr, Vio *vio, long timeout,
                  ssl_handshake_func_t func, unsigned long *errptr)
{
  int r;
  SSL *ssl;
  my_socket sd= mysql_socket_getfd(vio->mysql_socket);
  DBUG_ENTER("ssl_do");
  DBUG_PRINT("enter", ("ptr: %p, sd: %d  ctx: %p",
                       ptr, (int)sd, ptr->ssl_context));


  if (!(ssl= SSL_new(ptr->ssl_context)))
  {
    DBUG_PRINT("error", ("SSL_new failure"));
    *errptr= ERR_get_error();
    DBUG_RETURN(1);
  }
  DBUG_PRINT("info", ("ssl: %p timeout: %ld", ssl, timeout));
  SSL_clear(ssl);
  SSL_SESSION_set_timeout(SSL_get_session(ssl), timeout);
  SSL_set_fd(ssl, (int)sd);

  /*
    Since yaSSL does not support non-blocking send operations, use
    special transport functions that properly handles non-blocking
    sockets. These functions emulate the behavior of blocking I/O
    operations by waiting for I/O to become available.
  */
#ifdef HAVE_YASSL
  /* Set first argument of the transport functions. */
  yaSSL_transport_set_ptr(ssl, vio);
  /* Set functions to use in order to send and receive data. */
  yaSSL_transport_set_recv_function(ssl, yassl_recv);
  yaSSL_transport_set_send_function(ssl, yassl_send);
#endif

#if !defined(HAVE_YASSL) && defined(SSL_OP_NO_COMPRESSION)
  SSL_set_options(ssl, SSL_OP_NO_COMPRESSION);
#endif

  if ((r= ssl_handshake_loop(vio, ssl, func)) < 1)
  {
    DBUG_PRINT("error", ("SSL_connect/accept failure"));
    *errptr= SSL_errno(ssl, r);
    SSL_free(ssl);
    DBUG_RETURN(1);
  }

  /*
    Connection succeeded. Install new function handlers,
    change type, set sd to the fd used when connecting
    and set pointer to the SSL structure
  */
  if (vio_reset(vio, VIO_TYPE_SSL, SSL_get_fd(ssl), ssl, 0))
  {
    DBUG_RETURN(1);
  }

#ifndef DBUG_OFF
  {
    /* Print some info about the peer */
    X509 *cert;
    char buf[512];

    DBUG_PRINT("info",("SSL connection succeeded"));
    DBUG_PRINT("info",("Using cipher: '%s'" , SSL_get_cipher_name(ssl)));

    if ((cert= SSL_get_peer_certificate (ssl)))
    {
      DBUG_PRINT("info",("Peer certificate:"));
      X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
      DBUG_PRINT("info",("\t subject: '%s'", buf));
      X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
      DBUG_PRINT("info",("\t issuer: '%s'", buf));
      X509_free(cert);
    }
    else
      DBUG_PRINT("info",("Peer does not have certificate."));

    if (SSL_get_shared_ciphers(ssl, buf, sizeof(buf)))
    {
      DBUG_PRINT("info",("shared_ciphers: '%s'", buf));
    }
    else
      DBUG_PRINT("info",("no shared ciphers!"));
  }
#endif

  DBUG_RETURN(0);
}


int sslaccept(struct st_VioSSLFd *ptr, Vio *vio, long timeout, unsigned long *errptr)
{
  DBUG_ENTER("sslaccept");
  DBUG_RETURN(ssl_do(ptr, vio, timeout, SSL_accept, errptr));
}


int sslconnect(struct st_VioSSLFd *ptr, Vio *vio, long timeout, unsigned long *errptr)
{
  DBUG_ENTER("sslconnect");
  DBUG_RETURN(ssl_do(ptr, vio, timeout, SSL_connect, errptr));
}


int vio_ssl_blocking(Vio *vio __attribute__((unused)),
		     my_bool set_blocking_mode,
		     my_bool *old_mode)
{
  /* Mode is always blocking */
  *old_mode= 1;
  /* Return error if we try to change to non_blocking mode */
  return (set_blocking_mode ? 0 : 1);
}

my_bool vio_ssl_has_data(Vio *vio)
{
  return SSL_pending(vio->ssl_arg) > 0 ? TRUE : FALSE;
}

#endif /* HAVE_OPENSSL */