Check for OpenSSL defines before trying to use them.
[asterisk/asterisk.git] / main / tcptls.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2008, Digium, Inc.
5  *
6  * Luigi Rizzo (TCP and TLS server code)
7  * Brett Bryant <brettbryant@gmail.com> (updated for client support)
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*!
21  * \file
22  * \brief Code to support TCP and TLS server/client
23  *
24  * \author Luigi Rizzo
25  * \author Brett Bryant <brettbryant@gmail.com>
26  */
27
28 /*** MODULEINFO
29         <support_level>core</support_level>
30  ***/
31
32 #include "asterisk.h"
33
34 ASTERISK_REGISTER_FILE()
35
36 #ifdef HAVE_FCNTL_H
37 #include <fcntl.h>
38 #endif
39
40 #include <signal.h>
41 #include <sys/signal.h>
42
43 #include "asterisk/compat.h"
44 #include "asterisk/tcptls.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
53 /*! ao2 object used for the FILE stream fopencookie()/funopen() cookie. */
54 struct ast_tcptls_stream {
55         /*! SSL state if not NULL */
56         SSL *ssl;
57         /*!
58          * \brief Start time from when an I/O sequence must complete
59          * by struct ast_tcptls_stream.timeout.
60          *
61          * \note If struct ast_tcptls_stream.start.tv_sec is zero then
62          * start time is the current I/O request.
63          */
64         struct timeval start;
65         /*!
66          * \brief The socket returned by accept().
67          *
68          * \note Set to -1 if the stream is closed.
69          */
70         int fd;
71         /*!
72          * \brief Timeout in ms relative to struct ast_tcptls_stream.start
73          * to wait for an event on struct ast_tcptls_stream.fd.
74          *
75          * \note Set to -1 to disable timeout.
76          * \note The socket needs to be set to non-blocking for the timeout
77          * feature to work correctly.
78          */
79         int timeout;
80         /*! TRUE if stream can exclusively wait for fd input. */
81         int exclusive_input;
82 };
83
84 void ast_tcptls_stream_set_timeout_disable(struct ast_tcptls_stream *stream)
85 {
86         ast_assert(stream != NULL);
87
88         stream->timeout = -1;
89 }
90
91 void ast_tcptls_stream_set_timeout_inactivity(struct ast_tcptls_stream *stream, int timeout)
92 {
93         ast_assert(stream != NULL);
94
95         stream->start.tv_sec = 0;
96         stream->timeout = timeout;
97 }
98
99 void ast_tcptls_stream_set_timeout_sequence(struct ast_tcptls_stream *stream, struct timeval start, int timeout)
100 {
101         ast_assert(stream != NULL);
102
103         stream->start = start;
104         stream->timeout = timeout;
105 }
106
107 void ast_tcptls_stream_set_exclusive_input(struct ast_tcptls_stream *stream, int exclusive_input)
108 {
109         ast_assert(stream != NULL);
110
111         stream->exclusive_input = exclusive_input;
112 }
113
114 /*!
115  * \internal
116  * \brief fopencookie()/funopen() stream read function.
117  *
118  * \param cookie Stream control data.
119  * \param buf Where to put read data.
120  * \param size Size of the buffer.
121  *
122  * \retval number of bytes put into buf.
123  * \retval 0 on end of file.
124  * \retval -1 on error.
125  */
126 static HOOK_T tcptls_stream_read(void *cookie, char *buf, LEN_T size)
127 {
128         struct ast_tcptls_stream *stream = cookie;
129         struct timeval start;
130         int ms;
131         int res;
132
133         if (!size) {
134                 /* You asked for no data you got no data. */
135                 return 0;
136         }
137
138         if (!stream || stream->fd == -1) {
139                 errno = EBADF;
140                 return -1;
141         }
142
143         if (stream->start.tv_sec) {
144                 start = stream->start;
145         } else {
146                 start = ast_tvnow();
147         }
148
149 #if defined(DO_SSL)
150         if (stream->ssl) {
151                 for (;;) {
152                         res = SSL_read(stream->ssl, buf, size);
153                         if (0 < res) {
154                                 /* We read some payload data. */
155                                 return res;
156                         }
157                         switch (SSL_get_error(stream->ssl, res)) {
158                         case SSL_ERROR_ZERO_RETURN:
159                                 /* Report EOF for a shutdown */
160                                 ast_debug(1, "TLS clean shutdown alert reading data\n");
161                                 return 0;
162                         case SSL_ERROR_WANT_READ:
163                                 if (!stream->exclusive_input) {
164                                         /* We cannot wait for data now. */
165                                         errno = EAGAIN;
166                                         return -1;
167                                 }
168                                 while ((ms = ast_remaining_ms(start, stream->timeout))) {
169                                         res = ast_wait_for_input(stream->fd, ms);
170                                         if (0 < res) {
171                                                 /* Socket is ready to be read. */
172                                                 break;
173                                         }
174                                         if (res < 0) {
175                                                 if (errno == EINTR || errno == EAGAIN) {
176                                                         /* Try again. */
177                                                         continue;
178                                                 }
179                                                 ast_debug(1, "TLS socket error waiting for read data: %s\n",
180                                                         strerror(errno));
181                                                 return -1;
182                                         }
183                                 }
184                                 break;
185                         case SSL_ERROR_WANT_WRITE:
186                                 while ((ms = ast_remaining_ms(start, stream->timeout))) {
187                                         res = ast_wait_for_output(stream->fd, ms);
188                                         if (0 < res) {
189                                                 /* Socket is ready to be written. */
190                                                 break;
191                                         }
192                                         if (res < 0) {
193                                                 if (errno == EINTR || errno == EAGAIN) {
194                                                         /* Try again. */
195                                                         continue;
196                                                 }
197                                                 ast_debug(1, "TLS socket error waiting for write space: %s\n",
198                                                         strerror(errno));
199                                                 return -1;
200                                         }
201                                 }
202                                 break;
203                         default:
204                                 /* Report EOF for an undecoded SSL or transport error. */
205                                 ast_debug(1, "TLS transport or SSL error reading data\n");
206                                 return 0;
207                         }
208                         if (!ms) {
209                                 /* Report EOF for a timeout */
210                                 ast_debug(1, "TLS timeout reading data\n");
211                                 return 0;
212                         }
213                 }
214         }
215 #endif  /* defined(DO_SSL) */
216
217         for (;;) {
218                 res = read(stream->fd, buf, size);
219                 if (0 <= res || !stream->exclusive_input) {
220                         /* Got data or we cannot wait for it. */
221                         return res;
222                 }
223                 if (errno != EINTR && errno != EAGAIN) {
224                         /* Not a retryable error. */
225                         ast_debug(1, "TCP socket error reading data: %s\n",
226                                 strerror(errno));
227                         return -1;
228                 }
229                 ms = ast_remaining_ms(start, stream->timeout);
230                 if (!ms) {
231                         /* Report EOF for a timeout */
232                         ast_debug(1, "TCP timeout reading data\n");
233                         return 0;
234                 }
235                 ast_wait_for_input(stream->fd, ms);
236         }
237 }
238
239 /*!
240  * \internal
241  * \brief fopencookie()/funopen() stream write function.
242  *
243  * \param cookie Stream control data.
244  * \param buf Where to get data to write.
245  * \param size Size of the buffer.
246  *
247  * \retval number of bytes written from buf.
248  * \retval -1 on error.
249  */
250 static HOOK_T tcptls_stream_write(void *cookie, const char *buf, LEN_T size)
251 {
252         struct ast_tcptls_stream *stream = cookie;
253         struct timeval start;
254         int ms;
255         int res;
256         int written;
257         int remaining;
258
259         if (!size) {
260                 /* You asked to write no data you wrote no data. */
261                 return 0;
262         }
263
264         if (!stream || stream->fd == -1) {
265                 errno = EBADF;
266                 return -1;
267         }
268
269         if (stream->start.tv_sec) {
270                 start = stream->start;
271         } else {
272                 start = ast_tvnow();
273         }
274
275 #if defined(DO_SSL)
276         if (stream->ssl) {
277                 written = 0;
278                 remaining = size;
279                 for (;;) {
280                         res = SSL_write(stream->ssl, buf + written, remaining);
281                         if (res == remaining) {
282                                 /* Everything was written. */
283                                 return size;
284                         }
285                         if (0 < res) {
286                                 /* Successfully wrote part of the buffer.  Try to write the rest. */
287                                 written += res;
288                                 remaining -= res;
289                                 continue;
290                         }
291                         switch (SSL_get_error(stream->ssl, res)) {
292                         case SSL_ERROR_ZERO_RETURN:
293                                 ast_debug(1, "TLS clean shutdown alert writing data\n");
294                                 if (written) {
295                                         /* Report partial write. */
296                                         return written;
297                                 }
298                                 errno = EBADF;
299                                 return -1;
300                         case SSL_ERROR_WANT_READ:
301                                 ms = ast_remaining_ms(start, stream->timeout);
302                                 if (!ms) {
303                                         /* Report partial write. */
304                                         ast_debug(1, "TLS timeout writing data (want read)\n");
305                                         return written;
306                                 }
307                                 ast_wait_for_input(stream->fd, ms);
308                                 break;
309                         case SSL_ERROR_WANT_WRITE:
310                                 ms = ast_remaining_ms(start, stream->timeout);
311                                 if (!ms) {
312                                         /* Report partial write. */
313                                         ast_debug(1, "TLS timeout writing data (want write)\n");
314                                         return written;
315                                 }
316                                 ast_wait_for_output(stream->fd, ms);
317                                 break;
318                         default:
319                                 /* Undecoded SSL or transport error. */
320                                 ast_debug(1, "TLS transport or SSL error writing data\n");
321                                 if (written) {
322                                         /* Report partial write. */
323                                         return written;
324                                 }
325                                 errno = EBADF;
326                                 return -1;
327                         }
328                 }
329         }
330 #endif  /* defined(DO_SSL) */
331
332         written = 0;
333         remaining = size;
334         for (;;) {
335                 res = write(stream->fd, buf + written, remaining);
336                 if (res == remaining) {
337                         /* Yay everything was written. */
338                         return size;
339                 }
340                 if (0 < res) {
341                         /* Successfully wrote part of the buffer.  Try to write the rest. */
342                         written += res;
343                         remaining -= res;
344                         continue;
345                 }
346                 if (errno != EINTR && errno != EAGAIN) {
347                         /* Not a retryable error. */
348                         ast_debug(1, "TCP socket error writing: %s\n", strerror(errno));
349                         if (written) {
350                                 return written;
351                         }
352                         return -1;
353                 }
354                 ms = ast_remaining_ms(start, stream->timeout);
355                 if (!ms) {
356                         /* Report partial write. */
357                         ast_debug(1, "TCP timeout writing data\n");
358                         return written;
359                 }
360                 ast_wait_for_output(stream->fd, ms);
361         }
362 }
363
364 /*!
365  * \internal
366  * \brief fopencookie()/funopen() stream close function.
367  *
368  * \param cookie Stream control data.
369  *
370  * \retval 0 on success.
371  * \retval -1 on error.
372  */
373 static int tcptls_stream_close(void *cookie)
374 {
375         struct ast_tcptls_stream *stream = cookie;
376
377         if (!stream) {
378                 errno = EBADF;
379                 return -1;
380         }
381
382         if (stream->fd != -1) {
383 #if defined(DO_SSL)
384                 if (stream->ssl) {
385                         int res;
386
387                         /*
388                          * According to the TLS standard, it is acceptable for an
389                          * application to only send its shutdown alert and then
390                          * close the underlying connection without waiting for
391                          * the peer's response (this way resources can be saved,
392                          * as the process can already terminate or serve another
393                          * connection).
394                          */
395                         res = SSL_shutdown(stream->ssl);
396                         if (res < 0) {
397                                 ast_log(LOG_ERROR, "SSL_shutdown() failed: %d\n",
398                                         SSL_get_error(stream->ssl, res));
399                         }
400
401                         if (!stream->ssl->server) {
402                                 /* For client threads, ensure that the error stack is cleared */
403 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
404                                 ERR_remove_thread_state(NULL);
405 #else
406                                 ERR_remove_state(0);
407 #endif  /* OPENSSL_VERSION_NUMBER >= 0x10000000L */
408                         }
409
410                         SSL_free(stream->ssl);
411                         stream->ssl = NULL;
412                 }
413 #endif  /* defined(DO_SSL) */
414
415                 /*
416                  * Issuing shutdown() is necessary here to avoid a race
417                  * condition where the last data written may not appear
418                  * in the TCP stream.  See ASTERISK-23548
419                  */
420                 shutdown(stream->fd, SHUT_RDWR);
421                 if (close(stream->fd)) {
422                         ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
423                 }
424                 stream->fd = -1;
425         }
426         ao2_t_ref(stream, -1, "Closed tcptls stream cookie");
427
428         return 0;
429 }
430
431 /*!
432  * \internal
433  * \brief fopencookie()/funopen() stream destructor function.
434  *
435  * \param cookie Stream control data.
436  *
437  * \return Nothing
438  */
439 static void tcptls_stream_dtor(void *cookie)
440 {
441 #ifdef AST_DEVMODE
442         /* Since the ast_assert below is the only one using stream,
443          * and ast_assert is only available with AST_DEVMODE, we
444          * put this in a conditional to avoid compiler warnings. */
445         struct ast_tcptls_stream *stream = cookie;
446 #endif
447
448         ast_assert(stream->fd == -1);
449 }
450
451 /*!
452  * \internal
453  * \brief fopencookie()/funopen() stream allocation function.
454  *
455  * \retval stream_cookie on success.
456  * \retval NULL on error.
457  */
458 static struct ast_tcptls_stream *tcptls_stream_alloc(void)
459 {
460         struct ast_tcptls_stream *stream;
461
462         stream = ao2_alloc_options(sizeof(*stream), tcptls_stream_dtor,
463                 AO2_ALLOC_OPT_LOCK_NOLOCK);
464         if (stream) {
465                 stream->fd = -1;
466                 stream->timeout = -1;
467         }
468         return stream;
469 }
470
471 /*!
472  * \internal
473  * \brief Open a custom FILE stream for tcptls.
474  *
475  * \param stream Stream cookie control data.
476  * \param ssl SSL state if not NULL.
477  * \param fd Socket file descriptor.
478  * \param timeout ms to wait for an event on fd. -1 if timeout disabled.
479  *
480  * \retval fp on success.
481  * \retval NULL on error.
482  */
483 static FILE *tcptls_stream_fopen(struct ast_tcptls_stream *stream, SSL *ssl, int fd, int timeout)
484 {
485         FILE *fp;
486
487 #if defined(HAVE_FOPENCOOKIE)   /* the glibc/linux interface */
488         static const cookie_io_functions_t cookie_funcs = {
489                 tcptls_stream_read,
490                 tcptls_stream_write,
491                 NULL,
492                 tcptls_stream_close
493         };
494 #endif  /* defined(HAVE_FOPENCOOKIE) */
495
496         if (fd == -1) {
497                 /* Socket not open. */
498                 return NULL;
499         }
500
501         stream->ssl = ssl;
502         stream->fd = fd;
503         stream->timeout = timeout;
504         ao2_t_ref(stream, +1, "Opening tcptls stream cookie");
505
506 #if defined(HAVE_FUNOPEN)       /* the BSD interface */
507         fp = funopen(stream, tcptls_stream_read, tcptls_stream_write, NULL,
508                 tcptls_stream_close);
509 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
510         fp = fopencookie(stream, "w+", cookie_funcs);
511 #else
512         /* could add other methods here */
513         ast_debug(2, "No stream FILE methods attempted!\n");
514         fp = NULL;
515 #endif
516
517         if (!fp) {
518                 stream->fd = -1;
519                 ao2_t_ref(stream, -1, "Failed to open tcptls stream cookie");
520         }
521         return fp;
522 }
523
524 HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *tcptls_session, void *buf, size_t count)
525 {
526         if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
527                 ast_log(LOG_ERROR, "TCP/TLS read called on invalid stream.\n");
528                 errno = EIO;
529                 return -1;
530         }
531
532         return tcptls_stream_read(tcptls_session->stream_cookie, buf, count);
533 }
534
535 HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t count)
536 {
537         if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
538                 ast_log(LOG_ERROR, "TCP/TLS write called on invalid stream.\n");
539                 errno = EIO;
540                 return -1;
541         }
542
543         return tcptls_stream_write(tcptls_session->stream_cookie, buf, count);
544 }
545
546 static void session_instance_destructor(void *obj)
547 {
548         struct ast_tcptls_session_instance *i = obj;
549
550         if (i->stream_cookie) {
551                 ao2_t_ref(i->stream_cookie, -1, "Destroying tcptls session instance");
552                 i->stream_cookie = NULL;
553         }
554         ast_free(i->overflow_buf);
555         ao2_cleanup(i->private_data);
556 }
557
558 #ifdef DO_SSL
559 static int check_tcptls_cert_name(ASN1_STRING *cert_str, const char *hostname, const char *desc)
560 {
561         unsigned char *str;
562         int ret;
563
564         ret = ASN1_STRING_to_UTF8(&str, cert_str);
565         if (ret < 0 || !str) {
566                 return -1;
567         }
568
569         if (strlen((char *) str) != ret) {
570                 ast_log(LOG_WARNING, "Invalid certificate %s length (contains NULL bytes?)\n", desc);
571
572                 ret = -1;
573         } else if (!strcasecmp(hostname, (char *) str)) {
574                 ret = 0;
575         } else {
576                 ret = -1;
577         }
578
579         ast_debug(3, "SSL %s compare s1='%s' s2='%s'\n", desc, hostname, str);
580         OPENSSL_free(str);
581
582         return ret;
583 }
584 #endif
585
586 /*! \brief
587 * creates a FILE * from the fd passed by the accept thread.
588 * This operation is potentially expensive (certificate verification),
589 * so we do it in the child thread context.
590 *
591 * \note must decrement ref count before returning NULL on error
592 */
593 static void *handle_tcptls_connection(void *data)
594 {
595         struct ast_tcptls_session_instance *tcptls_session = data;
596 #ifdef DO_SSL
597         int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
598         int ret;
599         char err[256];
600 #endif
601
602         /* TCP/TLS connections are associated with external protocols, and
603          * should not be allowed to execute 'dangerous' functions. This may
604          * need to be pushed down into the individual protocol handlers, but
605          * this seems like a good general policy.
606          */
607         if (ast_thread_inhibit_escalations()) {
608                 ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
609                 ast_tcptls_close_session_file(tcptls_session);
610                 ao2_ref(tcptls_session, -1);
611                 return NULL;
612         }
613
614         tcptls_session->stream_cookie = tcptls_stream_alloc();
615         if (!tcptls_session->stream_cookie) {
616                 ast_tcptls_close_session_file(tcptls_session);
617                 ao2_ref(tcptls_session, -1);
618                 return NULL;
619         }
620
621         /*
622         * open a FILE * as appropriate.
623         */
624         if (!tcptls_session->parent->tls_cfg) {
625                 tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie, NULL,
626                         tcptls_session->fd, -1);
627                 if (tcptls_session->f) {
628                         if (setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
629                                 ast_tcptls_close_session_file(tcptls_session);
630                         }
631                 }
632         }
633 #ifdef DO_SSL
634         else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
635                 SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
636                 if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
637                         ast_log(LOG_ERROR, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
638                 } else if ((tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie,
639                         tcptls_session->ssl, tcptls_session->fd, -1))) {
640                         if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
641                                 || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
642                                 X509 *peer;
643                                 long res;
644                                 peer = SSL_get_peer_certificate(tcptls_session->ssl);
645                                 if (!peer) {
646                                         ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
647                                         ast_tcptls_close_session_file(tcptls_session);
648                                         ao2_ref(tcptls_session, -1);
649                                         return NULL;
650                                 }
651
652                                 res = SSL_get_verify_result(tcptls_session->ssl);
653                                 if (res != X509_V_OK) {
654                                         ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
655                                         X509_free(peer);
656                                         ast_tcptls_close_session_file(tcptls_session);
657                                         ao2_ref(tcptls_session, -1);
658                                         return NULL;
659                                 }
660                                 if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
661                                         ASN1_STRING *str;
662                                         X509_NAME *name = X509_get_subject_name(peer);
663                                         STACK_OF(GENERAL_NAME) *alt_names;
664                                         int pos = -1;
665                                         int found = 0;
666
667                                         for (;;) {
668                                                 /* Walk the certificate to check all available "Common Name" */
669                                                 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
670                                                 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
671                                                 if (pos < 0) {
672                                                         break;
673                                                 }
674
675                                                 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
676                                                 if (!check_tcptls_cert_name(str, tcptls_session->parent->hostname, "common name")) {
677                                                         found = 1;
678                                                         break;
679                                                 }
680                                         }
681
682                                         if (!found) {
683                                                 alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, NULL, NULL);
684                                                 if (alt_names != NULL) {
685                                                         int alt_names_count = sk_GENERAL_NAME_num(alt_names);
686
687                                                         for (pos = 0; pos < alt_names_count; pos++) {
688                                                                 const GENERAL_NAME *alt_name = sk_GENERAL_NAME_value(alt_names, pos);
689
690                                                                 if (alt_name->type != GEN_DNS) {
691                                                                         continue;
692                                                                 }
693
694                                                                 if (!check_tcptls_cert_name(alt_name->d.dNSName, tcptls_session->parent->hostname, "alt name")) {
695                                                                         found = 1;
696                                                                         break;
697                                                                 }
698                                                         }
699
700                                                         sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
701                                                 }
702                                         }
703
704                                         if (!found) {
705                                                 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
706                                                 X509_free(peer);
707                                                 ast_tcptls_close_session_file(tcptls_session);
708                                                 ao2_ref(tcptls_session, -1);
709                                                 return NULL;
710                                         }
711                                 }
712                                 X509_free(peer);
713                         }
714                 }
715                 if (!tcptls_session->f) {       /* no success opening descriptor stacking */
716                         SSL_free(tcptls_session->ssl);
717                 }
718         }
719 #endif /* DO_SSL */
720
721         if (!tcptls_session->f) {
722                 ast_tcptls_close_session_file(tcptls_session);
723                 ast_log(LOG_WARNING, "FILE * open failed!\n");
724 #ifndef DO_SSL
725                 if (tcptls_session->parent->tls_cfg) {
726                         ast_log(LOG_ERROR, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
727                 }
728 #endif
729                 ao2_ref(tcptls_session, -1);
730                 return NULL;
731         }
732
733         if (tcptls_session->parent->worker_fn) {
734                 return tcptls_session->parent->worker_fn(tcptls_session);
735         } else {
736                 return tcptls_session;
737         }
738 }
739
740 void *ast_tcptls_server_root(void *data)
741 {
742         struct ast_tcptls_session_args *desc = data;
743         int fd;
744         struct ast_sockaddr addr;
745         struct ast_tcptls_session_instance *tcptls_session;
746         pthread_t launched;
747
748         for (;;) {
749                 int i, flags;
750
751                 if (desc->periodic_fn) {
752                         desc->periodic_fn(desc);
753                 }
754                 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
755                 if (i <= 0) {
756                         continue;
757                 }
758                 fd = ast_accept(desc->accept_fd, &addr);
759                 if (fd < 0) {
760                         if ((errno != EAGAIN) && (errno != EWOULDBLOCK) && (errno != EINTR) && (errno != ECONNABORTED)) {
761                                 ast_log(LOG_ERROR, "Accept failed: %s\n", strerror(errno));
762                                 break;
763                         }
764                         continue;
765                 }
766                 tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
767                 if (!tcptls_session) {
768                         ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
769                         if (close(fd)) {
770                                 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
771                         }
772                         continue;
773                 }
774
775                 tcptls_session->overflow_buf = ast_str_create(128);
776                 flags = fcntl(fd, F_GETFL);
777                 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
778                 tcptls_session->fd = fd;
779                 tcptls_session->parent = desc;
780                 ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
781
782                 tcptls_session->client = 0;
783
784                 /* This thread is now the only place that controls the single ref to tcptls_session */
785                 if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
786                         ast_log(LOG_ERROR, "Unable to launch helper thread: %s\n", strerror(errno));
787                         ast_tcptls_close_session_file(tcptls_session);
788                         ao2_ref(tcptls_session, -1);
789                 }
790         }
791         return NULL;
792 }
793
794 #ifdef DO_SSL
795 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)
796 {
797         char *cert_file = ast_strdupa(cfg->certfile);
798
799         memcpy(cert_file + cert_file_len - 8, key_type_extension, 5);
800         if (access(cert_file, F_OK) == 0) {
801                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cert_file) == 0) {
802                         ast_log(LOG_WARNING, "TLS/SSL error loading public %s key (certificate) from <%s>.\n", key_type, cert_file);
803                 } else if (SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, cert_file, SSL_FILETYPE_PEM) == 0) {
804                         ast_log(LOG_WARNING, "TLS/SSL error loading private %s key from <%s>.\n", key_type, cert_file);
805                 } else if (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0) {
806                         ast_log(LOG_WARNING, "TLS/SSL error matching private %s key and certificate in <%s>.\n", key_type, cert_file);
807                 }
808         }
809 }
810 #endif
811
812 static int __ssl_setup(struct ast_tls_config *cfg, int client)
813 {
814 #ifndef DO_SSL
815         cfg->enabled = 0;
816         return 0;
817 #else
818         int disable_ssl = 0;
819         long ssl_opts = 0;
820
821         if (!cfg->enabled) {
822                 return 0;
823         }
824
825         /* Get rid of an old SSL_CTX since we're about to
826          * allocate a new one
827          */
828         if (cfg->ssl_ctx) {
829                 SSL_CTX_free(cfg->ssl_ctx);
830                 cfg->ssl_ctx = NULL;
831         }
832
833         if (client) {
834 #ifndef OPENSSL_NO_SSL2
835                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
836                         ast_log(LOG_WARNING, "Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
837                         cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
838                 } else
839 #endif
840 #ifndef OPENSSL_NO_SSL3_METHOD
841                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
842                         ast_log(LOG_WARNING, "Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
843                         cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
844                 } else
845 #endif
846                 if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
847                         cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
848                 } else {
849                         disable_ssl = 1;
850                         cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
851                 }
852         } else {
853                 disable_ssl = 1;
854                 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
855         }
856
857         if (!cfg->ssl_ctx) {
858                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
859                 cfg->enabled = 0;
860                 return 0;
861         }
862
863         /* Due to the POODLE vulnerability, completely disable
864          * SSLv2 and SSLv3 if we are not explicitly told to use
865          * them. SSLv23_*_method supports TLSv1+.
866          */
867         if (disable_ssl) {
868                 ssl_opts |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
869         }
870
871         if (ast_test_flag(&cfg->flags, AST_SSL_SERVER_CIPHER_ORDER)) {
872                 ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
873         }
874
875         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV1)) {
876                 ssl_opts |= SSL_OP_NO_TLSv1;
877         }
878 #if defined(HAVE_SSL_OP_NO_TLSV1_1) && defined(HAVE_SSL_OP_NO_TLSV1_2)
879         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV11)) {
880                 ssl_opts |= SSL_OP_NO_TLSv1_1;
881         }
882         if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV12)) {
883                 ssl_opts |= SSL_OP_NO_TLSv1_2;
884         }
885 #else
886         ast_log(LOG_WARNING, "Your version of OpenSSL leaves you potentially vulnerable "
887                         "to the SSL BEAST attack. Please upgrade to OpenSSL 1.0.1 or later\n");
888 #endif
889
890         SSL_CTX_set_options(cfg->ssl_ctx, ssl_opts);
891
892         SSL_CTX_set_verify(cfg->ssl_ctx,
893                 ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
894                 NULL);
895
896         if (!ast_strlen_zero(cfg->certfile)) {
897                 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
898                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
899                         if (!client) {
900                                 /* Clients don't need a certificate, but if its setup we can use it */
901                                 ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
902                                 cfg->enabled = 0;
903                                 SSL_CTX_free(cfg->ssl_ctx);
904                                 cfg->ssl_ctx = NULL;
905                                 return 0;
906                         }
907                 }
908                 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
909                         if (!client) {
910                                 /* Clients don't need a private key, but if its setup we can use it */
911                                 ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
912                                 cfg->enabled = 0;
913                                 SSL_CTX_free(cfg->ssl_ctx);
914                                 cfg->ssl_ctx = NULL;
915                                 return 0;
916                         }
917                 }
918                 if (!client) {
919                         size_t certfile_len = strlen(cfg->certfile);
920
921                         /* expects a file name which contains _rsa. like asterisk_rsa.pem
922                          * ignores any 3-character file-extension like .pem, .cer, .crt
923                          */
924                         if (certfile_len >= 8 && !strncmp(cfg->certfile + certfile_len - 8, "_rsa.", 5)) {
925                                 __ssl_setup_certs(cfg, certfile_len, "_ecc.", "ECC");
926                                 __ssl_setup_certs(cfg, certfile_len, "_dsa.", "DSA");
927                         }
928                 }
929         }
930         if (!ast_strlen_zero(cfg->cipher)) {
931                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
932                         if (!client) {
933                                 ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
934                                 cfg->enabled = 0;
935                                 SSL_CTX_free(cfg->ssl_ctx);
936                                 cfg->ssl_ctx = NULL;
937                                 return 0;
938                         }
939                 }
940         }
941         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
942                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
943                         ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
944                 }
945         }
946
947 #ifdef HAVE_OPENSSL_EC
948
949         if (!ast_strlen_zero(cfg->pvtfile)) {
950                 BIO *bio = BIO_new_file(cfg->pvtfile, "r");
951                 if (bio != NULL) {
952                         DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
953                         if (dh != NULL) {
954                                 if (SSL_CTX_set_tmp_dh(cfg->ssl_ctx, dh)) {
955                                         long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
956                                         options = SSL_CTX_set_options(cfg->ssl_ctx, options);
957                                         ast_verb(2, "TLS/SSL DH initialized, PFS cipher-suites enabled\n");
958                                 }
959                                 DH_free(dh);
960                         }
961                         BIO_free(bio);
962                 }
963         }
964         #ifndef SSL_CTRL_SET_ECDH_AUTO
965                 #define SSL_CTRL_SET_ECDH_AUTO 94
966         #endif
967         /* SSL_CTX_set_ecdh_auto(cfg->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
968         if (SSL_CTX_ctrl(cfg->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
969                 ast_verb(2, "TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
970         } else {
971                 /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
972                 EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
973                 if (ecdh != NULL) {
974                         if (SSL_CTX_set_tmp_ecdh(cfg->ssl_ctx, ecdh)) {
975                                 ast_verb(2, "TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
976                         }
977                         EC_KEY_free(ecdh);
978                 }
979         }
980
981 #endif /* #ifdef HAVE_OPENSSL_EC */
982
983         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 */
984         return 1;
985 #endif
986 }
987
988 int ast_ssl_setup(struct ast_tls_config *cfg)
989 {
990         return __ssl_setup(cfg, 0);
991 }
992
993 void ast_ssl_teardown(struct ast_tls_config *cfg)
994 {
995 #ifdef DO_SSL
996         if (cfg->ssl_ctx) {
997                 SSL_CTX_free(cfg->ssl_ctx);
998                 cfg->ssl_ctx = NULL;
999         }
1000 #endif
1001 }
1002
1003 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
1004 {
1005         struct ast_tcptls_session_args *desc;
1006         int flags;
1007
1008         if (!(desc = tcptls_session->parent)) {
1009                 goto client_start_error;
1010         }
1011
1012         if (ast_connect(desc->accept_fd, &desc->remote_address)) {
1013                 ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
1014                         desc->name,
1015                         ast_sockaddr_stringify(&desc->remote_address),
1016                         strerror(errno));
1017                 goto client_start_error;
1018         }
1019
1020         flags = fcntl(desc->accept_fd, F_GETFL);
1021         fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
1022
1023         if (desc->tls_cfg) {
1024                 desc->tls_cfg->enabled = 1;
1025                 __ssl_setup(desc->tls_cfg, 1);
1026         }
1027
1028         return handle_tcptls_connection(tcptls_session);
1029
1030 client_start_error:
1031         if (desc) {
1032                 close(desc->accept_fd);
1033                 desc->accept_fd = -1;
1034         }
1035         ao2_ref(tcptls_session, -1);
1036         return NULL;
1037
1038 }
1039
1040 struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
1041 {
1042         int x = 1;
1043         struct ast_tcptls_session_instance *tcptls_session = NULL;
1044
1045         /* Do nothing if nothing has changed */
1046         if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
1047                 ast_debug(1, "Nothing changed in %s\n", desc->name);
1048                 return NULL;
1049         }
1050
1051         /* If we return early, there is no connection */
1052         ast_sockaddr_setnull(&desc->old_address);
1053
1054         if (desc->accept_fd != -1) {
1055                 close(desc->accept_fd);
1056         }
1057
1058         desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
1059                                  AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
1060         if (desc->accept_fd < 0) {
1061                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
1062                         desc->name, strerror(errno));
1063                 return NULL;
1064         }
1065
1066         /* if a local address was specified, bind to it so the connection will
1067            originate from the desired address */
1068         if (!ast_sockaddr_isnull(&desc->local_address)) {
1069                 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1070                 if (ast_bind(desc->accept_fd, &desc->local_address)) {
1071                         ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
1072                                 desc->name,
1073                                 ast_sockaddr_stringify(&desc->local_address),
1074                                 strerror(errno));
1075                         goto error;
1076                 }
1077         }
1078
1079         if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor))) {
1080                 goto error;
1081         }
1082
1083         tcptls_session->overflow_buf = ast_str_create(128);
1084         tcptls_session->client = 1;
1085         tcptls_session->fd = desc->accept_fd;
1086         tcptls_session->parent = desc;
1087         tcptls_session->parent->worker_fn = NULL;
1088         ast_sockaddr_copy(&tcptls_session->remote_address,
1089                           &desc->remote_address);
1090
1091         /* Set current info */
1092         ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
1093         return tcptls_session;
1094
1095 error:
1096         close(desc->accept_fd);
1097         desc->accept_fd = -1;
1098         if (tcptls_session) {
1099                 ao2_ref(tcptls_session, -1);
1100         }
1101         return NULL;
1102 }
1103
1104 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
1105 {
1106         int flags;
1107         int x = 1;
1108
1109         /* Do nothing if nothing has changed */
1110         if (!ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
1111                 ast_debug(1, "Nothing changed in %s\n", desc->name);
1112                 return;
1113         }
1114
1115         /* If we return early, there is no one listening */
1116         ast_sockaddr_setnull(&desc->old_address);
1117
1118         /* Shutdown a running server if there is one */
1119         if (desc->master != AST_PTHREADT_NULL) {
1120                 pthread_cancel(desc->master);
1121                 pthread_kill(desc->master, SIGURG);
1122                 pthread_join(desc->master, NULL);
1123         }
1124
1125         if (desc->accept_fd != -1) {
1126                 close(desc->accept_fd);
1127         }
1128
1129         /* If there's no new server, stop here */
1130         if (ast_sockaddr_isnull(&desc->local_address)) {
1131                 ast_debug(2, "Server disabled:  %s\n", desc->name);
1132                 return;
1133         }
1134
1135         desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
1136                                  AF_INET6 : AF_INET, SOCK_STREAM, 0);
1137         if (desc->accept_fd < 0) {
1138                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
1139                 return;
1140         }
1141
1142         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1143         if (ast_bind(desc->accept_fd, &desc->local_address)) {
1144                 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
1145                         desc->name,
1146                         ast_sockaddr_stringify(&desc->local_address),
1147                         strerror(errno));
1148                 goto error;
1149         }
1150         if (listen(desc->accept_fd, 10)) {
1151                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
1152                 goto error;
1153         }
1154         flags = fcntl(desc->accept_fd, F_GETFL);
1155         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
1156         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
1157                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
1158                         desc->name,
1159                         ast_sockaddr_stringify(&desc->local_address),
1160                         strerror(errno));
1161                 goto error;
1162         }
1163
1164         /* Set current info */
1165         ast_sockaddr_copy(&desc->old_address, &desc->local_address);
1166
1167         return;
1168
1169 error:
1170         close(desc->accept_fd);
1171         desc->accept_fd = -1;
1172 }
1173
1174 void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
1175 {
1176         if (tcptls_session->f) {
1177                 fflush(tcptls_session->f);
1178                 if (fclose(tcptls_session->f)) {
1179                         ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
1180                 }
1181                 tcptls_session->f = NULL;
1182                 tcptls_session->fd = -1;
1183         } else if (tcptls_session->fd != -1) {
1184                 /*
1185                  * Issuing shutdown() is necessary here to avoid a race
1186                  * condition where the last data written may not appear
1187                  * in the TCP stream.  See ASTERISK-23548
1188                  */
1189                 shutdown(tcptls_session->fd, SHUT_RDWR);
1190                 if (close(tcptls_session->fd)) {
1191                         ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
1192                 }
1193                 tcptls_session->fd = -1;
1194         } else {
1195                 ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
1196         }
1197 }
1198
1199 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
1200 {
1201         if (desc->master != AST_PTHREADT_NULL) {
1202                 pthread_cancel(desc->master);
1203                 pthread_kill(desc->master, SIGURG);
1204                 pthread_join(desc->master, NULL);
1205                 desc->master = AST_PTHREADT_NULL;
1206         }
1207         if (desc->accept_fd != -1) {
1208                 close(desc->accept_fd);
1209         }
1210         desc->accept_fd = -1;
1211         ast_debug(2, "Stopped server :: %s\n", desc->name);
1212 }
1213
1214 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
1215 {
1216         if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
1217                 tls_cfg->enabled = ast_true(value) ? 1 : 0;
1218         } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
1219                 ast_free(tls_cfg->certfile);
1220                 tls_cfg->certfile = ast_strdup(value);
1221         } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
1222                 ast_free(tls_cfg->pvtfile);
1223                 tls_cfg->pvtfile = ast_strdup(value);
1224         } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
1225                 ast_free(tls_cfg->cipher);
1226                 tls_cfg->cipher = ast_strdup(value);
1227         } else if (!strcasecmp(varname, "tlscafile")) {
1228                 ast_free(tls_cfg->cafile);
1229                 tls_cfg->cafile = ast_strdup(value);
1230         } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
1231                 ast_free(tls_cfg->capath);
1232                 tls_cfg->capath = ast_strdup(value);
1233         } else if (!strcasecmp(varname, "tlsverifyclient")) {
1234                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
1235         } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
1236                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
1237         } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
1238                 if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
1239                         ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
1240         } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
1241                 if (!strcasecmp(value, "tlsv1")) {
1242                         ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1243                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1244                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1245                 } else if (!strcasecmp(value, "sslv3")) {
1246                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1247                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1248                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1249                 } else if (!strcasecmp(value, "sslv2")) {
1250                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1251                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1252                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1253                 }
1254         } else if (!strcasecmp(varname, "tlsservercipherorder")) {
1255                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_SERVER_CIPHER_ORDER);
1256         } else if (!strcasecmp(varname, "tlsdisablev1")) {
1257                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV1);
1258         } else if (!strcasecmp(varname, "tlsdisablev11")) {
1259                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV11);
1260         } else if (!strcasecmp(varname, "tlsdisablev12")) {
1261                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV12);
1262         } else {
1263                 return -1;
1264         }
1265
1266         return 0;
1267 }