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