src/ssl.c

1
/*--------------------------------------------------------------------------
2
 * LuaSec 0.4
3
 * Copyright (C) 2006-2009 Bruno Silvestre
4
 *
5
 *--------------------------------------------------------------------------*/
6
 
7
#include <string.h>
8
 
9
#include <openssl/ssl.h>
10
#include <openssl/x509v3.h>
11
#include <openssl/err.h>
12
 
13
#include <lua.h>
14
#include <lauxlib.h>
15
 
16
#include "io.h"
17
#include "buffer.h"
18
#include "timeout.h"
19
#include "socket.h"
20
#include "ssl.h"
21
#include "x509.h"
22
 
23
/* index into the SSL storage where the t_ssl is.
24
 * see SSL_get_ex_data().
25
 */
26
 int luasec_ssl_idx;
27
 
28
/**
29
 * Map error code into string.
30
 */
31
static const char *ssl_ioerror(void *ctx, int err)
32
{
33
  if (err == IO_SSL) {
34
    p_ssl ssl = (p_ssl) ctx;
35
    switch(ssl->error) {
36
    case SSL_ERROR_NONE: return "No error";
37
    case SSL_ERROR_ZERO_RETURN: return "closed";
38
    case SSL_ERROR_WANT_READ: return "wantread";
39
    case SSL_ERROR_WANT_WRITE: return "wantwrite";
40
    case SSL_ERROR_WANT_CONNECT: return "'connect' not completed";
41
    case SSL_ERROR_WANT_ACCEPT: return "'accept' not completed";
42
    case SSL_ERROR_WANT_X509_LOOKUP: return "Waiting for callback";
43
    case SSL_ERROR_SYSCALL: return "System error";
44
    case SSL_ERROR_SSL: return ERR_reason_error_string(ERR_get_error());
45
    default: return "Unknown SSL error";
46
    }
47
  }
48
  return socket_strerror(err);
49
}
50
 
51
/**
52
 * Close the connection before the GC collect the object.
53
 */
54
static int meth_destroy(lua_State *L)
55
{
56
  p_ssl ssl = (p_ssl) lua_touserdata(L, 1);
57
  if (ssl->ssl) {
58
    socket_setblocking(&ssl->sock);
59
    SSL_shutdown(ssl->ssl);
60
    socket_destroy(&ssl->sock);
61
    SSL_free(ssl->ssl);
62
    ssl->ssl = NULL;
63
  }
64
  luaL_unref(L, LUA_REGISTRYINDEX, ssl->t_cert_errors);
65
  ssl->t_cert_errors = LUA_NOREF;
66
  return 0;
67
}
68
 
69
/**
70
 * Object information -- tostring metamethod
71
 */
72
static int meth_tostring(lua_State *L)
73
{
74
  p_ssl ssl = (p_ssl)lua_touserdata(L, 1);
75
  lua_pushfstring(L, "SSL connection: %p", ssl);
76
  return 1;
77
}
78
 
79
/**
80
 * Perform the TLS/SSL handshake
81
 */
82
static int handshake(p_ssl ssl)
83
{
84
  int err;
85
  p_timeout tm = timeout_markstart(&ssl->tm);
86
  if (ssl->state == ST_SSL_CLOSED)
87
    return IO_CLOSED;
88
  for ( ; ; ) {
89
    ERR_clear_error();
90
    err = SSL_do_handshake(ssl->ssl);
91
    ssl->error = SSL_get_error(ssl->ssl, err);
92
    switch(ssl->error) {
93
    case SSL_ERROR_NONE:
94
      ssl->state = ST_SSL_CONNECTED;
95
      return IO_DONE;
96
    case SSL_ERROR_WANT_READ:
97
      err = socket_waitfd(&ssl->sock, WAITFD_R, tm);
98
      if (err == IO_TIMEOUT) return IO_SSL;
99
      if (err != IO_DONE)    return err;
100
      break;
101
    case SSL_ERROR_WANT_WRITE:
102
      err = socket_waitfd(&ssl->sock, WAITFD_W, tm);
103
      if (err == IO_TIMEOUT) return IO_SSL;
104
      if (err != IO_DONE)    return err;
105
      break;
106
    case SSL_ERROR_SYSCALL:
107
      if (ERR_peek_error())  {
108
        ssl->error = SSL_ERROR_SSL;
109
        return IO_SSL;
110
      }
111
      if (err == 0)
112
        return IO_CLOSED;
113
      return socket_error();
114
    default:
115
      return IO_SSL;
116
    }
117
  }
118
  return IO_UNKNOWN;
119
}
120
 
