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