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