root/src/eventer/eventer_SSL_fd_opset.c

Revision eb243ce995835fef0bf9b9b01f491bc3908335f9, 16.2 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 9 years ago)

quiet stuff down a bit (err -> deb), refs #42

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
16  *       of its contributors may be used to endorse or promote products
17  *       derived from this software without specific prior written
18  *       permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "noit_defines.h"
34 #include "eventer/eventer.h"
35 #include "utils/noit_log.h"
36 #include "eventer/eventer_SSL_fd_opset.h"
37 #include "eventer/OETS_asn1_helper.h"
38
39 #include <sys/socket.h>
40 #include <unistd.h>
41
42 #include <openssl/ssl.h>
43 #include <openssl/err.h>
44 #include <openssl/engine.h>
45
46 #define EVENTER_SSL_DATANAME "eventer_ssl"
47
48 struct eventer_ssl_ctx_t {
49   SSL_CTX *ssl_ctx;
50   SSL     *ssl;
51   char    *issuer;
52   char    *subject;
53   time_t   start_time;
54   time_t   end_time;
55   char    *cert_error;
56   eventer_ssl_verify_func_t verify_cb;
57   void    *verify_cb_closure;
58   unsigned no_more_negotiations:1;
59   unsigned renegotiated:1;
60 };
61
62 /* Static function prototypes */
63 static void SSL_set_eventer_ssl_ctx(SSL *ssl, eventer_ssl_ctx_t *ctx);
64 static eventer_ssl_ctx_t *SSL_get_eventer_ssl_ctx(const SSL *ssl);
65 static void _eventer_ssl_error();
66 static RSA *tmp_rsa_cb(SSL *ssl, int export, int keylen);
67
68 #define eventer_ssl_error() _eventer_ssl_error(__FILE__,__LINE__)
69
70 static void
71 _eventer_ssl_error(const char *f, int l) {
72   unsigned long err;
73   char buf[120]; /* ERR_error_string(3): buf must be at least 120 bytes */
74   noitL(eventer_deb, "%s:%d: errno: [%d] %s\n", f, l, errno, strerror(errno));
75   while((err = ERR_get_error()) != 0) {
76     ERR_error_string(err, buf);
77     noitL(eventer_deb, "%s:%d: write error[%08lx] %s\n", f, l, err, buf);
78   }
79 }
80
81 /*
82  * Cribbed from SSL examples.
83  */
84 static char *tmpkeyfile = NULL;
85 static time_t tmpkeyfile_time = 0;
86 static RSA *
87 tmp_rsa_cb(SSL *ssl, int export, int keylen) {
88   RSA *tmpkey;
89   if (!export) keylen = 512;
90   if (tmpkeyfile && keylen == 512) {
91     BIO *in = BIO_new_file(tmpkeyfile, "r");
92     if (in) {
93       RSA *rsa = PEM_read_bio_RSAPrivateKey(in,NULL,NULL,NULL);
94       BIO_free(in);
95       if (rsa) return rsa;
96     }
97   }
98   tmpkey = RSA_generate_key(keylen,RSA_F4,NULL,NULL);
99   if(tmpkeyfile && keylen == 512) {
100     BIO *out = BIO_new_file(tmpkeyfile, "r");
101     if(!out ||
102        !PEM_write_bio_RSAPrivateKey(out, tmpkey, NULL, NULL, 0, 0, NULL)) {
103       noitL(eventer_err, "Could not save temporary RSA key to %s\n", tmpkeyfile);
104     } else {
105       tmpkeyfile_time = time(NULL);
106     }
107     if(out) BIO_free(out);
108   }
109   return tmpkey;
110 }
111
112 int
113 eventer_ssl_verify_dates(eventer_ssl_ctx_t *ctx, int ok,
114                          X509_STORE_CTX *x509ctx, void *closure) {
115   time_t now;
116   int err;
117   X509 *peer;
118   ASN1_TIME *t;
119   if(!x509ctx) return -1;
120   peer = X509_STORE_CTX_get_current_cert(x509ctx);
121   time(&now);
122   t = X509_get_notBefore(peer);
123   ctx->start_time = OETS_ASN1_TIME_get(t, &err);
124   if(X509_cmp_time(t, &now) > 0) return -1;
125   t = X509_get_notAfter(peer);
126   ctx->end_time = OETS_ASN1_TIME_get(t, &err);
127   if(X509_cmp_time(t, &now) < 0) return 1;
128   return 0;
129 }
130
131 int
132 eventer_ssl_verify_cert(eventer_ssl_ctx_t *ctx, int ok,
133                         X509_STORE_CTX *x509ctx, void *closure) {
134   SSL *ssl;
135   noit_hash_table *options = closure;
136   const char *opt_no_ca, *ignore_dates;
137   int v_res;
138
139   if(!x509ctx) return 0;
140
141   if(!noit_hash_retr_str(options, "optional_no_ca", strlen("optional_no_ca"),
142                          &opt_no_ca))
143     opt_no_ca = "false";
144   if(!noit_hash_retr_str(options, "ignore_dates", strlen("ignore_dates"),
145                          &ignore_dates))
146     ignore_dates = "false";
147
148   if(options == NULL) {
149     /* Don't care about anything */
150     opt_no_ca = "true";
151     ignore_dates = "true";
152   }
153   ssl = X509_STORE_CTX_get_ex_data(x509ctx,
154                                    SSL_get_ex_data_X509_STORE_CTX_idx());
155   v_res = X509_STORE_CTX_get_error(x509ctx);
156
157   if((v_res == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) ||
158      (v_res == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) ||
159      (v_res == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) ||
160      (v_res == X509_V_ERR_CERT_UNTRUSTED) ||
161      (v_res == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE)) {
162     ctx->cert_error = strdup(X509_verify_cert_error_string(v_res));
163     if(!strcmp(opt_no_ca, "true")) ok = 1;
164     else {
165       noitL(eventer_deb, "SSL client cert invalid: %s\n",
166             X509_verify_cert_error_string(v_res));
167       ok = 0;
168       goto set_out;
169     }
170   }
171   v_res = eventer_ssl_verify_dates(ctx, ok, x509ctx, closure);
172   if(v_res != 0) {
173     if(!strcmp(ignore_dates, "true")) ok = 1;
174     else {
175       noitL(eventer_deb, "SSL client cert is %s valid.\n",
176             (v_res < 0) ? "not yet" : "no longer");
177       ok = 0;
178       goto set_out;
179     }
180   }
181  set_out:
182   return ok;
183 }
184
185 #define GET_SET_X509_NAME(type) \
186 static void \
187 eventer_ssl_set_peer_##type(eventer_ssl_ctx_t *ctx, \
188                              X509_STORE_CTX *x509ctx) { \
189   char buffer[1024]; \
190   X509 *peer; \
191   peer = X509_STORE_CTX_get_current_cert(x509ctx); \
192   X509_NAME_oneline(X509_get_##type##_name(peer), buffer, sizeof(buffer)-1); \
193   if(ctx->type) free(ctx->type); \
194   ctx->type = strdup(buffer); \
195 } \
196 const char * \
197 eventer_ssl_get_peer_##type(eventer_ssl_ctx_t *ctx) { \
198   return ctx->type; \
199 }
200
201 GET_SET_X509_NAME(issuer)
202 GET_SET_X509_NAME(subject)
203
204 time_t
205 eventer_ssl_get_peer_start_time(eventer_ssl_ctx_t *ctx) {
206   return ctx->start_time;
207 }
208 time_t
209 eventer_ssl_get_peer_end_time(eventer_ssl_ctx_t *ctx) {
210   return ctx->end_time;
211 }
212 const char *
213 eventer_ssl_get_peer_error(eventer_ssl_ctx_t *ctx) {
214   return ctx->cert_error;
215 }
216
217 static int
218 verify_cb(int ok, X509_STORE_CTX *x509ctx) {
219   eventer_ssl_ctx_t *ctx;
220   SSL *ssl;
221
222   ssl = X509_STORE_CTX_get_ex_data(x509ctx,
223                                    SSL_get_ex_data_X509_STORE_CTX_idx());
224   ctx = SSL_get_eventer_ssl_ctx(ssl);
225   eventer_ssl_set_peer_subject(ctx, x509ctx);
226   eventer_ssl_set_peer_issuer(ctx, x509ctx);
227   if(ctx->verify_cb)
228     return ctx->verify_cb(ctx, ok, x509ctx, ctx->verify_cb_closure);
229   return ok;
230 }
231
232 /*
233  * Helpers to create and destroy our context.
234  */
235 void
236 eventer_ssl_ctx_free(eventer_ssl_ctx_t *ctx) {
237   if(ctx->ssl) SSL_free(ctx->ssl);
238   if(ctx->ssl_ctx) SSL_CTX_free(ctx->ssl_ctx);
239   if(ctx->issuer) free(ctx->issuer);
240   if(ctx->subject) free(ctx->subject);
241   if(ctx->cert_error) free(ctx->cert_error);
242   free(ctx);
243 }
244
245 static void
246 eventer_SSL_server_info_callback(const SSL *ssl, int type, int val) {
247   eventer_ssl_ctx_t *ctx;
248
249   if (ssl->state != SSL3_ST_SR_CLNT_HELLO_A &&
250       ssl->state != SSL23_ST_SR_CLNT_HELLO_A)
251     return;
252
253   ctx = SSL_get_eventer_ssl_ctx(ssl);
254   if(ctx->no_more_negotiations) {
255     noitL(eventer_deb, "eventer_SSL_server_info_callback ... reneg is bad\n");
256     ctx->renegotiated = 1;
257   }
258 }
259
260 eventer_ssl_ctx_t *
261 eventer_ssl_ctx_new(eventer_ssl_orientation_t type,
262                     const char *certificate, const char *key,
263                     const char *ca, const char *ciphers) {
264   eventer_ssl_ctx_t *ctx;
265   ctx = calloc(1, sizeof(*ctx));
266   if(!ctx) return NULL;
267   /*
268    * First step is to setup the SSL context.  This is long-lived in SSL-land
269    * however, that would require us caching it.  Maybe we'll do that?
270    */
271   ctx->ssl_ctx = SSL_CTX_new(type == SSL_SERVER ?
272                              SSLv23_server_method() : SSLv23_client_method());
273   if(!ctx->ssl_ctx) return NULL;
274   if (type == SSL_SERVER)
275     SSL_CTX_set_session_id_context(ctx->ssl_ctx,
276             (unsigned char *)EVENTER_SSL_DATANAME,
277             sizeof(EVENTER_SSL_DATANAME)-1);
278   SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_ALL);
279   if(certificate &&
280      SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, certificate) != 1)
281     goto bail;
282   if(key &&
283      SSL_CTX_use_RSAPrivateKey_file(ctx->ssl_ctx,key,
284                                     SSL_FILETYPE_PEM) != 1)
285     goto bail;
286   if(ca) {
287     STACK_OF(X509_NAME) *cert_stack;
288     if(!SSL_CTX_load_verify_locations(ctx->ssl_ctx,ca,NULL) ||
289        (cert_stack = SSL_load_client_CA_file(ca)) == NULL)
290       goto bail;
291     SSL_CTX_set_client_CA_list(ctx->ssl_ctx, cert_stack);
292   }
293   SSL_CTX_set_tmp_rsa_callback(ctx->ssl_ctx, tmp_rsa_cb);
294   SSL_CTX_set_cipher_list(ctx->ssl_ctx, ciphers ? ciphers : "DEFAULT");
295   SSL_CTX_set_verify(ctx->ssl_ctx, SSL_VERIFY_PEER, verify_cb);
296   SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
297
298   ctx->ssl = SSL_new(ctx->ssl_ctx);
299   if(!ctx->ssl) goto bail;
300   SSL_set_info_callback(ctx->ssl, eventer_SSL_server_info_callback);
301   SSL_set_eventer_ssl_ctx(ctx->ssl, ctx);
302   return ctx;
303
304  bail:
305   eventer_ssl_error();
306   eventer_ssl_ctx_free(ctx);
307   return NULL;
308 }
309
310 /*
311  * This is a set of helpers to tie the SSL stuff to the eventer_t.
312  */
313 static int SSL_eventer_ssl_ctx_dataid = -1;
314 #define INIT_DATAID do { \
315   if(SSL_eventer_ssl_ctx_dataid == -1) \
316     SSL_eventer_ssl_ctx_dataid = \
317       SSL_get_ex_new_index(0, EVENTER_SSL_DATANAME, NULL, NULL, NULL); \
318 } while(0)
319
320 static void
321 SSL_set_eventer_ssl_ctx(SSL *ssl, eventer_ssl_ctx_t *ctx) {
322   INIT_DATAID;
323   SSL_set_ex_data(ssl, SSL_eventer_ssl_ctx_dataid, ctx);
324 }
325
326 static eventer_ssl_ctx_t *
327 SSL_get_eventer_ssl_ctx(const SSL *ssl) {
328   INIT_DATAID;
329   return SSL_get_ex_data(ssl, SSL_eventer_ssl_ctx_dataid);
330 }
331
332 eventer_ssl_ctx_t *
333 eventer_get_eventer_ssl_ctx(const eventer_t e) {
334   return (e->opset == eventer_SSL_fd_opset) ? e->opset_ctx : NULL;
335 }
336
337 void
338 eventer_set_eventer_ssl_ctx(eventer_t e, eventer_ssl_ctx_t *ctx) {
339   e->opset = eventer_SSL_fd_opset;
340   e->opset_ctx = ctx;
341   SSL_set_fd(ctx->ssl, e->fd);
342 }
343
344 void
345 eventer_ssl_ctx_set_verify(eventer_ssl_ctx_t *ctx,
346                            eventer_ssl_verify_func_t f, void *c) {
347   ctx->verify_cb = f;
348   ctx->verify_cb_closure = c;
349 }
350
351 /* Accept will perform the usual BSD socket accept and then
352  * hand it into the SSL system.
353  */
354 static int
355 _noallowed_eventer_SSL_accept(int fd, struct sockaddr *addr, socklen_t *len,
356                               int *mask, void *closure) {
357   return -1;
358 }
359
360 static int
361 eventer_SSL_setup(eventer_ssl_ctx_t *ctx) {
362   X509 *peer = NULL;
363   SSL_set_mode(ctx->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
364   peer = SSL_get_peer_certificate(ctx->ssl);
365
366   /* If have no peer, or the peer cert isn't okay, our
367    * callback won't fire, so fire it explicitly here.
368    * Learnt this from mod_ssl.
369    */
370   if(!peer ||
371      (peer && SSL_get_verify_result(ctx->ssl) != X509_V_OK)) {
372     if(ctx->verify_cb) {
373       return ctx->verify_cb(ctx, 0, NULL, ctx->verify_cb_closure);
374     }
375   }
376   return 0;
377 }
378
379 /* The read and write operations for ssl are almost identical.
380  * We read or write, depending on the need and if the SSL subsystem
381  * says we need more data to continue we mask for read, if it says
382  * we need need to write data to continue we mask for write.  Either
383  * way, we EAGAIN.
384  * If there is an SSL error, we spit it out and return EIO as that
385  * seems most appropriate.
386  */
387 static int
388 eventer_SSL_rw(int op, int fd, void *buffer, size_t len, int *mask,
389                void *closure) {
390   int rv, sslerror;
391   eventer_t e = closure;
392   eventer_ssl_ctx_t *ctx = e->opset_ctx;
393   int (*sslop)(SSL *) = NULL;
394   const char *opstr = "none";
395
396   switch(op) {
397     case SSL_OP_READ:
398       opstr = "read";
399       if((rv = SSL_read(ctx->ssl, buffer, len)) > 0) return rv;
400       break;
401     case SSL_OP_WRITE:
402       opstr = "write";
403       if((rv = SSL_write(ctx->ssl, buffer, len)) > 0) return rv;
404       break;
405
406     case SSL_OP_CONNECT:
407       opstr = "connect";
408       if(!sslop) sslop = SSL_connect;
409       /* fall through */
410     case SSL_OP_ACCEPT:
411       opstr = "accept";
412       /* only set if we didn't fall through */
413       if(!sslop) sslop = SSL_accept;
414    
415       if((rv = sslop(ctx->ssl)) > 0) {
416         if(eventer_SSL_setup(ctx)) {
417           errno = EIO;
418           return -1;
419         }
420         ctx->no_more_negotiations = 1;
421         return rv;
422       }
423       break;
424
425     default:
426       abort();
427   }
428
429   if(ctx->renegotiated) {
430     noitL(eventer_err, "SSL renogotiation attempted on %d\n", fd);
431     errno = EIO;
432     return -1;
433   }
434
435   switch(sslerror = SSL_get_error(ctx->ssl, rv)) {
436     case SSL_ERROR_NONE:
437       return 0;
438     case SSL_ERROR_WANT_READ:
439     case SSL_ERROR_WANT_WRITE:
440       *mask = (sslerror == SSL_ERROR_WANT_READ) ?
441                 EVENTER_READ : EVENTER_WRITE;
442       errno = EAGAIN;
443       break;
444     default:
445       noitL(eventer_deb, "SSL[%s of %d] rw error: %d\n", opstr,
446             (int)len, sslerror);
447       eventer_ssl_error();
448       errno = EIO;
449   }
450   return -1;
451 }
452
453 int
454 eventer_SSL_renegotiate(eventer_t e) {
455   eventer_ssl_ctx_t *ctx;
456   ctx = eventer_get_eventer_ssl_ctx(e);
457   SSL_renegotiate(ctx->ssl);
458   return 0;
459 }
460
461 int
462 eventer_SSL_accept(eventer_t e, int *mask) {
463   return eventer_SSL_rw(SSL_OP_ACCEPT, e->fd, NULL, 0, mask, e);
464 }
465 int
466 eventer_SSL_connect(eventer_t e, int *mask) {
467   return eventer_SSL_rw(SSL_OP_CONNECT, e->fd, NULL, 0, mask, e);
468 }
469 static int
470 eventer_SSL_read(int fd, void *buffer, size_t len, int *mask, void *closure) {
471   int rv;
472   rv = eventer_SSL_rw(SSL_OP_READ, fd, buffer, len, mask, closure);
473   return rv;
474 }
475 static int
476 eventer_SSL_write(int fd, const void *buffer, size_t len, int *mask,
477                   void *closure) {
478   int rv;
479   rv = eventer_SSL_rw(SSL_OP_WRITE, fd, (void *)buffer, len, mask, closure);
480   return rv;
481 }
482
483 /* Close simply shuts down the SSL site and closes the file descriptor. */
484 static int
485 eventer_SSL_close(int fd, int *mask, void *closure) {
486   eventer_t e = closure;
487   eventer_ssl_ctx_t *ctx = e->opset_ctx;
488   SSL_shutdown(ctx->ssl);
489   eventer_ssl_ctx_free(ctx);
490   close(fd);
491   if(mask) *mask = 0;
492   return 0;
493 }
494
495 struct _fd_opset _eventer_SSL_fd_opset = {
496   _noallowed_eventer_SSL_accept,
497   eventer_SSL_read,
498   eventer_SSL_write,
499   eventer_SSL_close
500 };
501
502 eventer_fd_opset_t eventer_SSL_fd_opset = &_eventer_SSL_fd_opset;
503
504
505 /* Locking stuff to make libcrypto thread safe */
506 /* This stuff cribbed from the openssl examples */
507 struct CRYPTO_dynlock_value { pthread_mutex_t lock; };
508 static struct CRYPTO_dynlock_value *__lcks = NULL;
509 static void lock_static(int mode, int type, const char *f, int l) {
510   if(mode & CRYPTO_LOCK) pthread_mutex_lock(&__lcks[type].lock);
511   else pthread_mutex_unlock(&__lcks[type].lock);
512 }
513 static struct CRYPTO_dynlock_value *dynlock_create(const char *f, int l) {
514   struct CRYPTO_dynlock_value *lock = CRYPTO_malloc(sizeof(*lock),f,l);
515   pthread_mutex_init(&lock->lock,  NULL);
516   return lock;
517 }
518 static void dynlock_destroy(struct CRYPTO_dynlock_value *lock,
519                             const char *f, int l) {
520   pthread_mutex_destroy(&lock->lock);
521   CRYPTO_free(lock);
522 }
523 static void lock_dynamic(int mode, struct CRYPTO_dynlock_value *lock,
524                          const char *f, int l) {
525   if(mode & CRYPTO_LOCK) pthread_mutex_lock(&lock->lock);
526   else pthread_mutex_unlock(&lock->lock);
527 }
528 void eventer_ssl_init() {
529   int i, numlocks;
530   if(__lcks) return;
531   numlocks = CRYPTO_num_locks();
532   __lcks = CRYPTO_malloc(numlocks * sizeof(*__lcks),__FILE__,__LINE__);
533   for(i=0; i<numlocks; i++)
534     pthread_mutex_init(&__lcks[i].lock, NULL);
535   CRYPTO_set_id_callback((unsigned long (*)()) pthread_self);
536   CRYPTO_set_dynlock_create_callback(dynlock_create);
537   CRYPTO_set_dynlock_destroy_callback(dynlock_destroy);
538   CRYPTO_set_dynlock_lock_callback(lock_dynamic);
539   CRYPTO_set_locking_callback(lock_static);
540
541   SSL_load_error_strings();
542   SSL_library_init();
543   return;
544 }
545
Note: See TracBrowser for help on using the browser.