Fix a crash in tcp and tls connections related to reference counts.
[asterisk/asterisk.git] / main / tcptls.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2008, Digium, Inc.
5  *
6  * Luigi Rizzo (TCP and TLS server code)
7  * Brett Bryant <brettbryant@gmail.com> (updated for client support)
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*!
21  * \file
22  * \brief Code to support TCP and TLS server/client
23  *
24  * \author Luigi Rizzo
25  * \author Brett Bryant <brettbryant@gmail.com>
26  */
27
28 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #ifdef HAVE_FCNTL_H
33 #include <fcntl.h>
34 #endif
35
36 #include <sys/signal.h>
37
38 #include "asterisk/compat.h"
39 #include "asterisk/tcptls.h"
40 #include "asterisk/http.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/strings.h"
43 #include "asterisk/options.h"
44 #include "asterisk/manager.h"
45
46 /*! \brief
47  * replacement read/write functions for SSL support.
48  * We use wrappers rather than SSL_read/SSL_write directly so
49  * we can put in some debugging.
50  */
51
52 #ifdef DO_SSL
53 static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
54 {
55         int i = SSL_read(cookie, buf, len-1);
56 #if 0
57         if (i >= 0)
58                 buf[i] = '\0';
59         ast_verb(0, "ssl read size %d returns %d <%s>\n", (int)len, i, buf);
60 #endif
61         return i;
62 }
63
64 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
65 {
66 #if 0
67         char *s = alloca(len+1);
68         strncpy(s, buf, len);
69         s[len] = '\0';
70         ast_verb(0, "ssl write size %d <%s>\n", (int)len, s);
71 #endif
72         return SSL_write(cookie, buf, len);
73 }
74
75 static int ssl_close(void *cookie)
76 {
77         close(SSL_get_fd(cookie));
78         SSL_shutdown(cookie);
79         SSL_free(cookie);
80         return 0;
81 }
82 #endif  /* DO_SSL */
83
84 HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *ser, void *buf, size_t count)
85 {
86         if (ser->fd == -1) {
87                 ast_log(LOG_ERROR, "server_read called with an fd of -1\n");
88                 errno = EIO;
89                 return -1;
90         }
91
92 #ifdef DO_SSL
93         if (ser->ssl)
94                 return ssl_read(ser->ssl, buf, count);
95 #endif
96         return read(ser->fd, buf, count);
97 }
98
99 HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *ser, void *buf, size_t count)
100 {
101         if (ser->fd == -1) {
102                 ast_log(LOG_ERROR, "server_write called with an fd of -1\n");
103                 errno = EIO;
104                 return -1;
105         }
106
107 #ifdef DO_SSL
108         if (ser->ssl)
109                 return ssl_write(ser->ssl, buf, count);
110 #endif
111         return write(ser->fd, buf, count);
112 }
113
114 static void session_instance_destructor(void *obj)
115 {
116         struct ast_tcptls_session_instance *i = obj;
117         ast_mutex_destroy(&i->lock);
118 }
119
120 void *ast_tcptls_server_root(void *data)
121 {
122         struct server_args *desc = data;
123         int fd;
124         struct sockaddr_in sin;
125         socklen_t sinlen;
126         struct ast_tcptls_session_instance *ser;
127         pthread_t launched;
128         
129         for (;;) {
130                 int i, flags;
131
132                 if (desc->periodic_fn)
133                         desc->periodic_fn(desc);
134                 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
135                 if (i <= 0)
136                         continue;
137                 sinlen = sizeof(sin);
138                 fd = accept(desc->accept_fd, (struct sockaddr *)&sin, &sinlen);
139                 if (fd < 0) {
140                         if ((errno != EAGAIN) && (errno != EINTR))
141                                 ast_log(LOG_WARNING, "Accept failed: %s\n", strerror(errno));
142                         continue;
143                 }
144                 ser = ao2_alloc(sizeof(*ser), session_instance_destructor);
145                 if (!ser) {
146                         ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
147                         close(fd);
148                         continue;
149                 }
150
151                 ast_mutex_init(&ser->lock);
152
153                 flags = fcntl(fd, F_GETFL);
154                 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
155                 ser->fd = fd;
156                 ser->parent = desc;
157                 memcpy(&ser->requestor, &sin, sizeof(ser->requestor));
158
159                 ser->client = 0;
160                         
161                 if (ast_pthread_create_detached_background(&launched, NULL, ast_make_file_from_fd, ser)) {
162                         ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
163                         close(ser->fd);
164                         ao2_ref(ser, -1);
165                 }
166         }
167         return NULL;
168 }
169
170 static int __ssl_setup(struct ast_tls_config *cfg, int client)
171 {
172 #ifndef DO_SSL
173         cfg->enabled = 0;
174         return 0;
175 #else
176         if (!cfg->enabled)
177                 return 0;
178
179         SSL_load_error_strings();
180         SSLeay_add_ssl_algorithms();
181
182         if (!(cfg->ssl_ctx = SSL_CTX_new( client ? SSLv23_client_method() : SSLv23_server_method() ))) {
183                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
184                 cfg->enabled = 0;
185                 return 0;
186         }
187         if (!ast_strlen_zero(cfg->certfile)) {
188                 if (SSL_CTX_use_certificate_file(cfg->ssl_ctx, cfg->certfile, SSL_FILETYPE_PEM) == 0 ||
189                     SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, cfg->certfile, SSL_FILETYPE_PEM) == 0 ||
190                     SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 ) {
191                         if (!client) {
192                                 /* Clients don't need a certificate, but if its setup we can use it */
193                                 ast_verb(0, "SSL cert error <%s>", cfg->certfile);
194                                 sleep(2);
195                                 cfg->enabled = 0;
196                                 return 0;
197                         }
198                 }
199         }
200         if (!ast_strlen_zero(cfg->cipher)) {
201                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
202                         if (!client) {
203                                 ast_verb(0, "SSL cipher error <%s>", cfg->cipher);
204                                 sleep(2);
205                                 cfg->enabled = 0;
206                                 return 0;
207                         }
208                 }
209         }
210         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
211                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0)
212                         ast_verb(0, "SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
213         }
214
215         ast_verb(0, "SSL certificate ok\n");
216         return 1;
217 #endif
218 }
219
220 int ast_ssl_setup(struct ast_tls_config *cfg)
221 {
222         return __ssl_setup(cfg, 0);
223 }
224
225 /*! \brief A generic client routine for a TCP client
226  *  and starts a thread for handling accept()
227  */
228 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct server_args *desc)
229 {
230         int flags;
231         struct ast_tcptls_session_instance *ser = NULL;
232
233         /* Do nothing if nothing has changed */
234         if(!memcmp(&desc->oldsin, &desc->sin, sizeof(desc->oldsin))) {
235                 ast_debug(1, "Nothing changed in %s\n", desc->name);
236                 return NULL;
237         }
238
239         desc->oldsin = desc->sin;
240
241         if (desc->accept_fd != -1)
242                 close(desc->accept_fd);
243
244         desc->accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
245         if (desc->accept_fd < 0) {
246                 ast_log(LOG_WARNING, "Unable to allocate socket for %s: %s\n",
247                         desc->name, strerror(errno));
248                 return NULL;
249         }
250
251         if (connect(desc->accept_fd, (const struct sockaddr *)&desc->sin, sizeof(desc->sin))) {
252                 ast_log(LOG_ERROR, "Unable to connect %s to %s:%d: %s\n",
253                         desc->name,
254                         ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
255                         strerror(errno));
256                 goto error;
257         }
258
259         if (!(ser = ao2_alloc(sizeof(*ser), session_instance_destructor)))
260                 goto error;
261
262         ast_mutex_init(&ser->lock);
263
264         flags = fcntl(desc->accept_fd, F_GETFL);
265         fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
266
267         ser->fd = desc->accept_fd;
268         ser->parent = desc;
269         ser->parent->worker_fn = NULL;
270         memcpy(&ser->requestor, &desc->sin, sizeof(ser->requestor));
271
272         ser->client = 1;
273
274         if (desc->tls_cfg) {
275                 desc->tls_cfg->enabled = 1;
276                 __ssl_setup(desc->tls_cfg, 1);
277         }
278
279         ao2_ref(ser, +1);
280         if (!ast_make_file_from_fd(ser))
281                 goto error;
282
283         return ser;
284
285 error:
286         close(desc->accept_fd);
287         desc->accept_fd = -1;
288         if (ser)
289                 ao2_ref(ser, -1);
290         return NULL;
291 }
292
293 /*! \brief
294  * This is a generic (re)start routine for a TCP server,
295  * which does the socket/bind/listen and starts a thread for handling
296  * accept().
297  */
298 void ast_tcptls_server_start(struct server_args *desc)
299 {
300         int flags;
301         int x = 1;
302         
303         /* Do nothing if nothing has changed */
304         if (!memcmp(&desc->oldsin, &desc->sin, sizeof(desc->oldsin))) {
305                 ast_debug(1, "Nothing changed in %s\n", desc->name);
306                 return;
307         }
308         
309         desc->oldsin = desc->sin;
310         
311         /* Shutdown a running server if there is one */
312         if (desc->master != AST_PTHREADT_NULL) {
313                 pthread_cancel(desc->master);
314                 pthread_kill(desc->master, SIGURG);
315                 pthread_join(desc->master, NULL);
316         }
317         
318         if (desc->accept_fd != -1)
319                 close(desc->accept_fd);
320
321         /* If there's no new server, stop here */
322         if (desc->sin.sin_family == 0)
323                 return;
324
325         desc->accept_fd = socket(AF_INET, SOCK_STREAM, 0);
326         if (desc->accept_fd < 0) {
327                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
328                         desc->name, strerror(errno));
329                 return;
330         }
331         
332         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
333         if (bind(desc->accept_fd, (struct sockaddr *)&desc->sin, sizeof(desc->sin))) {
334                 ast_log(LOG_ERROR, "Unable to bind %s to %s:%d: %s\n",
335                         desc->name,
336                         ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
337                         strerror(errno));
338                 goto error;
339         }
340         if (listen(desc->accept_fd, 10)) {
341                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
342                 goto error;
343         }
344         flags = fcntl(desc->accept_fd, F_GETFL);
345         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
346         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
347                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s:%d: %s\n",
348                         desc->name,
349                         ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
350                         strerror(errno));
351                 goto error;
352         }
353         return;
354
355 error:
356         close(desc->accept_fd);
357         desc->accept_fd = -1;
358 }
359
360 /*! \brief Shutdown a running server if there is one */
361 void ast_tcptls_server_stop(struct server_args *desc)
362 {
363         if (desc->master != AST_PTHREADT_NULL) {
364                 pthread_cancel(desc->master);
365                 pthread_kill(desc->master, SIGURG);
366                 pthread_join(desc->master, NULL);
367         }
368         if (desc->accept_fd != -1)
369                 close(desc->accept_fd);
370         desc->accept_fd = -1;
371 }
372
373 /*! \brief
374 * creates a FILE * from the fd passed by the accept thread.
375 * This operation is potentially expensive (certificate verification),
376 * so we do it in the child thread context.
377 */
378 void *ast_make_file_from_fd(void *data)
379 {
380         struct ast_tcptls_session_instance *ser = data;
381 #ifdef DO_SSL
382         int (*ssl_setup)(SSL *) = (ser->client) ? SSL_connect : SSL_accept;
383         int ret;
384         char err[256];
385 #endif
386
387         /*
388         * open a FILE * as appropriate.
389         */
390         if (!ser->parent->tls_cfg)
391                 ser->f = fdopen(ser->fd, "w+");
392 #ifdef DO_SSL
393         else if ( (ser->ssl = SSL_new(ser->parent->tls_cfg->ssl_ctx)) ) {
394                 SSL_set_fd(ser->ssl, ser->fd);
395                 if ((ret = ssl_setup(ser->ssl)) <= 0) {
396                         ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
397                 } else {
398 #if defined(HAVE_FUNOPEN)       /* the BSD interface */
399                         ser->f = funopen(ser->ssl, ssl_read, ssl_write, NULL, ssl_close);
400
401 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
402                         static const cookie_io_functions_t cookie_funcs = {
403                                 ssl_read, ssl_write, NULL, ssl_close
404                         };
405                         ser->f = fopencookie(ser->ssl, "w+", cookie_funcs);
406 #else
407                         /* could add other methods here */
408                         ast_debug(2, "no ser->f methods attempted!");
409 #endif
410                         if ((ser->client && !ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
411                                 || (!ser->client && ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
412                                 X509 *peer;
413                                 long res;
414                                 peer = SSL_get_peer_certificate(ser->ssl);
415                                 if (!peer)
416                                         ast_log(LOG_WARNING, "No peer SSL certificate\n");
417                                 res = SSL_get_verify_result(ser->ssl);
418                                 if (res != X509_V_OK)
419                                         ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
420                                 if (!ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
421                                         ASN1_STRING *str;
422                                         unsigned char *str2;
423                                         X509_NAME *name = X509_get_subject_name(peer);
424                                         int pos = -1;
425                                         int found = 0;
426                                 
427                                         for (;;) {
428                                                 /* Walk the certificate to check all available "Common Name" */
429                                                 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
430                                                 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
431                                                 if (pos < 0)
432                                                         break;
433                                                 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
434                                                 ASN1_STRING_to_UTF8(&str2, str);
435                                                 if (str2) {
436                                                         if (!strcasecmp(ser->parent->hostname, (char *) str2))
437                                                                 found = 1;
438                                                         ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", ser->parent->hostname, str2);
439                                                         OPENSSL_free(str2);
440                                                 }
441                                                 if (found)
442                                                         break;
443                                         }
444                                         if (!found) {
445                                                 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", ser->parent->hostname);
446                                                 if (peer)
447                                                         X509_free(peer);
448                                                 fclose(ser->f);
449                                                 return NULL;
450                                         }
451                                 }
452                                 if (peer)
453                                         X509_free(peer);
454                         }
455                 }
456                 if (!ser->f)    /* no success opening descriptor stacking */
457                         SSL_free(ser->ssl);
458    }
459 #endif /* DO_SSL */
460
461         if (!ser->f) {
462                 close(ser->fd);
463                 ast_log(LOG_WARNING, "FILE * open failed!\n");
464                 ao2_ref(ser, -1);
465                 return NULL;
466         }
467
468         if (ser && ser->parent->worker_fn)
469                 return ser->parent->worker_fn(ser);
470         else
471                 return ser;
472 }
473