121
/**
122
 * Send data
123
 */
124
static int ssl_send(void *ctx, const char *data, size_t count, size_t *sent,
125
   p_timeout tm)
126
{
127
  int err;
128
  p_ssl ssl = (p_ssl) ctx;
129
  if (ssl->state == ST_SSL_CLOSED)
130
    return IO_CLOSED;
131
  *sent = 0;
132
  for ( ; ; ) {
133
    ERR_clear_error();
134
    err = SSL_write(ssl->ssl, data, (int) count);
135
    ssl->error = SSL_get_error(ssl->ssl, err);
136
    switch(ssl->error) {
137
    case SSL_ERROR_NONE:
138
      *sent = err;
139
      return IO_DONE;
140
    case SSL_ERROR_WANT_READ: 
141
      err = socket_waitfd(&ssl->sock, WAITFD_R, tm);
142
      if (err == IO_TIMEOUT) return IO_SSL;
143
      if (err != IO_DONE)    return err;
144
      break;
145
    case SSL_ERROR_WANT_WRITE:
146
      err = socket_waitfd(&ssl->sock, WAITFD_W, tm);
147
      if (err == IO_TIMEOUT) return IO_SSL;
148
      if (err != IO_DONE)    return err;
149
      break;
150
    case SSL_ERROR_SYSCALL:
151
      if (ERR_peek_error())  {
152
        ssl->error = SSL_ERROR_SSL;
153
        return IO_SSL;
154
      }
155
      if (err == 0)
156
        return IO_CLOSED;
157
      return socket_error();
158
    default:
159
      return IO_SSL;
160
    }
161
  }
162
  return IO_UNKNOWN;
163
}
164
 
165
/**
166
 * Receive data
167
 */
168
static int ssl_recv(void *ctx, char *data, size_t count, size_t *got,
169
  p_timeout tm)
170
{
171
  int err;
172
  p_ssl ssl = (p_ssl) ctx;
173
  if (ssl->state == ST_SSL_CLOSED)
174
    return IO_CLOSED;
175
  *got = 0;
176
  for ( ; ; ) {
177
    ERR_clear_error();
178
    err = SSL_read(ssl->ssl, data, (int) count);
179
    ssl->error = SSL_get_error(ssl->ssl, err);
180
    switch(ssl->error) {
181
    case SSL_ERROR_NONE:
182
      *got = err;
183
      return IO_DONE;
184
    case SSL_ERROR_ZERO_RETURN:
185
      *got = err;
186
      return IO_CLOSED;
187
    case SSL_ERROR_WANT_READ:
188
      err = socket_waitfd(&ssl->sock, WAITFD_R, tm);
189
      if (err == IO_TIMEOUT) return IO_SSL;
190
      if (err != IO_DONE)    return err;
191
      break;
192
    case SSL_ERROR_WANT_WRITE:
193
      err = socket_waitfd(&ssl->sock, WAITFD_W, tm);
194
      if (err == IO_TIMEOUT) return IO_SSL;
195
      if (err != IO_DONE)    return err;
196
      break;
197
    case SSL_ERROR_SYSCALL:
198
      if (ERR_peek_error())  {
199
        ssl->error = SSL_ERROR_SSL;
200
        return IO_SSL;
201
      }
202
      if (err == 0)
203
        return IO_CLOSED;
204
      return socket_error();
205
    default:
206
      return IO_SSL;
207
    }
208
  }
209
  return IO_UNKNOWN;
210
}
211
 
212
/**
213
 * Create a new TLS/SSL object and mark it as new.
214
 */
