Updates all usages of ast_tcptls_session_instance to be managed by 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         if (!ast_make_file_from_fd(ser))
280                 goto error;
281
282         return ser;
283
284 error:
285         close(desc->accept_fd);
286         desc->accept_fd = -1;
287         if (ser)
288                 ao2_ref(ser, -1);
289         return NULL;
290 }
291
292 /*! \brief
293  * This is a generic (re)start routine for a TCP server,
294  * which does the socket/bind/listen and starts a thread for handling
295  * accept().
296  */
297 void ast_tcptls_server_start(struct server_args *desc)
298 {
299         int flags;
300         int x = 1;
301         
302         /* Do nothing if nothing has changed */
303         if (!memcmp(&desc->oldsin, &desc->sin, sizeof(desc->oldsin))) {
304                 ast_debug(1, "Nothing changed in %s\n", desc->name);
305                 return;
306         }
307         
308         desc->oldsin = desc->sin;
309         
310         /* Shutdown a running server if there is one */
311         if (desc->master != AST_PTHREADT_NULL) {
312                 pthread_cancel(desc->master);
313                 pthread_kill(desc->master, SIGURG);
314                 pthread_join(desc->master, NULL);
315         }
316         
317         if (desc->accept_fd != -1)
318                 close(desc->accept_fd);
319
320         /* If there's no new server, stop here */
321         if (desc->sin.sin_family == 0)
322                 return;
323
324         desc->accept_fd = socket(AF_INET, SOCK_STREAM, 0);
325         if (desc->accept_fd < 0) {
326                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
327                         desc->name, strerror(errno));
328                 return;
329         }
330         
331         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
332         if (bind(desc->accept_fd, (struct sockaddr *)&desc->sin, sizeof(desc->sin))) {
333                 ast_log(LOG_ERROR, "Unable to bind %s to %s:%d: %s\n",
334                         desc->name,
335                         ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
336                         strerror(errno));
337                 goto error;
338         }
339         if (listen(desc->accept_fd, 10)) {
340                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
341                 goto error;
342         }
343         flags = fcntl(desc->accept_fd, F_GETFL);
344         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
345         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
346                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s:%d: %s\n",
347                         desc->name,
348                         ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
349                         strerror(errno));
350                 goto error;
351         }
352         return;
353
354 error:
355         close(desc->accept_fd);
356         desc->accept_fd = -1;
357 }
358
359 /*! \brief Shutdown a running server if there is one */
360 void ast_tcptls_server_stop(struct server_args *desc)
361 {
362         if (desc->master != AST_PTHREADT_NULL) {
363                 pthread_cancel(desc->master);
364                 pthread_kill(desc->master, SIGURG);
365                 pthread_join(desc->master, NULL);
366         }
367         if (desc->accept_fd != -1)
368                 close(desc->accept_fd);
369         desc->accept_fd = -1;
370 }
371
372 /*! \brief
373 * creates a FILE * from the fd passed by the accept thread.
374 * This operation is potentially expensive (certificate verification),
375 * so we do it in the child thread context.
376 */
377 void *ast_make_file_from_fd(void *data)
378 {
379         struct ast_tcptls_session_instance *ser = data;
380 #ifdef DO_SSL
381         int (*ssl_setup)(SSL *) = (ser->client) ? SSL_connect : SSL_accept;
382         int ret;
383         char err[256];
384 #endif
385
386         /*
387         * open a FILE * as appropriate.
388         */
389         if (!ser->parent->tls_cfg)
390                 ser->f = fdopen(ser->fd, "w+");
391 #ifdef DO_SSL
392         else if ( (ser->ssl = SSL_new(ser->parent->tls_cfg->ssl_ctx)) ) {
393                 SSL_set_fd(ser->ssl, ser->fd);
394                 if ((ret = ssl_setup(ser->ssl)) <= 0) {
395                         ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
396                 } else {
397 #if defined(HAVE_FUNOPEN)       /* the BSD interface */
398                         ser->f = funopen(ser->ssl, ssl_read, ssl_write, NULL, ssl_close);
399
400 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
401                         static const cookie_io_functions_t cookie_funcs = {
402                                 ssl_read, ssl_write, NULL, ssl_close
403                         };
404                         ser->f = fopencookie(ser->ssl, "w+", cookie_funcs);
405 #else
406                         /* could add other methods here */
407                         ast_debug(2, "no ser->f methods attempted!");
408 #endif
409                         if ((ser->client && !ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
410                                 || (!ser->client && ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
411                                 X509 *peer;
412                                 long res;
413                                 peer = SSL_get_peer_certificate(ser->ssl);
414                                 if (!peer)
415                                         ast_log(LOG_WARNING, "No peer SSL certificate\n");
416                                 res = SSL_get_verify_result(ser->ssl);
417                                 if (res != X509_V_OK)
418                                         ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
419                                 if (!ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
420                                         ASN1_STRING *str;
421                                         unsigned char *str2;
422                                         X509_NAME *name = X509_get_subject_name(peer);
423                                         int pos = -1;
424                                         int found = 0;
425                                 
426                                         for (;;) {
427                                                 /* Walk the certificate to check all available "Common Name" */
428                                                 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
429                                                 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
430                                                 if (pos < 0)
431                                                         break;
432                                                 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
433                                                 ASN1_STRING_to_UTF8(&str2, str);
434                                                 if (str2) {
435                                                         if (!strcasecmp(ser->parent->hostname, (char *) str2))
436                                                                 found = 1;
437                                                         ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", ser->parent->hostname, str2);
438                                                         OPENSSL_free(str2);
439                                                 }
440                                                 if (found)
441                                                         break;
442                                         }
443                                         if (!found) {
444                                                 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", ser->parent->hostname);
445                                                 if (peer)
446                                                         X509_free(peer);
447                                                 fclose(ser->f);
448                                                 return NULL;
449                                         }
450                                 }
451                                 if (peer)
452                                         X509_free(peer);
453                         }
454                 }
455                 if (!ser->f)    /* no success opening descriptor stacking */
456                         SSL_free(ser->ssl);
457    }
458 #endif /* DO_SSL */
459
460         if (!ser->f) {
461                 close(ser->fd);
462                 ast_log(LOG_WARNING, "FILE * open failed!\n");
463                 ast_free(ser);
464                 return NULL;
465         }
466
467         if (ser && ser->parent->worker_fn)
468                 return ser->parent->worker_fn(ser);
469         else
470                 return ser;
471 }
472