tcptls: Print notice when TLS is enabled but not configured.
[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         if (cfg->enabled) {
320                 ast_log(LOG_NOTICE, "Configured without OpenSSL Development Headers");
321                 cfg->enabled = 0;
322         }
323         return 0;
324 #else
325         int disable_ssl = 0;
326         long ssl_opts = 0;
327
328         if (!cfg->enabled) {
329                 return 0;
330         }
331
332         /* Get rid of an old SSL_CTX since we're about to
333          * allocate a new one
334          */
335         if (cfg->ssl_ctx) {
336                 SSL_CTX_free(cfg->ssl_ctx);
337                 cfg->ssl_ctx = NULL;
338         }
339
340         if (client) {
341 #if !defined(OPENSSL_NO_SSL2) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
342                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
343                         ast_log(LOG_WARNING, "Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
344                         cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
345                 } else
346 #endif
347 #ifndef OPENSSL_NO_SSL3_METHOD
348                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
349                         ast_log(LOG_WARNING, "Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
350                         cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
351                 } else
352 #endif
353 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER  >= 0x10100000L)
354                 cfg->ssl_ctx = SSL_CTX_new(TLS_client_method());
355 #else
356                 if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
357                         cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
358                 } else {
359                         disable_ssl = 1;
360                         cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
361                 }
362 #endif
363         } else {
364                 disable_ssl = 1;
365                 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
366         }
367
368         if (!cfg->ssl_ctx) {
369                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
370                 cfg->enabled = 0;
371                 return 0;
372         }
373
374         /* Due to the POODLE vulnerability, completely disable
375          * SSLv2 and SSLv3 if we are not explicitly told to use
376          * them. SSLv23_*_method supports TLSv1+.
377          */
378         if (disable_ssl) {
379                 ssl_opts |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
380         }
381
382         if (ast_test_flag(&cfg->flags, AST_SSL_SERVER_CIPHER_ORDER)) {
383                 ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
384         }
385
386         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV1)) {
387                 ssl_opts |= SSL_OP_NO_TLSv1;
388         }
389 #if defined(HAVE_SSL_OP_NO_TLSV1_1) && defined(HAVE_SSL_OP_NO_TLSV1_2)
390         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV11)) {
391                 ssl_opts |= SSL_OP_NO_TLSv1_1;
392         }
393         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV12)) {
394                 ssl_opts |= SSL_OP_NO_TLSv1_2;
395         }
396 #else
397         ast_log(LOG_WARNING, "Your version of OpenSSL leaves you potentially vulnerable "
398                         "to the SSL BEAST attack. Please upgrade to OpenSSL 1.0.1 or later\n");
399 #endif
400
401         SSL_CTX_set_options(cfg->ssl_ctx, ssl_opts);
402
403         SSL_CTX_set_verify(cfg->ssl_ctx,
404                 ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
405                 NULL);
406
407         if (!ast_strlen_zero(cfg->certfile)) {
408                 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
409                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
410                         if (!client) {
411                                 /* Clients don't need a certificate, but if its setup we can use it */
412                                 ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
413                                 cfg->enabled = 0;
414                                 SSL_CTX_free(cfg->ssl_ctx);
415                                 cfg->ssl_ctx = NULL;
416                                 return 0;
417                         }
418                 }
419                 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
420                         if (!client) {
421                                 /* Clients don't need a private key, but if its setup we can use it */
422                                 ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
423                                 cfg->enabled = 0;
424                                 SSL_CTX_free(cfg->ssl_ctx);
425                                 cfg->ssl_ctx = NULL;
426                                 return 0;
427                         }
428                 }
429                 if (!client) {
430                         size_t certfile_len = strlen(cfg->certfile);
431
432                         /* expects a file name which contains _rsa. like asterisk_rsa.pem
433                          * ignores any 3-character file-extension like .pem, .cer, .crt
434                          */
435                         if (certfile_len >= 8 && !strncmp(cfg->certfile + certfile_len - 8, "_rsa.", 5)) {
436                                 __ssl_setup_certs(cfg, certfile_len, "_ecc.", "ECC");
437                                 __ssl_setup_certs(cfg, certfile_len, "_dsa.", "DSA");
438                         }
439                 }
440         }
441         if (!ast_strlen_zero(cfg->cipher)) {
442                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
443                         if (!client) {
444                                 ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
445                                 cfg->enabled = 0;
446                                 SSL_CTX_free(cfg->ssl_ctx);
447                                 cfg->ssl_ctx = NULL;
448                                 return 0;
449                         }
450                 }
451         }
452         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
453                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
454                         ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
455                 }
456         }
457
458 #ifdef HAVE_OPENSSL_EC
459
460         if (!ast_strlen_zero(cfg->pvtfile)) {
461                 BIO *bio = BIO_new_file(cfg->pvtfile, "r");
462                 if (bio != NULL) {
463                         DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
464                         if (dh != NULL) {
465                                 if (SSL_CTX_set_tmp_dh(cfg->ssl_ctx, dh)) {
466                                         long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
467                                         options = SSL_CTX_set_options(cfg->ssl_ctx, options);
468                                         ast_verb(2, "TLS/SSL DH initialized, PFS cipher-suites enabled\n");
469                                 }
470                                 DH_free(dh);
471                         }
472                         BIO_free(bio);
473                 }
474         }
475         #ifndef SSL_CTRL_SET_ECDH_AUTO
476                 #define SSL_CTRL_SET_ECDH_AUTO 94
477         #endif
478         /* SSL_CTX_set_ecdh_auto(cfg->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
479         if (SSL_CTX_ctrl(cfg->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
480                 ast_verb(2, "TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
481         } else {
482                 /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
483                 EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
484                 if (ecdh != NULL) {
485                         if (SSL_CTX_set_tmp_ecdh(cfg->ssl_ctx, ecdh)) {
486                                 ast_verb(2, "TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
487                         }
488                         EC_KEY_free(ecdh);
489                 }
490         }
491
492 #endif /* #ifdef HAVE_OPENSSL_EC */
493
494         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 */
495         return 1;
496 #endif
497 }
498
499 int ast_ssl_setup(struct ast_tls_config *cfg)
500 {
501         return __ssl_setup(cfg, 0);
502 }
503
504 void ast_ssl_teardown(struct ast_tls_config *cfg)
505 {
506 #ifdef DO_SSL
507         if (cfg && cfg->ssl_ctx) {
508                 SSL_CTX_free(cfg->ssl_ctx);
509                 cfg->ssl_ctx = NULL;
510         }
511 #endif
512 }
513
514 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
515 {
516         struct ast_tcptls_session_args *desc;
517         int flags;
518
519         if (!(desc = tcptls_session->parent)) {
520                 goto client_start_error;
521         }
522
523         if (ast_connect(desc->accept_fd, &desc->remote_address)) {
524                 ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
525                         desc->name,
526                         ast_sockaddr_stringify(&desc->remote_address),
527                         strerror(errno));
528                 goto client_start_error;
529         }
530
531         flags = fcntl(desc->accept_fd, F_GETFL);
532         fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
533
534         if (desc->tls_cfg) {
535                 desc->tls_cfg->enabled = 1;
536                 __ssl_setup(desc->tls_cfg, 1);
537         }
538
539         return handle_tcptls_connection(tcptls_session);
540
541 client_start_error:
542         if (desc) {
543                 close(desc->accept_fd);
544                 desc->accept_fd = -1;
545         }
546         ao2_ref(tcptls_session, -1);
547         return NULL;
548
549 }
550
551 struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
552 {
553         int fd, x = 1;
554         struct ast_tcptls_session_instance *tcptls_session = NULL;
555
556         /* Do nothing if nothing has changed */
557         if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
558                 ast_debug(1, "Nothing changed in %s\n", desc->name);
559                 return NULL;
560         }
561
562         /* If we return early, there is no connection */
563         ast_sockaddr_setnull(&desc->old_address);
564
565         if (desc->accept_fd != -1) {
566                 close(desc->accept_fd);
567         }
568
569         fd = desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
570                                       AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
571         if (desc->accept_fd < 0) {
572                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
573                         desc->name, strerror(errno));
574                 return NULL;
575         }
576
577         /* if a local address was specified, bind to it so the connection will
578            originate from the desired address */
579         if (!ast_sockaddr_isnull(&desc->local_address) &&
580             !ast_sockaddr_is_any(&desc->local_address)) {
581                 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
582                 if (ast_bind(desc->accept_fd, &desc->local_address)) {
583                         ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
584                                 desc->name,
585                                 ast_sockaddr_stringify(&desc->local_address),
586                                 strerror(errno));
587                         goto error;
588                 }
589         }
590
591         tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
592         if (!tcptls_session) {
593                 goto error;
594         }
595
596         tcptls_session->overflow_buf = ast_str_create(128);
597         if (!tcptls_session->overflow_buf) {
598                 goto error;
599         }
600         tcptls_session->client = 1;
601         tcptls_session->stream = ast_iostream_from_fd(&fd);
602         if (!tcptls_session->stream) {
603                 goto error;
604         }
605
606         tcptls_session->parent = desc;
607         tcptls_session->parent->worker_fn = NULL;
608         ast_sockaddr_copy(&tcptls_session->remote_address,
609                           &desc->remote_address);
610
611         /* Set current info */
612         ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
613         return tcptls_session;
614
615 error:
616         close(desc->accept_fd);
617         desc->accept_fd = -1;
618         ao2_cleanup(tcptls_session);
619         return NULL;
620 }
621
622 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
623 {
624         int flags;
625         int x = 1;
626         int tls_changed = 0;
627         int sd_socket;
628
629         if (desc->tls_cfg) {
630                 char hash[41];
631                 char *str = NULL;
632                 struct stat st;
633
634                 /* Store the hashes of the TLS certificate etc. */
635                 if (stat(desc->tls_cfg->certfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->certfile))) {
636                         memset(hash, 0, 41);
637                 } else {
638                         ast_sha1_hash(hash, str);
639                 }
640                 ast_free(str);
641                 str = NULL;
642                 memcpy(desc->tls_cfg->certhash, hash, 41);
643                 if (stat(desc->tls_cfg->pvtfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->pvtfile))) {
644                         memset(hash, 0, 41);
645                 } else {
646                         ast_sha1_hash(hash, str);
647                 }
648                 ast_free(str);
649                 str = NULL;
650                 memcpy(desc->tls_cfg->pvthash, hash, 41);
651                 if (stat(desc->tls_cfg->cafile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->cafile))) {
652                         memset(hash, 0, 41);
653                 } else {
654                         ast_sha1_hash(hash, str);
655                 }
656                 ast_free(str);
657                 str = NULL;
658                 memcpy(desc->tls_cfg->cahash, hash, 41);
659
660                 /* Check whether TLS configuration has changed */
661                 if (!desc->old_tls_cfg) { /* No previous configuration */
662                         tls_changed = 1;
663                         desc->old_tls_cfg = ast_calloc(1, sizeof(*desc->old_tls_cfg));
664                 } else if (memcmp(desc->tls_cfg->certhash, desc->old_tls_cfg->certhash, 41)) {
665                         tls_changed = 1;
666                 } else if (memcmp(desc->tls_cfg->pvthash, desc->old_tls_cfg->pvthash, 41)) {
667                         tls_changed = 1;
668                 } else if (strcmp(desc->tls_cfg->cipher, desc->old_tls_cfg->cipher)) {
669                         tls_changed = 1;
670                 } else if (memcmp(desc->tls_cfg->cahash, desc->old_tls_cfg->cahash, 41)) {
671                         tls_changed = 1;
672                 } else if (strcmp(desc->tls_cfg->capath, desc->old_tls_cfg->capath)) {
673                         tls_changed = 1;
674                 } else if (memcmp(&desc->tls_cfg->flags, &desc->old_tls_cfg->flags, sizeof(desc->tls_cfg->flags))) {
675                         tls_changed = 1;
676                 }
677
678                 if (tls_changed) {
679                         ast_debug(1, "Changed parameters for %s found\n", desc->name);
680                 }
681         }
682
683         /* Do nothing if nothing has changed */
684         if (!tls_changed && !ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
685                 ast_debug(1, "Nothing changed in %s\n", desc->name);
686                 return;
687         }
688
689         /* If we return early, there is no one listening */
690         ast_sockaddr_setnull(&desc->old_address);
691
692         /* Shutdown a running server if there is one */
693         if (desc->master != AST_PTHREADT_NULL) {
694                 pthread_cancel(desc->master);
695                 pthread_kill(desc->master, SIGURG);
696                 pthread_join(desc->master, NULL);
697         }
698
699         sd_socket = ast_sd_get_fd(SOCK_STREAM, &desc->local_address);
700
701         if (sd_socket != -1) {
702                 if (desc->accept_fd != sd_socket) {
703                         if (desc->accept_fd != -1) {
704                                 close(desc->accept_fd);
705                         }
706                         desc->accept_fd = sd_socket;
707                 }
708
709                 goto systemd_socket_activation;
710         }
711
712         if (desc->accept_fd != -1) {
713                 close(desc->accept_fd);
714         }
715
716         /* If there's no new server, stop here */
717         if (ast_sockaddr_isnull(&desc->local_address)) {
718                 ast_debug(2, "Server disabled:  %s\n", desc->name);
719                 return;
720         }
721
722         desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
723                                  AF_INET6 : AF_INET, SOCK_STREAM, 0);
724         if (desc->accept_fd < 0) {
725                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
726                 return;
727         }
728
729         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
730         if (ast_bind(desc->accept_fd, &desc->local_address)) {
731                 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
732                         desc->name,
733                         ast_sockaddr_stringify(&desc->local_address),
734                         strerror(errno));
735                 goto error;
736         }
737         if (listen(desc->accept_fd, 10)) {
738                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
739                 goto error;
740         }
741
742 systemd_socket_activation:
743         flags = fcntl(desc->accept_fd, F_GETFL);
744         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
745         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
746                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
747                         desc->name,
748                         ast_sockaddr_stringify(&desc->local_address),
749                         strerror(errno));
750                 goto error;
751         }
752
753         /* Set current info */
754         ast_sockaddr_copy(&desc->old_address, &desc->local_address);
755         if (desc->old_tls_cfg) {
756                 ast_free(desc->old_tls_cfg->certfile);
757                 ast_free(desc->old_tls_cfg->pvtfile);
758                 ast_free(desc->old_tls_cfg->cipher);
759                 ast_free(desc->old_tls_cfg->cafile);
760                 ast_free(desc->old_tls_cfg->capath);
761                 desc->old_tls_cfg->certfile = ast_strdup(desc->tls_cfg->certfile);
762                 desc->old_tls_cfg->pvtfile = ast_strdup(desc->tls_cfg->pvtfile);
763                 desc->old_tls_cfg->cipher = ast_strdup(desc->tls_cfg->cipher);
764                 desc->old_tls_cfg->cafile = ast_strdup(desc->tls_cfg->cafile);
765                 desc->old_tls_cfg->capath = ast_strdup(desc->tls_cfg->capath);
766                 memcpy(desc->old_tls_cfg->certhash, desc->tls_cfg->certhash, 41);
767                 memcpy(desc->old_tls_cfg->pvthash, desc->tls_cfg->pvthash, 41);
768                 memcpy(desc->old_tls_cfg->cahash, desc->tls_cfg->cahash, 41);
769                 memcpy(&desc->old_tls_cfg->flags, &desc->tls_cfg->flags, sizeof(desc->old_tls_cfg->flags));
770         }
771
772         return;
773
774 error:
775         close(desc->accept_fd);
776         desc->accept_fd = -1;
777 }
778
779 void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
780 {
781         if (tcptls_session->stream) {
782                 ast_iostream_close(tcptls_session->stream);
783                 tcptls_session->stream = NULL;
784         } else {
785                 ast_debug(1, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
786         }
787 }
788
789 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
790 {
791         if (desc->master != AST_PTHREADT_NULL) {
792                 pthread_cancel(desc->master);
793                 pthread_kill(desc->master, SIGURG);
794                 pthread_join(desc->master, NULL);
795                 desc->master = AST_PTHREADT_NULL;
796         }
797         if (desc->accept_fd != -1) {
798                 close(desc->accept_fd);
799         }
800         desc->accept_fd = -1;
801
802         if (desc->old_tls_cfg) {
803                 ast_free(desc->old_tls_cfg->certfile);
804                 ast_free(desc->old_tls_cfg->pvtfile);
805                 ast_free(desc->old_tls_cfg->cipher);
806                 ast_free(desc->old_tls_cfg->cafile);
807                 ast_free(desc->old_tls_cfg->capath);
808                 ast_free(desc->old_tls_cfg);
809                 desc->old_tls_cfg = NULL;
810         }
811
812         ast_debug(2, "Stopped server :: %s\n", desc->name);
813 }
814
815 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
816 {
817         if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
818                 tls_cfg->enabled = ast_true(value) ? 1 : 0;
819         } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
820                 ast_free(tls_cfg->certfile);
821                 tls_cfg->certfile = ast_strdup(value);
822         } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
823                 ast_free(tls_cfg->pvtfile);
824                 tls_cfg->pvtfile = ast_strdup(value);
825         } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
826                 ast_free(tls_cfg->cipher);
827                 tls_cfg->cipher = ast_strdup(value);
828         } else if (!strcasecmp(varname, "tlscafile")) {
829                 ast_free(tls_cfg->cafile);
830                 tls_cfg->cafile = ast_strdup(value);
831         } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
832                 ast_free(tls_cfg->capath);
833                 tls_cfg->capath = ast_strdup(value);
834         } else if (!strcasecmp(varname, "tlsverifyclient")) {
835                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
836         } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
837                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
838         } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
839                 if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
840                         ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
841         } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
842                 if (!strcasecmp(value, "tlsv1")) {
843                         ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
844                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
845                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
846                 } else if (!strcasecmp(value, "sslv3")) {
847                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
848                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
849                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
850                 } else if (!strcasecmp(value, "sslv2")) {
851                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
852                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
853                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
854                 }
855         } else if (!strcasecmp(varname, "tlsservercipherorder")) {
856                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_SERVER_CIPHER_ORDER);
857         } else if (!strcasecmp(varname, "tlsdisablev1")) {
858                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV1);
859         } else if (!strcasecmp(varname, "tlsdisablev11")) {
860                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV11);
861         } else if (!strcasecmp(varname, "tlsdisablev12")) {
862                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV12);
863         } else {
864                 return -1;
865         }
866
867         return 0;
868 }