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