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