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