declare optional openssl dependencies in moduleinfo
[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, flags;
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                 flags = fcntl(fd, F_GETFL);
265                 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
266
267                 tcptls_session->stream = ast_iostream_from_fd(&fd);
268                 if (!tcptls_session->stream) {
269                         ao2_ref(tcptls_session, -1);
270                         close(fd);
271                         continue;
272                 }
273
274                 tcptls_session->parent = desc;
275                 ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
276
277                 tcptls_session->client = 0;
278
279                 /* This thread is now the only place that controls the single ref to tcptls_session */
280                 if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
281                         ast_log(LOG_ERROR, "TCP/TLS unable to launch helper thread: %s\n",
282                                 strerror(errno));
283                         ao2_ref(tcptls_session, -1);
284                 }
285         }
286
287         ast_log(LOG_ERROR, "TCP/TLS listener thread ended abnormally\n");
288
289         /* Close the listener socket so Asterisk doesn't appear dead. */
290         fd = desc->accept_fd;
291         desc->accept_fd = -1;
292         if (0 <= fd) {
293                 close(fd);
294         }
295         return NULL;
296 }
297
298 #ifdef DO_SSL
299 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)
300 {
301         char *cert_file = ast_strdupa(cfg->certfile);
302
303         memcpy(cert_file + cert_file_len - 8, key_type_extension, 5);
304         if (access(cert_file, F_OK) == 0) {
305                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cert_file) == 0) {
306                         ast_log(LOG_WARNING, "TLS/SSL error loading public %s key (certificate) from <%s>.\n", key_type, cert_file);
307                 } else if (SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, cert_file, SSL_FILETYPE_PEM) == 0) {
308                         ast_log(LOG_WARNING, "TLS/SSL error loading private %s key from <%s>.\n", key_type, cert_file);
309                 } else if (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0) {
310                         ast_log(LOG_WARNING, "TLS/SSL error matching private %s key and certificate in <%s>.\n", key_type, cert_file);
311                 }
312         }
313 }
314 #endif
315
316 static int __ssl_setup(struct ast_tls_config *cfg, int client)
317 {
318 #ifndef DO_SSL
319         cfg->enabled = 0;
320         return 0;
321 #else
322         int disable_ssl = 0;
323         long ssl_opts = 0;
324
325         if (!cfg->enabled) {
326                 return 0;
327         }
328
329         /* Get rid of an old SSL_CTX since we're about to
330          * allocate a new one
331          */
332         if (cfg->ssl_ctx) {
333                 SSL_CTX_free(cfg->ssl_ctx);
334                 cfg->ssl_ctx = NULL;
335         }
336
337         if (client) {
338 #if !defined(OPENSSL_NO_SSL2) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
339                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
340                         ast_log(LOG_WARNING, "Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
341                         cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
342                 } else
343 #endif
344 #ifndef OPENSSL_NO_SSL3_METHOD
345                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
346                         ast_log(LOG_WARNING, "Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
347                         cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
348                 } else
349 #endif
350 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER  >= 0x10100000L)
351                 cfg->ssl_ctx = SSL_CTX_new(TLS_client_method());
352 #else
353                 if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
354                         cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
355                 } else {
356                         disable_ssl = 1;
357                         cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
358                 }
359 #endif
360         } else {
361                 disable_ssl = 1;
362                 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
363         }
364
365         if (!cfg->ssl_ctx) {
366                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
367                 cfg->enabled = 0;
368                 return 0;
369         }
370
371         /* Due to the POODLE vulnerability, completely disable
372          * SSLv2 and SSLv3 if we are not explicitly told to use
373          * them. SSLv23_*_method supports TLSv1+.
374          */
375         if (disable_ssl) {
376                 ssl_opts |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
377         }
378
379         if (ast_test_flag(&cfg->flags, AST_SSL_SERVER_CIPHER_ORDER)) {
380                 ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
381         }
382
383         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV1)) {
384                 ssl_opts |= SSL_OP_NO_TLSv1;
385         }
386 #if defined(HAVE_SSL_OP_NO_TLSV1_1) && defined(HAVE_SSL_OP_NO_TLSV1_2)
387         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV11)) {
388                 ssl_opts |= SSL_OP_NO_TLSv1_1;
389         }
390         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV12)) {
391                 ssl_opts |= SSL_OP_NO_TLSv1_2;
392         }
393 #else
394         ast_log(LOG_WARNING, "Your version of OpenSSL leaves you potentially vulnerable "
395                         "to the SSL BEAST attack. Please upgrade to OpenSSL 1.0.1 or later\n");
396 #endif
397
398         SSL_CTX_set_options(cfg->ssl_ctx, ssl_opts);
399
400         SSL_CTX_set_verify(cfg->ssl_ctx,
401                 ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
402                 NULL);
403
404         if (!ast_strlen_zero(cfg->certfile)) {
405                 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
406                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
407                         if (!client) {
408                                 /* Clients don't need a certificate, but if its setup we can use it */
409                                 ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
410                                 cfg->enabled = 0;
411                                 SSL_CTX_free(cfg->ssl_ctx);
412                                 cfg->ssl_ctx = NULL;
413                                 return 0;
414                         }
415                 }
416                 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
417                         if (!client) {
418                                 /* Clients don't need a private key, but if its setup we can use it */
419                                 ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
420                                 cfg->enabled = 0;
421                                 SSL_CTX_free(cfg->ssl_ctx);
422                                 cfg->ssl_ctx = NULL;
423                                 return 0;
424                         }
425                 }
426                 if (!client) {
427                         size_t certfile_len = strlen(cfg->certfile);
428
429                         /* expects a file name which contains _rsa. like asterisk_rsa.pem
430                          * ignores any 3-character file-extension like .pem, .cer, .crt
431                          */
432                         if (certfile_len >= 8 && !strncmp(cfg->certfile + certfile_len - 8, "_rsa.", 5)) {
433                                 __ssl_setup_certs(cfg, certfile_len, "_ecc.", "ECC");
434                                 __ssl_setup_certs(cfg, certfile_len, "_dsa.", "DSA");
435                         }
436                 }
437         }
438         if (!ast_strlen_zero(cfg->cipher)) {
439                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
440                         if (!client) {
441                                 ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
442                                 cfg->enabled = 0;
443                                 SSL_CTX_free(cfg->ssl_ctx);
444                                 cfg->ssl_ctx = NULL;
445                                 return 0;
446                         }
447                 }
448         }
449         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
450                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
451                         ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
452                 }
453         }
454
455 #ifdef HAVE_OPENSSL_EC
456
457         if (!ast_strlen_zero(cfg->pvtfile)) {
458                 BIO *bio = BIO_new_file(cfg->pvtfile, "r");
459                 if (bio != NULL) {
460                         DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
461                         if (dh != NULL) {
462                                 if (SSL_CTX_set_tmp_dh(cfg->ssl_ctx, dh)) {
463                                         long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
464                                         options = SSL_CTX_set_options(cfg->ssl_ctx, options);
465                                         ast_verb(2, "TLS/SSL DH initialized, PFS cipher-suites enabled\n");
466                                 }
467                                 DH_free(dh);
468                         }
469                         BIO_free(bio);
470                 }
471         }
472         #ifndef SSL_CTRL_SET_ECDH_AUTO
473                 #define SSL_CTRL_SET_ECDH_AUTO 94
474         #endif
475         /* SSL_CTX_set_ecdh_auto(cfg->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
476         if (SSL_CTX_ctrl(cfg->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
477                 ast_verb(2, "TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
478         } else {
479                 /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
480                 EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
481                 if (ecdh != NULL) {
482                         if (SSL_CTX_set_tmp_ecdh(cfg->ssl_ctx, ecdh)) {
483                                 ast_verb(2, "TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
484                         }
485                         EC_KEY_free(ecdh);
486                 }
487         }
488
489 #endif /* #ifdef HAVE_OPENSSL_EC */
490
491         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 */
492         return 1;
493 #endif
494 }
495
496 int ast_ssl_setup(struct ast_tls_config *cfg)
497 {
498         return __ssl_setup(cfg, 0);
499 }
500
501 void ast_ssl_teardown(struct ast_tls_config *cfg)
502 {
503 #ifdef DO_SSL
504         if (cfg->ssl_ctx) {
505                 SSL_CTX_free(cfg->ssl_ctx);
506                 cfg->ssl_ctx = NULL;
507         }
508 #endif
509 }
510
511 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
512 {
513         struct ast_tcptls_session_args *desc;
514         int flags;
515
516         if (!(desc = tcptls_session->parent)) {
517                 goto client_start_error;
518         }
519
520         if (ast_connect(desc->accept_fd, &desc->remote_address)) {
521                 ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
522                         desc->name,
523                         ast_sockaddr_stringify(&desc->remote_address),
524                         strerror(errno));
525                 goto client_start_error;
526         }
527
528         flags = fcntl(desc->accept_fd, F_GETFL);
529         fcntl(desc->accept_fd, F_SETFL, flags & ~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                 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
578                 if (ast_bind(desc->accept_fd, &desc->local_address)) {
579                         ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
580                                 desc->name,
581                                 ast_sockaddr_stringify(&desc->local_address),
582                                 strerror(errno));
583                         goto error;
584                 }
585         }
586
587         tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
588         if (!tcptls_session) {
589                 goto error;
590         }
591
592         tcptls_session->overflow_buf = ast_str_create(128);
593         if (!tcptls_session->overflow_buf) {
594                 goto error;
595         }
596         tcptls_session->client = 1;
597         tcptls_session->stream = ast_iostream_from_fd(&fd);
598         if (!tcptls_session->stream) {
599                 goto error;
600         }
601
602         tcptls_session->parent = desc;
603         tcptls_session->parent->worker_fn = NULL;
604         ast_sockaddr_copy(&tcptls_session->remote_address,
605                           &desc->remote_address);
606
607         /* Set current info */
608         ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
609         return tcptls_session;
610
611 error:
612         close(desc->accept_fd);
613         desc->accept_fd = -1;
614         ao2_cleanup(tcptls_session);
615         return NULL;
616 }
617
618 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
619 {
620         int flags;
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         flags = fcntl(desc->accept_fd, F_GETFL);
740         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
741         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
742                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
743                         desc->name,
744                         ast_sockaddr_stringify(&desc->local_address),
745                         strerror(errno));
746                 goto error;
747         }
748
749         /* Set current info */
750         ast_sockaddr_copy(&desc->old_address, &desc->local_address);
751         if (desc->old_tls_cfg) {
752                 ast_free(desc->old_tls_cfg->certfile);
753                 ast_free(desc->old_tls_cfg->pvtfile);
754                 ast_free(desc->old_tls_cfg->cipher);
755                 ast_free(desc->old_tls_cfg->cafile);
756                 ast_free(desc->old_tls_cfg->capath);
757                 desc->old_tls_cfg->certfile = ast_strdup(desc->tls_cfg->certfile);
758                 desc->old_tls_cfg->pvtfile = ast_strdup(desc->tls_cfg->pvtfile);
759                 desc->old_tls_cfg->cipher = ast_strdup(desc->tls_cfg->cipher);
760                 desc->old_tls_cfg->cafile = ast_strdup(desc->tls_cfg->cafile);
761                 desc->old_tls_cfg->capath = ast_strdup(desc->tls_cfg->capath);
762                 memcpy(desc->old_tls_cfg->certhash, desc->tls_cfg->certhash, 41);
763                 memcpy(desc->old_tls_cfg->pvthash, desc->tls_cfg->pvthash, 41);
764                 memcpy(desc->old_tls_cfg->cahash, desc->tls_cfg->cahash, 41);
765                 memcpy(&desc->old_tls_cfg->flags, &desc->tls_cfg->flags, sizeof(desc->old_tls_cfg->flags));
766         }
767
768         return;
769
770 error:
771         close(desc->accept_fd);
772         desc->accept_fd = -1;
773 }
774
775 void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
776 {
777         if (tcptls_session->stream) {
778                 ast_iostream_close(tcptls_session->stream);
779                 tcptls_session->stream = NULL;
780         } else {
781                 ast_debug(1, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
782         }
783 }
784
785 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
786 {
787         if (desc->master != AST_PTHREADT_NULL) {
788                 pthread_cancel(desc->master);
789                 pthread_kill(desc->master, SIGURG);
790                 pthread_join(desc->master, NULL);
791                 desc->master = AST_PTHREADT_NULL;
792         }
793         if (desc->accept_fd != -1) {
794                 close(desc->accept_fd);
795         }
796         desc->accept_fd = -1;
797
798         if (desc->old_tls_cfg) {
799                 ast_free(desc->old_tls_cfg->certfile);
800                 ast_free(desc->old_tls_cfg->pvtfile);
801                 ast_free(desc->old_tls_cfg->cipher);
802                 ast_free(desc->old_tls_cfg->cafile);
803                 ast_free(desc->old_tls_cfg->capath);
804                 ast_free(desc->old_tls_cfg);
805                 desc->old_tls_cfg = NULL;
806         }
807
808         ast_debug(2, "Stopped server :: %s\n", desc->name);
809 }
810
811 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
812 {
813         if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
814                 tls_cfg->enabled = ast_true(value) ? 1 : 0;
815         } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
816                 ast_free(tls_cfg->certfile);
817                 tls_cfg->certfile = ast_strdup(value);
818         } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
819                 ast_free(tls_cfg->pvtfile);
820                 tls_cfg->pvtfile = ast_strdup(value);
821         } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
822                 ast_free(tls_cfg->cipher);
823                 tls_cfg->cipher = ast_strdup(value);
824         } else if (!strcasecmp(varname, "tlscafile")) {
825                 ast_free(tls_cfg->cafile);
826                 tls_cfg->cafile = ast_strdup(value);
827         } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
828                 ast_free(tls_cfg->capath);
829                 tls_cfg->capath = ast_strdup(value);
830         } else if (!strcasecmp(varname, "tlsverifyclient")) {
831                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
832         } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
833                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
834         } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
835                 if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
836                         ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
837         } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
838                 if (!strcasecmp(value, "tlsv1")) {
839                         ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
840                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
841                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
842                 } else if (!strcasecmp(value, "sslv3")) {
843                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
844                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
845                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
846                 } else if (!strcasecmp(value, "sslv2")) {
847                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
848                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
849                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
850                 }
851         } else if (!strcasecmp(varname, "tlsservercipherorder")) {
852                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_SERVER_CIPHER_ORDER);
853         } else if (!strcasecmp(varname, "tlsdisablev1")) {
854                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV1);
855         } else if (!strcasecmp(varname, "tlsdisablev11")) {
856                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV11);
857         } else if (!strcasecmp(varname, "tlsdisablev12")) {
858                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV12);
859         } else {
860                 return -1;
861         }
862
863         return 0;
864 }