215
static int meth_create(lua_State *L)
216
{
217
  p_ssl ssl;
218
  int mode = ctx_getmode(L, 1);
219
  p_context ctx = checkctx(L, 1);
220
 
221
  if (mode == MD_CTX_INVALID) {
222
    lua_pushnil(L);
223
    lua_pushstring(L, "invalid mode");
224
    return 2;
225
  }
226
  if (luasec_ssl_idx == -1) {
227
    luasec_ssl_idx = SSL_get_ex_new_index(0, "luasec ssl context", NULL, NULL, NULL);
228
    if (luasec_ssl_idx == -1) {
229
      lua_pushnil(L);
230
      lua_pushstring(L, "error creating luasec SSL index");
231
      return 2;
232
    }
233
  }
234
  ssl = (p_ssl) lua_newuserdata(L, sizeof(t_ssl));
235
  if (!ssl) {
236
    lua_pushnil(L);
237
    lua_pushstring(L, "error creating SSL object");
238
    return 2;
239
  }
240
  ssl->ssl = SSL_new(ctx->context);
241
  if (!ssl->ssl) {
242
    lua_pushnil(L);
243
    lua_pushstring(L, "error creating SSL object");
244
    return 2;;
245
  }
246
  ssl->state = ST_SSL_NEW;
247
  SSL_set_fd(ssl->ssl, (int) SOCKET_INVALID);
248
  SSL_set_mode(ssl->ssl,   SSL_MODE_ENABLE_PARTIAL_WRITE |
249
    SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
250
 
251
#ifdef SSL_MODE_RELEASE_BUFFERS
252
  SSL_set_mode(ssl->ssl, SSL_MODE_RELEASE_BUFFERS);
253
#endif
254
 
255
  SSL_set_ex_data(ssl->ssl, luasec_ssl_idx, ssl);
256
  ssl->t_cert_errors = LUA_NOREF;
257
 
258
  if (mode == MD_CTX_SERVER)
259
    SSL_set_accept_state(ssl->ssl);
260
  else
261
    SSL_set_connect_state(ssl->ssl);
262
 
263
  io_init(&ssl->io, (p_send) ssl_send, (p_recv) ssl_recv, 
264
    (p_error) ssl_ioerror, ssl);
265
  timeout_init(&ssl->tm, -1, -1);
266
  buffer_init(&ssl->buf, &ssl->io, &ssl->tm);
267
 
268
  luaL_getmetatable(L, "SSL:Connection");
269
  lua_setmetatable(L, -2);
270
  return 1;
271
}
272
 
273
/**
274
 * Buffer send function
275
 */
276
static int meth_send(lua_State *L) {
277
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
278
  return buffer_meth_send(L, &ssl->buf);
279
}
280
 
281
/**
282
 * Buffer receive function
283
 */
284
static int meth_receive(lua_State *L) {
285
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
286
  return buffer_meth_receive(L, &ssl->buf);
287
}
288
 
289
/**
290
 * Select support methods
291
 */
292
static int meth_getfd(lua_State *L)
293
{
294
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
295
  lua_pushnumber(L, ssl->sock);
296
  return 1;
297
}
298
 
299
/**
300
 * Set the TLS/SSL file descriptor.
301
 * This is done *before* the handshake.
302
 */
303
static int meth_setfd(lua_State *L)
304
{
305
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
306
  if (ssl->state != ST_SSL_NEW)
307
    luaL_argerror(L, 1, "invalid SSL object state");
308
  ssl->sock = luaL_checkint(L, 2);
309
  socket_setnonblocking(&ssl->sock);
310
  SSL_set_fd(ssl->ssl, (int)ssl->sock);
311
  return 0;
312
}
313
 
314
/**
315
 * Lua handshake function.
316
 */
317
static int meth_handshake(lua_State *L)
318
{
319
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
320
  int err = handshake(ssl);
321
  if (err == IO_DONE) {
322
    lua_pushboolean(L, 1);
323
    return 1;
324
  }
325
  lua_pushboolean(L, 0);
326
  lua_pushstring(L, ssl_ioerror((void*)ssl, err));
327
  return 2;
328
}
329
 
330
/**
331
 * Close the connection.
332
 */
333
static int meth_close(lua_State *L)
334
{
335
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
336
  meth_destroy(L);
337
  ssl->state = ST_SSL_CLOSED;
338
  return 0;
339
}
340
 
341
/**
342
 * Set timeout.
343
 */
344
static int meth_settimeout(lua_State *L)
345
{
346
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
347
  return timeout_meth_settimeout(L, &ssl->tm);
348
}
349
 
350
/**
351
 * Check if there is data in the buffer.
352
 */
353
static int meth_dirty(lua_State *L)
354
{
355
  int res = 0;
356
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
357
  if (ssl->state != ST_SSL_CLOSED)
358
    res = !buffer_isempty(&ssl->buf) || SSL_pending(ssl->ssl);
359
  lua_pushboolean(L, res);
360
  return 1;
361
}
362
 
363
/**
364
 * Return the state information about the SSL object.
365
 */
366
static int meth_want(lua_State *L)
367
{
368
  p_ssl ssl = (p_ssl) luaL_checkudata(L, 1, "SSL:Connection");
369
  int code = (ssl->state == ST_SSL_CLOSED) ? SSL_NOTHING : SSL_want(ssl->ssl);
370
  switch(code) {
371
  case SSL_NOTHING: lua_pushstring(L, "nothing"); break;
372
  case SSL_READING: lua_pushstring(L, "read"); break;
373
  case SSL_WRITING: lua_pushstring(L, "write"); break;
374
  case SSL_X509_LOOKUP: lua_pushstring(L, "x509lookup"); break;
375
  }
376
  return 1;
377
}
378
  
379
/**
380
 * Return a pointer to SSL structure.
381
 */
382
static int meth_rawconn(lua_State *L)
383
{
384
  p_ssl ssl = (p_ssl)luaL_checkudata(L, 1, "SSL:Connection");
385
  lua_pushlightuserdata(L, (void*)ssl->ssl);
386
  return 1;
387
}
388
 
389
/**
390
 * Return the compression method used.
391
 */
392
static int meth_compression(lua_State *L)
393
{
394
  const COMP_METHOD *comp;
395
  p_ssl ssl = (p_ssl)luaL_checkudata(L, 1, "SSL:Connection");
396
  comp = SSL_get_current_compression(ssl->ssl);
397
  if (comp) {
398
    lua_pushstring(L, SSL_COMP_get_name(comp));
399
    return 1;
400
  } else {
401
    lua_pushboolean(L, 0);
402
    return 1;
403
  }
404
}
405
 
406
/**
407
 * Return the validation state of the peer chain
408
 */
409
static int meth_getpeerverification(lua_State *L)
410
{
411
  p_ssl ssl = (p_ssl)luaL_checkudata(L, 1, "SSL:Connection");
412
 
413
  lua_pushboolean(L, SSL_get_verify_result(ssl->ssl) == X509_V_OK);
414
  lua_rawgeti(L, LUA_REGISTRYINDEX, ssl->t_cert_errors);
415
  return 2;
416
}
417
 
418
static void luasec_push_cert(lua_State *L, X509 *cert)
419
{
420
  if (cert == NULL) {
421
    lua_pushnil(L);
422
  }
423
  else
424
  {
425
    luasec_push_x509(L, cert);
426
  }
427
}
428
 
429
/**
430
 * Return the nth certificate of the peer's chain.
431
 */
432
static int meth_getpeercertificate(lua_State *L)
433
{
434
  p_ssl ssl = (p_ssl)luaL_checkudata(L, 1, "SSL:Connection");
435
  int n = luaL_optint(L, 2, 1); /* Default to the first cert */
436
  STACK_OF(X509) *certs;
437
  X509 *cert;
438
 
439
  /* This function is 1-based, but OpenSSL is 0-based */
440
  --n;
441
  if (n < 0) {
442
    lua_pushnil(L);
443
    lua_pushliteral(L, "n must be positive");
444
    return 2;
445
  }
446
 
447
  if (n == 0) {
448
    luasec_push_cert(L, SSL_get_peer_certificate(ssl->ssl));
449
    return 1;
450
  }
451
 
452
  /*
453
   * In a server-context, the stack doesn't contain the peer cert, so
454
   * adjust accordingly.
455
   */
456
  if (ssl->ssl->server)
457
    --n;
458
 
459
  certs = SSL_get_peer_cert_chain(ssl->ssl);
460
  if (n >= sk_X509_num(certs)) {
461
    lua_pushnil(L);
462
    lua_pushliteral(L, "no certificate at this index");
463
    return 2;
464
  }
465
  cert = sk_X509_value(certs, n);
466
  /* Locking...the same as in SSL_get_peer_certificate */
467
  CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
468
  luasec_push_cert(L, cert);
469
  return 1;
470
}
471
 
472
static int meth_getpeerchain(lua_State *L)
473
{
474
  p_ssl ssl = (p_ssl)luaL_checkudata(L, 1, "SSL:Connection");
475
  STACK_OF(X509) *certs;
476
  int n_certs, i;
477
 
478
  lua_newtable(L);
479
 
480
  if (ssl->ssl->server) {
481
    luasec_push_cert(L, SSL_get_peer_certificate(ssl->ssl));
482
    lua_rawseti(L, -2, 1);
483
  }
484
 
485
  certs = SSL_get_peer_cert_chain(ssl->ssl);
486
  n_certs = sk_X509_num(certs);
487
  for (i = 0; i < n_certs; ++i) {
488
    X509 *cert = sk_X509_value(certs, i);
489
    /* Locking...the same as in SSL_get_peer_certificate */
490
    CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
491
    luasec_push_cert(L, cert);
492
    lua_rawseti(L, -2, lua_objlen(L, -2)+1);
493
  }
494
 
495
  return 1;
496
}
497
 
498
static int meth_getfinished(lua_State *L)
499
{
500
  p_ssl ssl = (p_ssl)luaL_checkudata(L, 1, "SSL:Connection");
501
  SSL *conn = ssl->ssl;
502
  char *buffer = NULL;
503
  size_t len = 0;
504
  if ((len = SSL_get_finished(conn, NULL, 0)) != 0) {
505
    buffer = malloc(len);
506
    if (buffer == NULL) return 0;
507
    len = SSL_get_finished(conn, buffer, len);
508
    lua_pushlstring(L, buffer, len);
509
    free(buffer);
510
    return 1;
511
  } else {
512
    return 0;
513
  }
514
}
515
 
516
static int meth_getpeerfinished(lua_State *L)
517
{
518
  p_ssl ssl = (p_ssl)luaL_checkudata(L, 1, "SSL:Connection");
519
  SSL *conn = ssl->ssl;
520
  char *buffer = NULL;
521
  size_t len = 0;
522
  if ((len = SSL_get_peer_finished(conn, NULL, 0)) != 0) {
523
    buffer = malloc(len);
524
    if (buffer == NULL) return 0;
525
    len = SSL_get_peer_finished(conn, buffer, len);
526
    lua_pushlstring(L, buffer, len);
527
    free(buffer);
528
    return 1;
529
  } else {
530
    return 0;
531
  }
532
}
533
 
534
/*---------------------------------------------------------------------------*/
535
 
536
 
537
/**
538
 * SSL metamethods 
539
 */
540
static luaL_Reg methods[] = {
541
  {"close",             meth_close},
542
  {"getfd",             meth_getfd},
543
  {"dirty",             meth_dirty},
544
  {"dohandshake",       meth_handshake},
545
  {"receive",           meth_receive},
546
  {"send",              meth_send},
547
  {"settimeout",        meth_settimeout},
548
  {"want",              meth_want},
549
  {"compression",       meth_compression},
550
  {"getpeercertificate",meth_getpeercertificate},
551
  {"getpeerchain",      meth_getpeerchain},
552
  {"getpeerverification", meth_getpeerverification},
553
  {"getfinished",       meth_getfinished},
554
  {"getpeerfinished",   meth_getpeerfinished},
555
  {NULL,                NULL}
556
};
557
 
558
/**
559
 * SSL functions 
560
 */
561
static luaL_Reg funcs[] = {
562
  {"create",        meth_create},
563
  {"setfd",         meth_setfd},
564
  {"rawconnection", meth_rawconn},
565
  {NULL,            NULL}
566
};
567
 
568
/**
569
 * Context metamethods.
570
 */
571
static luaL_Reg meta[] = {
572
  {"__gc",       meth_destroy},
573
  {"__tostring", meth_tostring},
574
  {NULL, NULL}
575
};
576
 
577
/**
578
 * Initialize modules
579
 */
580
LUASEC_API int luaopen_ssl_core(lua_State *L)
581
{
582
  /* Initialize SSL */
583
  if (!SSL_library_init()) {
584
    lua_pushstring(L, "unable to initialize SSL library");
585
    lua_error(L);
586
  }
587
  SSL_load_error_strings();
588
 
589
  /* Initialize internal library */
590
  socket_open();
591
 
592
  /* Register the functions and tables */
593
  luaL_newmetatable(L, "SSL:Connection");
594
  luaL_register(L, NULL, meta);
595
 
596
  lua_newtable(L);
597
  luaL_register(L, NULL, methods);
598
  lua_setfield(L, -2, "__index");
599
 
600
  luaL_register(L, "ssl.core", funcs);
601
  lua_pushnumber(L, SOCKET_INVALID);
602
  lua_setfield(L, -2, "invalidfd");
603
 
604
  return 1;
605
}