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