SIP option to specify outbound TLS/SSL client protocol.
[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                 setvbuf(tcptls_session->f, NULL, _IONBF, 0);
141         }
142 #ifdef DO_SSL
143         else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
144                 SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
145                 if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
146                         ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
147                 } else {
148 #if defined(HAVE_FUNOPEN)       /* the BSD interface */
149                         tcptls_session->f = funopen(tcptls_session->ssl, ssl_read, ssl_write, NULL, ssl_close);
150
151 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
152                         static const cookie_io_functions_t cookie_funcs = {
153                                 ssl_read, ssl_write, NULL, ssl_close
154                         };
155                         tcptls_session->f = fopencookie(tcptls_session->ssl, "w+", cookie_funcs);
156 #else
157                         /* could add other methods here */
158                         ast_debug(2, "no tcptls_session->f methods attempted!");
159 #endif
160                         if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
161                                 || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
162                                 X509 *peer;
163                                 long res;
164                                 peer = SSL_get_peer_certificate(tcptls_session->ssl);
165                                 if (!peer)
166                                         ast_log(LOG_WARNING, "No peer SSL certificate\n");
167                                 res = SSL_get_verify_result(tcptls_session->ssl);
168                                 if (res != X509_V_OK)
169                                         ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
170                                 if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
171                                         ASN1_STRING *str;
172                                         unsigned char *str2;
173                                         X509_NAME *name = X509_get_subject_name(peer);
174                                         int pos = -1;
175                                         int found = 0;
176
177                                         for (;;) {
178                                                 /* Walk the certificate to check all available "Common Name" */
179                                                 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
180                                                 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
181                                                 if (pos < 0)
182                                                         break;
183                                                 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
184                                                 ASN1_STRING_to_UTF8(&str2, str);
185                                                 if (str2) {
186                                                         if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2))
187                                                                 found = 1;
188                                                         ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
189                                                         OPENSSL_free(str2);
190                                                 }
191                                                 if (found)
192                                                         break;
193                                         }
194                                         if (!found) {
195                                                 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
196                                                 if (peer)
197                                                         X509_free(peer);
198                                                 fclose(tcptls_session->f);
199                                                 return NULL;
200                                         }
201                                 }
202                                 if (peer)
203                                         X509_free(peer);
204                         }
205                 }
206                 if (!tcptls_session->f) /* no success opening descriptor stacking */
207                         SSL_free(tcptls_session->ssl);
208    }
209 #endif /* DO_SSL */
210
211         if (!tcptls_session->f) {
212                 close(tcptls_session->fd);
213                 ast_log(LOG_WARNING, "FILE * open failed!\n");
214                 ao2_ref(tcptls_session, -1);
215                 return NULL;
216         }
217
218         if (tcptls_session && tcptls_session->parent->worker_fn)
219                 return tcptls_session->parent->worker_fn(tcptls_session);
220         else
221                 return tcptls_session;
222 }
223
224 void *ast_tcptls_server_root(void *data)
225 {
226         struct ast_tcptls_session_args *desc = data;
227         int fd;
228         struct sockaddr_in sin;
229         socklen_t sinlen;
230         struct ast_tcptls_session_instance *tcptls_session;
231         pthread_t launched;
232
233         for (;;) {
234                 int i, flags;
235
236                 if (desc->periodic_fn)
237                         desc->periodic_fn(desc);
238                 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
239                 if (i <= 0)
240                         continue;
241                 sinlen = sizeof(sin);
242                 fd = accept(desc->accept_fd, (struct sockaddr *) &sin, &sinlen);
243                 if (fd < 0) {
244                         if ((errno != EAGAIN) && (errno != EINTR))
245                                 ast_log(LOG_WARNING, "Accept failed: %s\n", strerror(errno));
246                         continue;
247                 }
248                 tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
249                 if (!tcptls_session) {
250                         ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
251                         close(fd);
252                         continue;
253                 }
254
255                 ast_mutex_init(&tcptls_session->lock);
256
257                 flags = fcntl(fd, F_GETFL);
258                 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
259                 tcptls_session->fd = fd;
260                 tcptls_session->parent = desc;
261                 memcpy(&tcptls_session->remote_address, &sin, sizeof(tcptls_session->remote_address));
262
263                 tcptls_session->client = 0;
264
265                 if (ast_pthread_create_detached_background(&launched, NULL, handle_tls_connection, tcptls_session)) {
266                         ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
267                         close(tcptls_session->fd);
268                         ao2_ref(tcptls_session, -1);
269                 }
270         }
271         return NULL;
272 }
273
274 static int __ssl_setup(struct ast_tls_config *cfg, int client)
275 {
276 #ifndef DO_SSL
277         cfg->enabled = 0;
278         return 0;
279 #else
280         if (!cfg->enabled)
281                 return 0;
282
283         SSL_load_error_strings();
284         SSLeay_add_ssl_algorithms();
285
286         if (client) {
287                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
288                         cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
289                 } else if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
290                         cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
291                 } else if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
292                         cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
293                 } else {
294                         /* SSLv23_client_method() sends SSLv2, this was the original
295                          * default for ssl clients before the option was given to
296                          * pick what protocol a client should use.  In order not
297                          * to break expected behavior it remains the default. */
298                         cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
299                 }
300         } else {
301                 /* SSLv23_server_method() supports TLSv1, SSLv2, and SSLv3 inbound connections. */
302                 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
303         }
304
305         if (!cfg->ssl_ctx) {
306                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
307                 cfg->enabled = 0;
308                 return 0;
309         }
310         if (!ast_strlen_zero(cfg->certfile)) {
311                 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
312                 if (SSL_CTX_use_certificate_file(cfg->ssl_ctx, cfg->certfile, SSL_FILETYPE_PEM) == 0) {
313                         if (!client) {
314                                 /* Clients don't need a certificate, but if its setup we can use it */
315                                 ast_verb(0, "SSL error loading cert file. <%s>", cfg->certfile);
316                                 sleep(2);
317                                 cfg->enabled = 0;
318                                 return 0;
319                         }
320                 }
321                 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
322                         if (!client) {
323                                 /* Clients don't need a private key, but if its setup we can use it */
324                                 ast_verb(0, "SSL error loading private key file. <%s>", tmpprivate);
325                                 sleep(2);
326                                 cfg->enabled = 0;
327                                 return 0;
328                         }
329                 }
330         }
331         if (!ast_strlen_zero(cfg->cipher)) {
332                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
333                         if (!client) {
334                                 ast_verb(0, "SSL cipher error <%s>", cfg->cipher);
335                                 sleep(2);
336                                 cfg->enabled = 0;
337                                 return 0;
338                         }
339                 }
340         }
341         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
342                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0)
343                         ast_verb(0, "SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
344         }
345
346         ast_verb(0, "SSL certificate ok\n");
347         return 1;
348 #endif
349 }
350
351 int ast_ssl_setup(struct ast_tls_config *cfg)
352 {
353         return __ssl_setup(cfg, 0);
354 }
355
356 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_args *desc)
357 {
358         int flags;
359         int x = 1;
360         struct ast_tcptls_session_instance *tcptls_session = NULL;
361
362         /* Do nothing if nothing has changed */
363         if (!memcmp(&desc->old_address, &desc->remote_address, sizeof(desc->old_address))) {
364                 ast_debug(1, "Nothing changed in %s\n", desc->name);
365                 return NULL;
366         }
367
368         desc->old_address = desc->remote_address;
369
370         if (desc->accept_fd != -1)
371                 close(desc->accept_fd);
372
373         desc->accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
374         if (desc->accept_fd < 0) {
375                 ast_log(LOG_WARNING, "Unable to allocate socket for %s: %s\n",
376                         desc->name, strerror(errno));
377                 return NULL;
378         }
379
380         /* if a local address was specified, bind to it so the connection will
381            originate from the desired address */
382         if (desc->local_address.sin_family != 0) {
383                 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
384                 if (bind(desc->accept_fd, (struct sockaddr *) &desc->local_address, sizeof(desc->local_address))) {
385                         ast_log(LOG_ERROR, "Unable to bind %s to %s:%d: %s\n",
386                         desc->name,
387                                 ast_inet_ntoa(desc->local_address.sin_addr), ntohs(desc->local_address.sin_port),
388                                 strerror(errno));
389                         goto error;
390                 }
391         }
392
393         if (connect(desc->accept_fd, (const struct sockaddr *) &desc->remote_address, sizeof(desc->remote_address))) {
394                 ast_log(LOG_ERROR, "Unable to connect %s to %s:%d: %s\n",
395                         desc->name,
396                         ast_inet_ntoa(desc->remote_address.sin_addr), ntohs(desc->remote_address.sin_port),
397                         strerror(errno));
398                 goto error;
399         }
400
401         if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor)))
402                 goto error;
403
404         ast_mutex_init(&tcptls_session->lock);
405
406         flags = fcntl(desc->accept_fd, F_GETFL);
407         fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
408
409         tcptls_session->fd = desc->accept_fd;
410         tcptls_session->parent = desc;
411         tcptls_session->parent->worker_fn = NULL;
412         memcpy(&tcptls_session->remote_address, &desc->remote_address, sizeof(tcptls_session->remote_address));
413
414         tcptls_session->client = 1;
415
416         if (desc->tls_cfg) {
417                 desc->tls_cfg->enabled = 1;
418                 __ssl_setup(desc->tls_cfg, 1);
419         }
420
421         ao2_ref(tcptls_session, +1);
422         if (!handle_tls_connection(tcptls_session))
423                 goto error;
424
425         return tcptls_session;
426
427 error:
428         close(desc->accept_fd);
429         desc->accept_fd = -1;
430         if (tcptls_session)
431                 ao2_ref(tcptls_session, -1);
432         return NULL;
433 }
434
435 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
436 {
437         int flags;
438         int x = 1;
439
440         /* Do nothing if nothing has changed */
441         if (!memcmp(&desc->old_address, &desc->local_address, sizeof(desc->old_address))) {
442                 ast_debug(1, "Nothing changed in %s\n", desc->name);
443                 return;
444         }
445
446         desc->old_address = desc->local_address;
447
448         /* Shutdown a running server if there is one */
449         if (desc->master != AST_PTHREADT_NULL) {
450                 pthread_cancel(desc->master);
451                 pthread_kill(desc->master, SIGURG);
452                 pthread_join(desc->master, NULL);
453         }
454
455         if (desc->accept_fd != -1)
456                 close(desc->accept_fd);
457
458         /* If there's no new server, stop here */
459         if (desc->local_address.sin_family == 0) {
460                 ast_debug(2, "Server disabled:  %s\n", desc->name);
461                 return;
462         }
463
464         desc->accept_fd = socket(AF_INET, SOCK_STREAM, 0);
465         if (desc->accept_fd < 0) {
466                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
467                 return;
468         }
469
470         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
471         if (bind(desc->accept_fd, (struct sockaddr *) &desc->local_address, sizeof(desc->local_address))) {
472                 ast_log(LOG_ERROR, "Unable to bind %s to %s:%d: %s\n",
473                         desc->name,
474                         ast_inet_ntoa(desc->local_address.sin_addr), ntohs(desc->local_address.sin_port),
475                         strerror(errno));
476                 goto error;
477         }
478         if (listen(desc->accept_fd, 10)) {
479                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
480                 goto error;
481         }
482         flags = fcntl(desc->accept_fd, F_GETFL);
483         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
484         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
485                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s:%d: %s\n",
486                         desc->name,
487                         ast_inet_ntoa(desc->local_address.sin_addr), ntohs(desc->local_address.sin_port),
488                         strerror(errno));
489                 goto error;
490         }
491         return;
492
493 error:
494         close(desc->accept_fd);
495         desc->accept_fd = -1;
496 }
497
498 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
499 {
500         if (desc->master != AST_PTHREADT_NULL) {
501                 pthread_cancel(desc->master);
502                 pthread_kill(desc->master, SIGURG);
503                 pthread_join(desc->master, NULL);
504         }
505         if (desc->accept_fd != -1)
506                 close(desc->accept_fd);
507         desc->accept_fd = -1;
508         ast_debug(2, "Stopped server :: %s\n", desc->name);
509 }
510
511 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
512 {
513         if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
514                 tls_cfg->enabled = ast_true(value) ? 1 : 0;
515                 tls_desc->local_address.sin_family = AF_INET;
516         } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
517                 ast_free(tls_cfg->certfile);
518                 tls_cfg->certfile = ast_strdup(value);
519         } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
520                 ast_free(tls_cfg->pvtfile);
521                 tls_cfg->pvtfile = ast_strdup(value);
522         } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
523                 ast_free(tls_cfg->cipher);
524                 tls_cfg->cipher = ast_strdup(value);
525         } else if (!strcasecmp(varname, "tlscafile")) {
526                 ast_free(tls_cfg->cafile);
527                 tls_cfg->cafile = ast_strdup(value);
528         } else if (!strcasecmp(varname, "tlscapath")) {
529                 ast_free(tls_cfg->capath);
530                 tls_cfg->capath = ast_strdup(value);
531         } else if (!strcasecmp(varname, "tlsverifyclient")) {
532                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
533         } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
534                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
535         } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
536                 if (ast_parse_arg(value, PARSE_INADDR, &tls_desc->local_address))
537                         ast_log(LOG_WARNING, "Invalid %s '%s'\n", varname, value);
538         } else if (!strcasecmp(varname, "tlsbindport") || !strcasecmp(varname, "sslbindport")) {
539                 tls_desc->local_address.sin_port = htons(atoi(value));
540         } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
541                 if (!strcasecmp(value, "tlsv1")) {
542                         ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
543                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
544                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
545                 } else if (!strcasecmp(value, "sslv3")) {
546                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
547                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
548                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
549                 } else if (!strcasecmp(value, "sslv2")) {
550                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
551                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
552                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
553                 }
554         } else {
555                 return -1;
556         }
557
558         return 0;
559 }