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