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