root/src/eventer/eventer_SSL_fd_opset.c

Revision fb5f8f9daa6e4df8e9acc3c11501205c21866b72, 13.2 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 6 years ago)

fix up SSL layer to handle termination and make the jlog rcpt side completely reset on error, refs #41

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  */
5
6 #include "noit_defines.h"
7 #include "eventer/eventer.h"
8 #include "utils/noit_log.h"
9 #include "eventer/eventer_SSL_fd_opset.h"
10
11 #include <sys/socket.h>
12 #include <unistd.h>
13
14 #include <openssl/ssl.h>
15 #include <openssl/err.h>
16 #include <openssl/engine.h>
17
18 #define EVENTER_SSL_DATANAME "eventer_ssl"
19
20 struct eventer_ssl_ctx_t {
21   SSL_CTX *ssl_ctx;
22   SSL     *ssl;
23   char    *issuer;
24   char    *subject;
25   eventer_ssl_verify_func_t verify_cb;
26   void    *verify_cb_closure;
27 };
28
29 /* Static function prototypes */
30 static void SSL_set_eventer_ssl_ctx(SSL *ssl, eventer_ssl_ctx_t *ctx);
31 static eventer_ssl_ctx_t *SSL_get_eventer_ssl_ctx(SSL *ssl);
32 static void _eventer_ssl_error();
33 static RSA *tmp_rsa_cb(SSL *ssl, int export, int keylen);
34
35 #define eventer_ssl_error() _eventer_ssl_error(__FILE__,__LINE__)
36
37 static void
38 _eventer_ssl_error(const char *f, int l) {
39   unsigned long err;
40   char buf[120]; /* ERR_error_string(3): buf must be at least 120 bytes */
41   while((err = ERR_get_error()) != 0) {
42     ERR_error_string(err, buf);
43     noitL(noit_error, "%s:%d: write error[%08lx] %s\n", f, l, err, buf);
44   }
45 }
46
47 /*
48  * Cribbed from SSL examples.
49  */
50 static char *tmpkeyfile = NULL;
51 static time_t tmpkeyfile_time = 0;
52 static RSA *
53 tmp_rsa_cb(SSL *ssl, int export, int keylen) {
54   RSA *tmpkey;
55   if (!export) keylen = 512;
56   if (tmpkeyfile && keylen == 512) {
57     BIO *in = BIO_new_file(tmpkeyfile, "r");
58     if (in) {
59       RSA *rsa = PEM_read_bio_RSAPrivateKey(in,NULL,NULL,NULL);
60       BIO_free(in);
61       if (rsa) return rsa;
62     }
63   }
64   tmpkey = RSA_generate_key(keylen,RSA_F4,NULL,NULL);
65   if(tmpkeyfile && keylen == 512) {
66     BIO *out = BIO_new_file(tmpkeyfile, "r");
67     if(!out ||
68        !PEM_write_bio_RSAPrivateKey(out, tmpkey, NULL, NULL, 0, 0, NULL)) {
69       noitL(noit_error, "Could not save temporary RSA key to %s\n", tmpkeyfile);
70     } else {
71       tmpkeyfile_time = time(NULL);
72     }
73     if(out) BIO_free(out);
74   }
75   return tmpkey;
76 }
77
78 int
79 eventer_ssl_verify_dates(eventer_ssl_ctx_t *ctx, int ok,
80                          X509_STORE_CTX *x509ctx, void *closure) {
81   time_t now;
82   X509 *peer;
83   if(!x509ctx) return -1;
84   peer = X509_STORE_CTX_get_current_cert(x509ctx);
85   time(&now);
86   if(X509_cmp_time(X509_get_notBefore(peer), &now) > 0) return -1;
87   if(X509_cmp_time(X509_get_notAfter(peer), &now) < 0) return 1;
88   return 0;
89 }
90
91 int
92 eventer_ssl_verify_cert(eventer_ssl_ctx_t *ctx, int ok,
93                         X509_STORE_CTX *x509ctx, void *closure) {
94   SSL *ssl;
95   noit_hash_table *options = closure;
96   const char *opt_no_ca, *ignore_dates;
97   int v_res;
98
99   if(!x509ctx) return 0;
100
101   if(!noit_hash_retrieve(options, "optional_no_ca", strlen("optional_no_ca"),
102                          (void **)&opt_no_ca))
103     opt_no_ca = "false";
104   if(!noit_hash_retrieve(options, "ignore_dates", strlen("ignore_dates"),
105                          (void **)&ignore_dates))
106     ignore_dates = "false";
107
108   ssl = X509_STORE_CTX_get_ex_data(x509ctx,
109                                    SSL_get_ex_data_X509_STORE_CTX_idx());
110   v_res = X509_STORE_CTX_get_error(x509ctx);
111
112   if((v_res == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) ||
113      (v_res == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) ||
114      (v_res == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) ||
115      (v_res == X509_V_ERR_CERT_UNTRUSTED) ||
116      (v_res == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE)) {
117     if(!strcmp(opt_no_ca, "true")) ok = 1;
118     else {
119       noitL(noit_error, "SSL client cert invalid: %s\n",
120             X509_verify_cert_error_string(v_res));
121       ok = 0;
122       goto set_out;
123     }
124   }
125   v_res = eventer_ssl_verify_dates(ctx, ok, x509ctx, closure);
126   if(v_res != 0) {
127     if(!strcmp(ignore_dates, "true")) ok = 1;
128     else {
129       noitL(noit_error, "SSL client cert is %s valid.\n",
130             (v_res < 0) ? "not yet" : "no longer");
131       ok = 0;
132       goto set_out;
133     }
134   }
135  set_out:
136   return ok;
137 }
138
139 #define GET_SET_X509_NAME(type) \
140 static void \
141 eventer_ssl_set_peer_##type(eventer_ssl_ctx_t *ctx, \
142                              X509_STORE_CTX *x509ctx) { \
143   char buffer[1024]; \
144   X509 *peer; \
145   peer = X509_STORE_CTX_get_current_cert(x509ctx); \
146   X509_NAME_oneline(X509_get_##type##_name(peer), buffer, sizeof(buffer)-1); \
147   if(ctx->type) free(ctx->type); \
148   ctx->type = strdup(buffer); \
149 } \
150 char * \
151 eventer_ssl_get_peer_##type(eventer_ssl_ctx_t *ctx) { \
152   return ctx->type; \
153 }
154
155 GET_SET_X509_NAME(issuer)
156 GET_SET_X509_NAME(subject)
157
158 static int
159 verify_cb(int ok, X509_STORE_CTX *x509ctx) {
160   eventer_ssl_ctx_t *ctx;
161   SSL *ssl;
162
163   ssl = X509_STORE_CTX_get_ex_data(x509ctx,
164                                    SSL_get_ex_data_X509_STORE_CTX_idx());
165   ctx = SSL_get_eventer_ssl_ctx(ssl);
166   eventer_ssl_set_peer_subject(ctx, x509ctx);
167   eventer_ssl_set_peer_issuer(ctx, x509ctx);
168   if(ctx->verify_cb)
169     return ctx->verify_cb(ctx, ok, x509ctx, ctx->verify_cb_closure);
170   return ok;
171 }
172
173 /*
174  * Helpers to create and destroy our context.
175  */
176 void
177 eventer_ssl_ctx_free(eventer_ssl_ctx_t *ctx) {
178   if(ctx->ssl) SSL_free(ctx->ssl);
179   if(ctx->ssl_ctx) SSL_CTX_free(ctx->ssl_ctx);
180   if(ctx->issuer) free(ctx->issuer);
181   if(ctx->subject) free(ctx->subject);
182   free(ctx);
183 }
184
185 eventer_ssl_ctx_t *
186 eventer_ssl_ctx_new(eventer_ssl_orientation_t type,
187                     const char *certificate, const char *key,
188                     const char *ca, const char *ciphers) {
189   eventer_ssl_ctx_t *ctx;
190   ctx = calloc(1, sizeof(*ctx));
191   if(!ctx) return NULL;
192   /*
193    * First step is to setup the SSL context.  This is long-lived in SSL-land
194    * however, that would require us caching it.  Maybe we'll do that?
195    */
196   ctx->ssl_ctx = SSL_CTX_new(type == SSL_SERVER ?
197                              SSLv23_server_method() : SSLv23_client_method());
198   if(!ctx->ssl_ctx) return NULL;
199   if (type == SSL_SERVER)
200     SSL_CTX_set_session_id_context(ctx->ssl_ctx,
201             (unsigned char *)EVENTER_SSL_DATANAME,
202             sizeof(EVENTER_SSL_DATANAME)-1);
203   SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_ALL);
204   if(certificate &&
205      SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, certificate) != 1)
206     goto bail;
207   if(key &&
208      SSL_CTX_use_RSAPrivateKey_file(ctx->ssl_ctx,key,
209                                     SSL_FILETYPE_PEM) != 1)
210     goto bail;
211   if(ca) {
212     STACK_OF(X509_NAME) *cert_stack;
213     if(!SSL_CTX_load_verify_locations(ctx->ssl_ctx,ca,NULL) ||
214        (cert_stack = SSL_load_client_CA_file(ca)) == NULL)
215       goto bail;
216     SSL_CTX_set_client_CA_list(ctx->ssl_ctx, cert_stack);
217   }
218   SSL_CTX_set_tmp_rsa_callback(ctx->ssl_ctx, tmp_rsa_cb);
219   SSL_CTX_set_cipher_list(ctx->ssl_ctx, ciphers ? ciphers : "DEFAULT");
220   SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, verify_cb);
221   SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
222
223   ctx->ssl = SSL_new(ctx->ssl_ctx);
224   if(!ctx->ssl) goto bail;
225   SSL_set_eventer_ssl_ctx(ctx->ssl, ctx);
226   return ctx;
227
228  bail:
229   eventer_ssl_error();
230   eventer_ssl_ctx_free(ctx);
231   return NULL;
232 }
233
234 /*
235  * This is a set of helpers to tie the SSL stuff to the eventer_t.
236  */
237 static int SSL_eventer_ssl_ctx_dataid = -1;
238 #define INIT_DATAID do { \
239   if(SSL_eventer_ssl_ctx_dataid == -1) \
240     SSL_eventer_ssl_ctx_dataid = \
241       SSL_get_ex_new_index(0, EVENTER_SSL_DATANAME, NULL, NULL, NULL); \
242 } while(0)
243
244 static void
245 SSL_set_eventer_ssl_ctx(SSL *ssl, eventer_ssl_ctx_t *ctx) {
246   INIT_DATAID;
247   SSL_set_ex_data(ssl, SSL_eventer_ssl_ctx_dataid, ctx);
248 }
249
250 static eventer_ssl_ctx_t *
251 SSL_get_eventer_ssl_ctx(SSL *ssl) {
252   INIT_DATAID;
253   return SSL_get_ex_data(ssl, SSL_eventer_ssl_ctx_dataid);
254 }
255
256 eventer_ssl_ctx_t *
257 eventer_get_eventer_ssl_ctx(eventer_t e) {
258   return (e->opset == eventer_SSL_fd_opset) ? e->opset_ctx : NULL;
259 }
260
261 void
262 eventer_set_eventer_ssl_ctx(eventer_t e, eventer_ssl_ctx_t *ctx) {
263   e->opset = eventer_SSL_fd_opset;
264   e->opset_ctx = ctx;
265   SSL_set_fd(ctx->ssl, e->fd);
266 }
267
268 void
269 eventer_ssl_ctx_set_verify(eventer_ssl_ctx_t *ctx,
270                            eventer_ssl_verify_func_t f, void *c) {
271   ctx->verify_cb = f;
272   ctx->verify_cb_closure = c;
273 }
274
275 /* Accept will perform the usual BSD socket accept and then
276  * hand it into the SSL system.
277  */
278 static int
279 _noallowed_eventer_SSL_accept(int fd, struct sockaddr *addr, socklen_t *len,
280                               int *mask, void *closure) {
281   return -1;
282 }
283
284 static int
285 eventer_SSL_setup(eventer_ssl_ctx_t *ctx) {
286   X509 *peer = NULL;
287   SSL_set_mode(ctx->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
288   peer = SSL_get_peer_certificate(ctx->ssl);
289
290   /* If have no peer, or the peer cert isn't okay, our
291    * callback won't fire, so fire it explicitly here.
292    * Learnt this from mod_ssl.
293    */
294   if(!peer ||
295      (peer && SSL_get_verify_result(ctx->ssl) != X509_V_OK)) {
296     if(ctx->verify_cb) {
297       return ctx->verify_cb(ctx, 0, NULL, ctx->verify_cb_closure);
298     }
299   }
300   return 0;
301 }
302
303 /* The read and write operations for ssl are almost identical.
304  * We read or write, depending on the need and if the SSL subsystem
305  * says we need more data to continue we mask for read, if it says
306  * we need need to write data to continue we mask for write.  Either
307  * way, we EAGAIN.
308  * If there is an SSL error, we spit it out and return EIO as that
309  * seems most appropriate.
310  */
311 static int
312 eventer_SSL_rw(int op, int fd, void *buffer, size_t len, int *mask,
313                void *closure) {
314   int rv, sslerror;
315   eventer_t e = closure;
316   eventer_ssl_ctx_t *ctx = e->opset_ctx;
317   int (*sslop)(SSL *) = NULL;
318
319   switch(op) {
320     case SSL_OP_READ:
321       if((rv = SSL_read(ctx->ssl, buffer, len)) > 0) return rv;
322       break;
323     case SSL_OP_WRITE:
324       if((rv = SSL_write(ctx->ssl, buffer, len)) > 0) return rv;
325       break;
326
327     case SSL_OP_CONNECT:
328       if(!sslop) sslop = SSL_connect;
329       /* fall through */
330     case SSL_OP_ACCEPT:
331       /* only set if we didn't fall through */
332       if(!sslop) sslop = SSL_accept;
333    
334       if((rv = sslop(ctx->ssl)) > 0) {
335         if(eventer_SSL_setup(ctx)) {
336           errno = EIO;
337           return -1;
338         }
339         return rv;
340       }
341       break;
342
343     default:
344       abort();
345   }
346
347   switch(sslerror = SSL_get_error(ctx->ssl, rv)) {
348     case SSL_ERROR_NONE:
349       return 0;
350     case SSL_ERROR_WANT_READ:
351     case SSL_ERROR_WANT_WRITE:
352       *mask = (sslerror == SSL_ERROR_WANT_READ) ?
353                 EVENTER_READ : EVENTER_WRITE;
354       errno = EAGAIN;
355       break;
356     default:
357       noitL(noit_error, "SSL rw error: %d\n", sslerror);
358       eventer_ssl_error();
359       errno = EIO;
360   }
361   return -1;
362 }
363
364 int
365 eventer_SSL_accept(eventer_t e, int *mask) {
366   return eventer_SSL_rw(SSL_OP_ACCEPT, e->fd, NULL, 0, mask, e);
367 }
368 int
369 eventer_SSL_connect(eventer_t e, int *mask) {
370   return eventer_SSL_rw(SSL_OP_CONNECT, e->fd, NULL, 0, mask, e);
371 }
372 static int
373 eventer_SSL_read(int fd, void *buffer, size_t len, int *mask, void *closure) {
374   int rv;
375   noitL(noit_debug, "SSL_read(%d) wants %ld bytes\n", fd, len);
376   rv = eventer_SSL_rw(SSL_OP_READ, fd, buffer, len, mask, closure);
377   noitL(noit_debug, "SSL_read(%d) wanted %ld bytes, got return value %d\n", fd, len, rv);
378   return rv;
379 }
380 static int
381 eventer_SSL_write(int fd, const void *buffer, size_t len, int *mask,
382                   void *closure) {
383   int rv;
384   noitL(noit_debug, "SSL_write(%d) wants %ld bytes\n", fd, len);
385   rv = eventer_SSL_rw(SSL_OP_WRITE, fd, (void *)buffer, len, mask, closure);
386   noitL(noit_debug, "SSL_write(%d) wanted %ld bytes, got return value %d\n", fd, len, rv);
387   return rv;
388 }
389
390 /* Close simply shuts down the SSL site and closes the file descriptor. */
391 static int
392 eventer_SSL_close(int fd, int *mask, void *closure) {
393   eventer_t e = closure;
394   eventer_ssl_ctx_t *ctx = e->opset_ctx;
395   SSL_shutdown(ctx->ssl);
396   eventer_ssl_ctx_free(ctx);
397   close(fd);
398   if(mask) *mask = 0;
399   return 0;
400 }
401
402 struct _fd_opset _eventer_SSL_fd_opset = {
403   _noallowed_eventer_SSL_accept,
404   eventer_SSL_read,
405   eventer_SSL_write,
406   eventer_SSL_close
407 };
408
409 eventer_fd_opset_t eventer_SSL_fd_opset = &_eventer_SSL_fd_opset;
410
411
412 /* Locking stuff to make libcrypto thread safe */
413 /* This stuff cribbed from the openssl examples */
414 struct CRYPTO_dynlock_value { pthread_mutex_t lock; };
415 static struct CRYPTO_dynlock_value *__lcks = NULL;
416 static void lock_static(int mode, int type, const char *f, int l) {
417   if(mode & CRYPTO_LOCK) pthread_mutex_lock(&__lcks[type].lock);
418   else pthread_mutex_unlock(&__lcks[type].lock);
419 }
420 static struct CRYPTO_dynlock_value *dynlock_create(const char *f, int l) {
421   struct CRYPTO_dynlock_value *lock = CRYPTO_malloc(sizeof(*lock),f,l);
422   pthread_mutex_init(&lock->lock,  NULL);
423   return lock;
424 }
425 static void dynlock_destroy(struct CRYPTO_dynlock_value *lock,
426                             const char *f, int l) {
427   pthread_mutex_destroy(&lock->lock);
428   CRYPTO_free(lock);
429 }
430 static void lock_dynamic(int mode, struct CRYPTO_dynlock_value *lock,
431                          const char *f, int l) {
432   if(mode & CRYPTO_LOCK) pthread_mutex_lock(&lock->lock);
433   else pthread_mutex_unlock(&lock->lock);
434 }
435 void eventer_ssl_init() {
436   int i, numlocks;
437   if(__lcks) return;
438   numlocks = CRYPTO_num_locks();
439   __lcks = CRYPTO_malloc(numlocks * sizeof(*__lcks),__FILE__,__LINE__);
440   for(i=0; i<numlocks; i++)
441     pthread_mutex_init(&__lcks[i].lock, NULL);
442   CRYPTO_set_id_callback((unsigned long (*)()) pthread_self);
443   CRYPTO_set_dynlock_create_callback(dynlock_create);
444   CRYPTO_set_dynlock_destroy_callback(dynlock_destroy);
445   CRYPTO_set_dynlock_lock_callback(lock_dynamic);
446   CRYPTO_set_locking_callback(lock_static);
447
448   SSL_load_error_strings();
449   SSL_library_init();
450   return;
451 }
452
Note: See TracBrowser for help on using the browser.