tcptls.c: Cleanup TCP/TLS listener thread on abnormal exit.
[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 /*** MODULEINFO
29         <support_level>core</support_level>
30  ***/
31
32 #include "asterisk.h"
33
34 #ifdef HAVE_FCNTL_H
35 #include <fcntl.h>
36 #endif
37
38 #include <signal.h>
39 #include <sys/stat.h>
40
41 #include "asterisk/compat.h"
42 #include "asterisk/tcptls.h"
43 #include "asterisk/http.h"
44 #include "asterisk/utils.h"
45 #include "asterisk/strings.h"
46 #include "asterisk/options.h"
47 #include "asterisk/manager.h"
48 #include "asterisk/astobj2.h"
49 #include "asterisk/pbx.h"
50 #include "asterisk/app.h"
51
52 static void session_instance_destructor(void *obj)
53 {
54         struct ast_tcptls_session_instance *i = obj;
55
56         if (i->stream) {
57                 ast_iostream_close(i->stream);
58                 i->stream = NULL;
59         }
60         ast_free(i->overflow_buf);
61         ao2_cleanup(i->private_data);
62 }
63
64 #ifdef DO_SSL
65 static int check_tcptls_cert_name(ASN1_STRING *cert_str, const char *hostname, const char *desc)
66 {
67         unsigned char *str;
68         int ret;
69
70         ret = ASN1_STRING_to_UTF8(&str, cert_str);
71         if (ret < 0 || !str) {
72                 return -1;
73         }
74
75         if (strlen((char *) str) != ret) {
76                 ast_log(LOG_WARNING, "Invalid certificate %s length (contains NULL bytes?)\n", desc);
77
78                 ret = -1;
79         } else if (!strcasecmp(hostname, (char *) str)) {
80                 ret = 0;
81         } else {
82                 ret = -1;
83         }
84
85         ast_debug(3, "SSL %s compare s1='%s' s2='%s'\n", desc, hostname, str);
86         OPENSSL_free(str);
87
88         return ret;
89 }
90 #endif
91
92 /*! \brief
93 * creates a FILE * from the fd passed by the accept thread.
94 * This operation is potentially expensive (certificate verification),
95 * so we do it in the child thread context.
96 *
97 * \note must decrement ref count before returning NULL on error
98 */
99 static void *handle_tcptls_connection(void *data)
100 {
101         struct ast_tcptls_session_instance *tcptls_session = data;
102 #ifdef DO_SSL
103         SSL *ssl;
104 #endif
105
106         /* TCP/TLS connections are associated with external protocols, and
107          * should not be allowed to execute 'dangerous' functions. This may
108          * need to be pushed down into the individual protocol handlers, but
109          * this seems like a good general policy.
110          */
111         if (ast_thread_inhibit_escalations()) {
112                 ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
113                 ast_tcptls_close_session_file(tcptls_session);
114                 ao2_ref(tcptls_session, -1);
115                 return NULL;
116         }
117
118         if (tcptls_session->parent->tls_cfg) {
119 #ifdef DO_SSL
120                 if (ast_iostream_start_tls(&tcptls_session->stream, tcptls_session->parent->tls_cfg->ssl_ctx, tcptls_session->client) < 0) {
121                         ast_tcptls_close_session_file(tcptls_session);
122                         ao2_ref(tcptls_session, -1);
123                         return NULL;
124                 }
125
126                 ssl = ast_iostream_get_ssl(tcptls_session->stream);
127                 if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
128                         || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
129                         X509 *peer;
130                         long res;
131                         peer = SSL_get_peer_certificate(ssl);
132                         if (!peer) {
133                                 ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
134                                 ast_tcptls_close_session_file(tcptls_session);
135                                 ao2_ref(tcptls_session, -1);
136                                 return NULL;
137                         }
138
139                         res = SSL_get_verify_result(ssl);
140                         if (res != X509_V_OK) {
141                                 ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
142                                 X509_free(peer);
143                                 ast_tcptls_close_session_file(tcptls_session);
144                                 ao2_ref(tcptls_session, -1);
145                                 return NULL;
146                         }
147                         if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
148                                 ASN1_STRING *str;
149                                 X509_NAME *name = X509_get_subject_name(peer);
150                                 STACK_OF(GENERAL_NAME) *alt_names;
151                                 int pos = -1;
152                                 int found = 0;
153
154                                 for (;;) {
155                                         /* Walk the certificate to check all available "Common Name" */
156                                         /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
157                                         pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
158                                         if (pos < 0) {
159                                                 break;
160                                         }
161                                         str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
162                                         if (!check_tcptls_cert_name(str, tcptls_session->parent->hostname, "common name")) {
163                                                 found = 1;
164                                                 break;
165                                         }
166                                 }
167
168                                 if (!found) {
169                                         alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, NULL, NULL);
170                                         if (alt_names != NULL) {
171                                                 int alt_names_count = sk_GENERAL_NAME_num(alt_names);
172
173                                                 for (pos = 0; pos < alt_names_count; pos++) {
174                                                         const GENERAL_NAME *alt_name = sk_GENERAL_NAME_value(alt_names, pos);
175
176                                                         if (alt_name->type != GEN_DNS) {
177                                                                 continue;
178                                                         }
179
180                                                         if (!check_tcptls_cert_name(alt_name->d.dNSName, tcptls_session->parent->hostname, "alt name")) {
181                                                                 found = 1;
182                                                                 break;
183                                                         }
184                                                 }
185
186                                                 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
187                                         }
188                                 }
189
190                                 if (!found) {
191                                         ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
192                                         X509_free(peer);
193                                         ast_tcptls_close_session_file(tcptls_session);
194                                         ao2_ref(tcptls_session, -1);
195                                         return NULL;
196                                 }
197                         }
198                         X509_free(peer);
199                 }
200 #else
201                 ast_log(LOG_ERROR, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
202                 ast_tcptls_close_session_file(tcptls_session);
203                 ao2_ref(tcptls_session, -1);
204                 return NULL;
205 #endif /* DO_SSL */
206         }
207
208         if (tcptls_session->parent->worker_fn) {
209                 return tcptls_session->parent->worker_fn(tcptls_session);
210         } else {
211                 return tcptls_session;
212         }
213 }
214
215 void *ast_tcptls_server_root(void *data)
216 {
217         struct ast_tcptls_session_args *desc = data;
218         int fd;
219         struct ast_sockaddr addr;
220         struct ast_tcptls_session_instance *tcptls_session;
221         pthread_t launched;
222
223         for (;;) {
224                 int i, flags;
225
226                 if (desc->periodic_fn) {
227                         desc->periodic_fn(desc);
228                 }
229                 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
230                 if (i <= 0) {
231                         /* Prevent tight loop from hogging CPU */
232                         usleep(1);
233                         continue;
234                 }
235                 fd = ast_accept(desc->accept_fd, &addr);
236                 if (fd < 0) {
237                         if (errno != EAGAIN
238                                 && errno != EWOULDBLOCK
239                                 && errno != EINTR
240                                 && errno != ECONNABORTED) {
241                                 ast_log(LOG_ERROR, "TCP/TLS accept failed: %s\n", strerror(errno));
242                                 if (errno != EMFILE) {
243                                         break;
244                                 }
245                         }
246                         /* Prevent tight loop from hogging CPU */
247                         usleep(1);
248                         continue;
249                 }
250                 tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
251                 if (!tcptls_session) {
252                         close(fd);
253                         continue;
254                 }
255
256                 tcptls_session->overflow_buf = ast_str_create(128);
257                 if (!tcptls_session->overflow_buf) {
258                         ao2_ref(tcptls_session, -1);
259                         close(fd);
260                         continue;
261                 }
262                 flags = fcntl(fd, F_GETFL);
263                 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
264
265                 tcptls_session->stream = ast_iostream_from_fd(&fd);
266                 if (!tcptls_session->stream) {
267                         ao2_ref(tcptls_session, -1);
268                         close(fd);
269                         continue;
270                 }
271
272                 tcptls_session->parent = desc;
273                 ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
274
275                 tcptls_session->client = 0;
276
277                 /* This thread is now the only place that controls the single ref to tcptls_session */
278                 if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
279                         ast_log(LOG_ERROR, "TCP/TLS unable to launch helper thread: %s\n",
280                                 strerror(errno));
281                         ao2_ref(tcptls_session, -1);
282                 }
283         }
284
285         ast_log(LOG_ERROR, "TCP/TLS listener thread ended abnormally\n");
286
287         /* Close the listener socket so Asterisk doesn't appear dead. */
288         fd = desc->accept_fd;
289         desc->accept_fd = -1;
290         if (0 <= fd) {
291                 close(fd);
292         }
293         return NULL;
294 }
295
296 #ifdef DO_SSL
297 static void __ssl_setup_certs(struct ast_tls_config *cfg, const size_t cert_file_len, const char *key_type_extension, const char *key_type)
298 {
299         char *cert_file = ast_strdupa(cfg->certfile);
300
301         memcpy(cert_file + cert_file_len - 8, key_type_extension, 5);
302         if (access(cert_file, F_OK) == 0) {
303                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cert_file) == 0) {
304                         ast_log(LOG_WARNING, "TLS/SSL error loading public %s key (certificate) from <%s>.\n", key_type, cert_file);
305                 } else if (SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, cert_file, SSL_FILETYPE_PEM) == 0) {
306                         ast_log(LOG_WARNING, "TLS/SSL error loading private %s key from <%s>.\n", key_type, cert_file);
307                 } else if (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0) {
308                         ast_log(LOG_WARNING, "TLS/SSL error matching private %s key and certificate in <%s>.\n", key_type, cert_file);
309                 }
310         }
311 }
312 #endif
313
314 static int __ssl_setup(struct ast_tls_config *cfg, int client)
315 {
316 #ifndef DO_SSL
317         cfg->enabled = 0;
318         return 0;
319 #else
320         int disable_ssl = 0;
321         long ssl_opts = 0;
322
323         if (!cfg->enabled) {
324                 return 0;
325         }
326
327         /* Get rid of an old SSL_CTX since we're about to
328          * allocate a new one
329          */
330         if (cfg->ssl_ctx) {
331                 SSL_CTX_free(cfg->ssl_ctx);
332                 cfg->ssl_ctx = NULL;
333         }
334
335         if (client) {
336 #if !defined(OPENSSL_NO_SSL2) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
337                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
338                         ast_log(LOG_WARNING, "Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
339                         cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
340                 } else
341 #endif
342 #ifndef OPENSSL_NO_SSL3_METHOD
343                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
344                         ast_log(LOG_WARNING, "Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
345                         cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
346                 } else
347 #endif
348 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER  >= 0x10100000L)
349                 cfg->ssl_ctx = SSL_CTX_new(TLS_client_method());
350 #else
351                 if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
352                         cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
353                 } else {
354                         disable_ssl = 1;
355                         cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
356                 }
357 #endif
358         } else {
359                 disable_ssl = 1;
360                 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
361         }
362
363         if (!cfg->ssl_ctx) {
364                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
365                 cfg->enabled = 0;
366                 return 0;
367         }
368
369         /* Due to the POODLE vulnerability, completely disable
370          * SSLv2 and SSLv3 if we are not explicitly told to use
371          * them. SSLv23_*_method supports TLSv1+.
372          */
373         if (disable_ssl) {
374                 ssl_opts |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
375         }
376
377         if (ast_test_flag(&cfg->flags, AST_SSL_SERVER_CIPHER_ORDER)) {
378                 ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
379         }
380
381         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV1)) {
382                 ssl_opts |= SSL_OP_NO_TLSv1;
383         }
384 #if defined(HAVE_SSL_OP_NO_TLSV1_1) && defined(HAVE_SSL_OP_NO_TLSV1_2)
385         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV11)) {
386                 ssl_opts |= SSL_OP_NO_TLSv1_1;
387         }
388         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV12)) {
389                 ssl_opts |= SSL_OP_NO_TLSv1_2;
390         }
391 #else
392         ast_log(LOG_WARNING, "Your version of OpenSSL leaves you potentially vulnerable "
393                         "to the SSL BEAST attack. Please upgrade to OpenSSL 1.0.1 or later\n");
394 #endif
395
396         SSL_CTX_set_options(cfg->ssl_ctx, ssl_opts);
397
398         SSL_CTX_set_verify(cfg->ssl_ctx,
399                 ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
400                 NULL);
401
402         if (!ast_strlen_zero(cfg->certfile)) {
403                 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
404                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
405                         if (!client) {
406                                 /* Clients don't need a certificate, but if its setup we can use it */
407                                 ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
408                                 cfg->enabled = 0;
409                                 SSL_CTX_free(cfg->ssl_ctx);
410                                 cfg->ssl_ctx = NULL;
411                                 return 0;
412                         }
413                 }
414                 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
415                         if (!client) {
416                                 /* Clients don't need a private key, but if its setup we can use it */
417                                 ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
418                                 cfg->enabled = 0;
419                                 SSL_CTX_free(cfg->ssl_ctx);
420                                 cfg->ssl_ctx = NULL;
421                                 return 0;
422                         }
423                 }
424                 if (!client) {
425                         size_t certfile_len = strlen(cfg->certfile);
426
427                         /* expects a file name which contains _rsa. like asterisk_rsa.pem
428                          * ignores any 3-character file-extension like .pem, .cer, .crt
429                          */
430                         if (certfile_len >= 8 && !strncmp(cfg->certfile + certfile_len - 8, "_rsa.", 5)) {
431                                 __ssl_setup_certs(cfg, certfile_len, "_ecc.", "ECC");
432                                 __ssl_setup_certs(cfg, certfile_len, "_dsa.", "DSA");
433                         }
434                 }
435         }
436         if (!ast_strlen_zero(cfg->cipher)) {
437                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
438                         if (!client) {
439                                 ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
440                                 cfg->enabled = 0;
441                                 SSL_CTX_free(cfg->ssl_ctx);
442                                 cfg->ssl_ctx = NULL;
443                                 return 0;
444                         }
445                 }
446         }
447         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
448                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
449                         ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
450                 }
451         }
452
453 #ifdef HAVE_OPENSSL_EC
454
455         if (!ast_strlen_zero(cfg->pvtfile)) {
456                 BIO *bio = BIO_new_file(cfg->pvtfile, "r");
457                 if (bio != NULL) {
458                         DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
459                         if (dh != NULL) {
460                                 if (SSL_CTX_set_tmp_dh(cfg->ssl_ctx, dh)) {
461                                         long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
462                                         options = SSL_CTX_set_options(cfg->ssl_ctx, options);
463                                         ast_verb(2, "TLS/SSL DH initialized, PFS cipher-suites enabled\n");
464                                 }
465                                 DH_free(dh);
466                         }
467                         BIO_free(bio);
468                 }
469         }
470         #ifndef SSL_CTRL_SET_ECDH_AUTO
471                 #define SSL_CTRL_SET_ECDH_AUTO 94
472         #endif
473         /* SSL_CTX_set_ecdh_auto(cfg->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
474         if (SSL_CTX_ctrl(cfg->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
475                 ast_verb(2, "TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
476         } else {
477                 /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
478                 EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
479                 if (ecdh != NULL) {
480                         if (SSL_CTX_set_tmp_ecdh(cfg->ssl_ctx, ecdh)) {
481                                 ast_verb(2, "TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
482                         }
483                         EC_KEY_free(ecdh);
484                 }
485         }
486
487 #endif /* #ifdef HAVE_OPENSSL_EC */
488
489         ast_verb(2, "TLS/SSL certificate ok\n");        /* We should log which one that is ok. This message doesn't really make sense in production use */
490         return 1;
491 #endif
492 }
493
494 int ast_ssl_setup(struct ast_tls_config *cfg)
495 {
496         return __ssl_setup(cfg, 0);
497 }
498
499 void ast_ssl_teardown(struct ast_tls_config *cfg)
500 {
501 #ifdef DO_SSL
502         if (cfg->ssl_ctx) {
503                 SSL_CTX_free(cfg->ssl_ctx);
504                 cfg->ssl_ctx = NULL;
505         }
506 #endif
507 }
508
509 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
510 {
511         struct ast_tcptls_session_args *desc;
512         int flags;
513
514         if (!(desc = tcptls_session->parent)) {
515                 goto client_start_error;
516         }
517
518         if (ast_connect(desc->accept_fd, &desc->remote_address)) {
519                 ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
520                         desc->name,
521                         ast_sockaddr_stringify(&desc->remote_address),
522                         strerror(errno));
523                 goto client_start_error;
524         }
525
526         flags = fcntl(desc->accept_fd, F_GETFL);
527         fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
528
529         if (desc->tls_cfg) {
530                 desc->tls_cfg->enabled = 1;
531                 __ssl_setup(desc->tls_cfg, 1);
532         }
533
534         return handle_tcptls_connection(tcptls_session);
535
536 client_start_error:
537         if (desc) {
538                 close(desc->accept_fd);
539                 desc->accept_fd = -1;
540         }
541         ao2_ref(tcptls_session, -1);
542         return NULL;
543
544 }
545
546 struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
547 {
548         int fd, x = 1;
549         struct ast_tcptls_session_instance *tcptls_session = NULL;
550
551         /* Do nothing if nothing has changed */
552         if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
553                 ast_debug(1, "Nothing changed in %s\n", desc->name);
554                 return NULL;
555         }
556
557         /* If we return early, there is no connection */
558         ast_sockaddr_setnull(&desc->old_address);
559
560         if (desc->accept_fd != -1) {
561                 close(desc->accept_fd);
562         }
563
564         fd = desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
565                                       AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
566         if (desc->accept_fd < 0) {
567                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
568                         desc->name, strerror(errno));
569                 return NULL;
570         }
571
572         /* if a local address was specified, bind to it so the connection will
573            originate from the desired address */
574         if (!ast_sockaddr_isnull(&desc->local_address)) {
575                 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
576                 if (ast_bind(desc->accept_fd, &desc->local_address)) {
577                         ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
578                                 desc->name,
579                                 ast_sockaddr_stringify(&desc->local_address),
580                                 strerror(errno));
581                         goto error;
582                 }
583         }
584
585         tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
586         if (!tcptls_session) {
587                 goto error;
588         }
589
590         tcptls_session->overflow_buf = ast_str_create(128);
591         if (!tcptls_session->overflow_buf) {
592                 goto error;
593         }
594         tcptls_session->client = 1;
595         tcptls_session->stream = ast_iostream_from_fd(&fd);
596         if (!tcptls_session->stream) {
597                 goto error;
598         }
599
600         tcptls_session->parent = desc;
601         tcptls_session->parent->worker_fn = NULL;
602         ast_sockaddr_copy(&tcptls_session->remote_address,
603                           &desc->remote_address);
604
605         /* Set current info */
606         ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
607         return tcptls_session;
608
609 error:
610         close(desc->accept_fd);
611         desc->accept_fd = -1;
612         ao2_cleanup(tcptls_session);
613         return NULL;
614 }
615
616 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
617 {
618         int flags;
619         int x = 1;
620         int tls_changed = 0;
621
622         if (desc->tls_cfg) {
623                 char hash[41];
624                 char *str = NULL;
625                 struct stat st;
626
627                 /* Store the hashes of the TLS certificate etc. */
628                 if (stat(desc->tls_cfg->certfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->certfile))) {
629                         memset(hash, 0, 41);
630                 } else {
631                         ast_sha1_hash(hash, str);
632                 }
633                 ast_free(str);
634                 str = NULL;
635                 memcpy(desc->tls_cfg->certhash, hash, 41);
636                 if (stat(desc->tls_cfg->pvtfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->pvtfile))) {
637                         memset(hash, 0, 41);
638                 } else {
639                         ast_sha1_hash(hash, str);
640                 }
641                 ast_free(str);
642                 str = NULL;
643                 memcpy(desc->tls_cfg->pvthash, hash, 41);
644                 if (stat(desc->tls_cfg->cafile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->cafile))) {
645                         memset(hash, 0, 41);
646                 } else {
647                         ast_sha1_hash(hash, str);
648                 }
649                 ast_free(str);
650                 str = NULL;
651                 memcpy(desc->tls_cfg->cahash, hash, 41);
652
653                 /* Check whether TLS configuration has changed */
654                 if (!desc->old_tls_cfg) { /* No previous configuration */
655                         tls_changed = 1;
656                         desc->old_tls_cfg = ast_calloc(1, sizeof(*desc->old_tls_cfg));
657                 } else if (memcmp(desc->tls_cfg->certhash, desc->old_tls_cfg->certhash, 41)) {
658                         tls_changed = 1;
659                 } else if (memcmp(desc->tls_cfg->pvthash, desc->old_tls_cfg->pvthash, 41)) {
660                         tls_changed = 1;
661                 } else if (strcmp(desc->tls_cfg->cipher, desc->old_tls_cfg->cipher)) {
662                         tls_changed = 1;
663                 } else if (memcmp(desc->tls_cfg->cahash, desc->old_tls_cfg->cahash, 41)) {
664                         tls_changed = 1;
665                 } else if (strcmp(desc->tls_cfg->capath, desc->old_tls_cfg->capath)) {
666                         tls_changed = 1;
667                 } else if (memcmp(&desc->tls_cfg->flags, &desc->old_tls_cfg->flags, sizeof(desc->tls_cfg->flags))) {
668                         tls_changed = 1;
669                 }
670
671                 if (tls_changed) {
672                         ast_debug(1, "Changed parameters for %s found\n", desc->name);
673                 }
674         }
675
676         /* Do nothing if nothing has changed */
677         if (!tls_changed && !ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
678                 ast_debug(1, "Nothing changed in %s\n", desc->name);
679                 return;
680         }
681
682         /* If we return early, there is no one listening */
683         ast_sockaddr_setnull(&desc->old_address);
684
685         /* Shutdown a running server if there is one */
686         if (desc->master != AST_PTHREADT_NULL) {
687                 pthread_cancel(desc->master);
688                 pthread_kill(desc->master, SIGURG);
689                 pthread_join(desc->master, NULL);
690         }
691
692         if (desc->accept_fd != -1) {
693                 close(desc->accept_fd);
694         }
695
696         /* If there's no new server, stop here */
697         if (ast_sockaddr_isnull(&desc->local_address)) {
698                 ast_debug(2, "Server disabled:  %s\n", desc->name);
699                 return;
700         }
701
702         desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
703                                  AF_INET6 : AF_INET, SOCK_STREAM, 0);
704         if (desc->accept_fd < 0) {
705                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
706                 return;
707         }
708
709         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
710         if (ast_bind(desc->accept_fd, &desc->local_address)) {
711                 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
712                         desc->name,
713                         ast_sockaddr_stringify(&desc->local_address),
714                         strerror(errno));
715                 goto error;
716         }
717         if (listen(desc->accept_fd, 10)) {
718                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
719                 goto error;
720         }
721         flags = fcntl(desc->accept_fd, F_GETFL);
722         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
723         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
724                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
725                         desc->name,
726                         ast_sockaddr_stringify(&desc->local_address),
727                         strerror(errno));
728                 goto error;
729         }
730
731         /* Set current info */
732         ast_sockaddr_copy(&desc->old_address, &desc->local_address);
733         if (desc->old_tls_cfg) {
734                 ast_free(desc->old_tls_cfg->certfile);
735                 ast_free(desc->old_tls_cfg->pvtfile);
736                 ast_free(desc->old_tls_cfg->cipher);
737                 ast_free(desc->old_tls_cfg->cafile);
738                 ast_free(desc->old_tls_cfg->capath);
739                 desc->old_tls_cfg->certfile = ast_strdup(desc->tls_cfg->certfile);
740                 desc->old_tls_cfg->pvtfile = ast_strdup(desc->tls_cfg->pvtfile);
741                 desc->old_tls_cfg->cipher = ast_strdup(desc->tls_cfg->cipher);
742                 desc->old_tls_cfg->cafile = ast_strdup(desc->tls_cfg->cafile);
743                 desc->old_tls_cfg->capath = ast_strdup(desc->tls_cfg->capath);
744                 memcpy(desc->old_tls_cfg->certhash, desc->tls_cfg->certhash, 41);
745                 memcpy(desc->old_tls_cfg->pvthash, desc->tls_cfg->pvthash, 41);
746                 memcpy(desc->old_tls_cfg->cahash, desc->tls_cfg->cahash, 41);
747                 memcpy(&desc->old_tls_cfg->flags, &desc->tls_cfg->flags, sizeof(desc->old_tls_cfg->flags));
748         }
749
750         return;
751
752 error:
753         close(desc->accept_fd);
754         desc->accept_fd = -1;
755 }
756
757 void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
758 {
759         if (tcptls_session->stream) {
760                 ast_iostream_close(tcptls_session->stream);
761                 tcptls_session->stream = NULL;
762         } else {
763                 ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
764         }
765 }
766
767 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
768 {
769         if (desc->master != AST_PTHREADT_NULL) {
770                 pthread_cancel(desc->master);
771                 pthread_kill(desc->master, SIGURG);
772                 pthread_join(desc->master, NULL);
773                 desc->master = AST_PTHREADT_NULL;
774         }
775         if (desc->accept_fd != -1) {
776                 close(desc->accept_fd);
777         }
778         desc->accept_fd = -1;
779
780         if (desc->old_tls_cfg) {
781                 ast_free(desc->old_tls_cfg->certfile);
782                 ast_free(desc->old_tls_cfg->pvtfile);
783                 ast_free(desc->old_tls_cfg->cipher);
784                 ast_free(desc->old_tls_cfg->cafile);
785                 ast_free(desc->old_tls_cfg->capath);
786                 ast_free(desc->old_tls_cfg);
787                 desc->old_tls_cfg = NULL;
788         }
789
790         ast_debug(2, "Stopped server :: %s\n", desc->name);
791 }
792
793 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
794 {
795         if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
796                 tls_cfg->enabled = ast_true(value) ? 1 : 0;
797         } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
798                 ast_free(tls_cfg->certfile);
799                 tls_cfg->certfile = ast_strdup(value);
800         } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
801                 ast_free(tls_cfg->pvtfile);
802                 tls_cfg->pvtfile = ast_strdup(value);
803         } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
804                 ast_free(tls_cfg->cipher);
805                 tls_cfg->cipher = ast_strdup(value);
806         } else if (!strcasecmp(varname, "tlscafile")) {
807                 ast_free(tls_cfg->cafile);
808                 tls_cfg->cafile = ast_strdup(value);
809         } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
810                 ast_free(tls_cfg->capath);
811                 tls_cfg->capath = ast_strdup(value);
812         } else if (!strcasecmp(varname, "tlsverifyclient")) {
813                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
814         } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
815                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
816         } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
817                 if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
818                         ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
819         } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
820                 if (!strcasecmp(value, "tlsv1")) {
821                         ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
822                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
823                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
824                 } else if (!strcasecmp(value, "sslv3")) {
825                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
826                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
827                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
828                 } else if (!strcasecmp(value, "sslv2")) {
829                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
830                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
831                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
832                 }
833         } else if (!strcasecmp(varname, "tlsservercipherorder")) {
834                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_SERVER_CIPHER_ORDER);
835         } else if (!strcasecmp(varname, "tlsdisablev1")) {
836                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV1);
837         } else if (!strcasecmp(varname, "tlsdisablev11")) {
838                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV11);
839         } else if (!strcasecmp(varname, "tlsdisablev12")) {
840                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV12);
841         } else {
842                 return -1;
843         }
844
845         return 0;
846 }