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