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