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