HTTP: Add persistent connection support.
[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_FILE_VERSION(__FILE__, "$Revision$")
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                                 ERR_remove_state(0);
404                         }
405
406                         SSL_free(stream->ssl);
407                         stream->ssl = NULL;
408                 }
409 #endif  /* defined(DO_SSL) */
410
411                 /*
412                  * Issuing shutdown() is necessary here to avoid a race
413                  * condition where the last data written may not appear
414                  * in the TCP stream.  See ASTERISK-23548
415                  */
416                 shutdown(stream->fd, SHUT_RDWR);
417                 if (close(stream->fd)) {
418                         ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
419                 }
420                 stream->fd = -1;
421         }
422         ao2_t_ref(stream, -1, "Closed tcptls stream cookie");
423
424         return 0;
425 }
426
427 /*!
428  * \internal
429  * \brief fopencookie()/funopen() stream destructor function.
430  *
431  * \param cookie Stream control data.
432  *
433  * \return Nothing
434  */
435 static void tcptls_stream_dtor(void *cookie)
436 {
437         struct ast_tcptls_stream *stream = cookie;
438
439         ast_assert(stream->fd == -1);
440 }
441
442 /*!
443  * \internal
444  * \brief fopencookie()/funopen() stream allocation function.
445  *
446  * \retval stream_cookie on success.
447  * \retval NULL on error.
448  */
449 static struct ast_tcptls_stream *tcptls_stream_alloc(void)
450 {
451         struct ast_tcptls_stream *stream;
452
453         stream = ao2_alloc_options(sizeof(*stream), tcptls_stream_dtor,
454                 AO2_ALLOC_OPT_LOCK_NOLOCK);
455         if (stream) {
456                 stream->fd = -1;
457                 stream->timeout = -1;
458         }
459         return stream;
460 }
461
462 /*!
463  * \internal
464  * \brief Open a custom FILE stream for tcptls.
465  *
466  * \param stream Stream cookie control data.
467  * \param ssl SSL state if not NULL.
468  * \param fd Socket file descriptor.
469  * \param timeout ms to wait for an event on fd. -1 if timeout disabled.
470  *
471  * \retval fp on success.
472  * \retval NULL on error.
473  */
474 static FILE *tcptls_stream_fopen(struct ast_tcptls_stream *stream, SSL *ssl, int fd, int timeout)
475 {
476         FILE *fp;
477
478 #if defined(HAVE_FOPENCOOKIE)   /* the glibc/linux interface */
479         static const cookie_io_functions_t cookie_funcs = {
480                 tcptls_stream_read,
481                 tcptls_stream_write,
482                 NULL,
483                 tcptls_stream_close
484         };
485 #endif  /* defined(HAVE_FOPENCOOKIE) */
486
487         if (fd == -1) {
488                 /* Socket not open. */
489                 return NULL;
490         }
491
492         stream->ssl = ssl;
493         stream->fd = fd;
494         stream->timeout = timeout;
495         ao2_t_ref(stream, +1, "Opening tcptls stream cookie");
496
497 #if defined(HAVE_FUNOPEN)       /* the BSD interface */
498         fp = funopen(stream, tcptls_stream_read, tcptls_stream_write, NULL,
499                 tcptls_stream_close);
500 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
501         fp = fopencookie(stream, "w+", cookie_funcs);
502 #else
503         /* could add other methods here */
504         ast_debug(2, "No stream FILE methods attempted!\n");
505         fp = NULL;
506 #endif
507
508         if (!fp) {
509                 stream->fd = -1;
510                 ao2_t_ref(stream, -1, "Failed to open tcptls stream cookie");
511         }
512         return fp;
513 }
514
515 HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *tcptls_session, void *buf, size_t count)
516 {
517         if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
518                 ast_log(LOG_ERROR, "TCP/TLS read called on invalid stream.\n");
519                 errno = EIO;
520                 return -1;
521         }
522
523         return tcptls_stream_read(tcptls_session->stream_cookie, buf, count);
524 }
525
526 HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t count)
527 {
528         if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
529                 ast_log(LOG_ERROR, "TCP/TLS write called on invalid stream.\n");
530                 errno = EIO;
531                 return -1;
532         }
533
534         return tcptls_stream_write(tcptls_session->stream_cookie, buf, count);
535 }
536
537 static void session_instance_destructor(void *obj)
538 {
539         struct ast_tcptls_session_instance *i = obj;
540
541         if (i->stream_cookie) {
542                 ao2_t_ref(i->stream_cookie, -1, "Destroying tcptls session instance");
543                 i->stream_cookie = NULL;
544         }
545         ast_free(i->overflow_buf);
546         ao2_cleanup(i->private_data);
547 }
548
549 /*! \brief
550 * creates a FILE * from the fd passed by the accept thread.
551 * This operation is potentially expensive (certificate verification),
552 * so we do it in the child thread context.
553 *
554 * \note must decrement ref count before returning NULL on error
555 */
556 static void *handle_tcptls_connection(void *data)
557 {
558         struct ast_tcptls_session_instance *tcptls_session = data;
559 #ifdef DO_SSL
560         int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
561         int ret;
562         char err[256];
563 #endif
564
565         /* TCP/TLS connections are associated with external protocols, and
566          * should not be allowed to execute 'dangerous' functions. This may
567          * need to be pushed down into the individual protocol handlers, but
568          * this seems like a good general policy.
569          */
570         if (ast_thread_inhibit_escalations()) {
571                 ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
572                 ast_tcptls_close_session_file(tcptls_session);
573                 ao2_ref(tcptls_session, -1);
574                 return NULL;
575         }
576
577         tcptls_session->stream_cookie = tcptls_stream_alloc();
578         if (!tcptls_session->stream_cookie) {
579                 ast_tcptls_close_session_file(tcptls_session);
580                 ao2_ref(tcptls_session, -1);
581                 return NULL;
582         }
583
584         /*
585         * open a FILE * as appropriate.
586         */
587         if (!tcptls_session->parent->tls_cfg) {
588                 tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie, NULL,
589                         tcptls_session->fd, -1);
590                 if (tcptls_session->f) {
591                         if (setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
592                                 ast_tcptls_close_session_file(tcptls_session);
593                         }
594                 }
595         }
596 #ifdef DO_SSL
597         else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
598                 SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
599                 if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
600                         ast_log(LOG_ERROR, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
601                 } else if ((tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie,
602                         tcptls_session->ssl, tcptls_session->fd, -1))) {
603                         if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
604                                 || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
605                                 X509 *peer;
606                                 long res;
607                                 peer = SSL_get_peer_certificate(tcptls_session->ssl);
608                                 if (!peer) {
609                                         ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
610                                         ast_tcptls_close_session_file(tcptls_session);
611                                         ao2_ref(tcptls_session, -1);
612                                         return NULL;
613                                 }
614
615                                 res = SSL_get_verify_result(tcptls_session->ssl);
616                                 if (res != X509_V_OK) {
617                                         ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
618                                         X509_free(peer);
619                                         ast_tcptls_close_session_file(tcptls_session);
620                                         ao2_ref(tcptls_session, -1);
621                                         return NULL;
622                                 }
623                                 if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
624                                         ASN1_STRING *str;
625                                         unsigned char *str2;
626                                         X509_NAME *name = X509_get_subject_name(peer);
627                                         int pos = -1;
628                                         int found = 0;
629
630                                         for (;;) {
631                                                 /* Walk the certificate to check all available "Common Name" */
632                                                 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
633                                                 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
634                                                 if (pos < 0) {
635                                                         break;
636                                                 }
637                                                 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
638                                                 ASN1_STRING_to_UTF8(&str2, str);
639                                                 if (str2) {
640                                                         if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2)) {
641                                                                 found = 1;
642                                                         }
643                                                         ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
644                                                         OPENSSL_free(str2);
645                                                 }
646                                                 if (found) {
647                                                         break;
648                                                 }
649                                         }
650                                         if (!found) {
651                                                 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
652                                                 X509_free(peer);
653                                                 ast_tcptls_close_session_file(tcptls_session);
654                                                 ao2_ref(tcptls_session, -1);
655                                                 return NULL;
656                                         }
657                                 }
658                                 X509_free(peer);
659                         }
660                 }
661                 if (!tcptls_session->f) {       /* no success opening descriptor stacking */
662                         SSL_free(tcptls_session->ssl);
663                 }
664         }
665 #endif /* DO_SSL */
666
667         if (!tcptls_session->f) {
668                 ast_tcptls_close_session_file(tcptls_session);
669                 ast_log(LOG_WARNING, "FILE * open failed!\n");
670 #ifndef DO_SSL
671                 if (tcptls_session->parent->tls_cfg) {
672                         ast_log(LOG_ERROR, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
673                 }
674 #endif
675                 ao2_ref(tcptls_session, -1);
676                 return NULL;
677         }
678
679         if (tcptls_session->parent->worker_fn) {
680                 return tcptls_session->parent->worker_fn(tcptls_session);
681         } else {
682                 return tcptls_session;
683         }
684 }
685
686 void *ast_tcptls_server_root(void *data)
687 {
688         struct ast_tcptls_session_args *desc = data;
689         int fd;
690         struct ast_sockaddr addr;
691         struct ast_tcptls_session_instance *tcptls_session;
692         pthread_t launched;
693
694         for (;;) {
695                 int i, flags;
696
697                 if (desc->periodic_fn) {
698                         desc->periodic_fn(desc);
699                 }
700                 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
701                 if (i <= 0) {
702                         continue;
703                 }
704                 fd = ast_accept(desc->accept_fd, &addr);
705                 if (fd < 0) {
706                         if ((errno != EAGAIN) && (errno != EINTR)) {
707                                 ast_log(LOG_ERROR, "Accept failed: %s\n", strerror(errno));
708                         }
709                         continue;
710                 }
711                 tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
712                 if (!tcptls_session) {
713                         ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
714                         if (close(fd)) {
715                                 ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
716                         }
717                         continue;
718                 }
719
720                 tcptls_session->overflow_buf = ast_str_create(128);
721                 flags = fcntl(fd, F_GETFL);
722                 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
723                 tcptls_session->fd = fd;
724                 tcptls_session->parent = desc;
725                 ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
726
727                 tcptls_session->client = 0;
728
729                 /* This thread is now the only place that controls the single ref to tcptls_session */
730                 if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
731                         ast_log(LOG_ERROR, "Unable to launch helper thread: %s\n", strerror(errno));
732                         ast_tcptls_close_session_file(tcptls_session);
733                         ao2_ref(tcptls_session, -1);
734                 }
735         }
736         return NULL;
737 }
738
739 static int __ssl_setup(struct ast_tls_config *cfg, int client)
740 {
741 #ifndef DO_SSL
742         cfg->enabled = 0;
743         return 0;
744 #else
745         if (!cfg->enabled) {
746                 return 0;
747         }
748
749         /* Get rid of an old SSL_CTX since we're about to
750          * allocate a new one
751          */
752         if (cfg->ssl_ctx) {
753                 SSL_CTX_free(cfg->ssl_ctx);
754                 cfg->ssl_ctx = NULL;
755         }
756
757         if (client) {
758 #ifndef OPENSSL_NO_SSL2
759                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
760                         cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
761                 } else
762 #endif
763                 if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
764                         cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
765                 } else if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
766                         cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
767                 } else {
768                         /* SSLv23_client_method() sends SSLv2, this was the original
769                          * default for ssl clients before the option was given to
770                          * pick what protocol a client should use.  In order not
771                          * to break expected behavior it remains the default. */
772                         cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
773                 }
774         } else {
775                 /* SSLv23_server_method() supports TLSv1, SSLv2, and SSLv3 inbound connections. */
776                 cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
777         }
778
779         if (!cfg->ssl_ctx) {
780                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
781                 cfg->enabled = 0;
782                 return 0;
783         }
784
785         SSL_CTX_set_verify(cfg->ssl_ctx,
786                 ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
787                 NULL);
788
789         if (!ast_strlen_zero(cfg->certfile)) {
790                 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
791                 if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
792                         if (!client) {
793                                 /* Clients don't need a certificate, but if its setup we can use it */
794                                 ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
795                                 cfg->enabled = 0;
796                                 SSL_CTX_free(cfg->ssl_ctx);
797                                 cfg->ssl_ctx = NULL;
798                                 return 0;
799                         }
800                 }
801                 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
802                         if (!client) {
803                                 /* Clients don't need a private key, but if its setup we can use it */
804                                 ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
805                                 cfg->enabled = 0;
806                                 SSL_CTX_free(cfg->ssl_ctx);
807                                 cfg->ssl_ctx = NULL;
808                                 return 0;
809                         }
810                 }
811         }
812         if (!ast_strlen_zero(cfg->cipher)) {
813                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
814                         if (!client) {
815                                 ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
816                                 cfg->enabled = 0;
817                                 SSL_CTX_free(cfg->ssl_ctx);
818                                 cfg->ssl_ctx = NULL;
819                                 return 0;
820                         }
821                 }
822         }
823         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
824                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
825                         ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
826                 }
827         }
828
829 #ifdef HAVE_OPENSSL_EC
830
831         if (!ast_strlen_zero(cfg->pvtfile)) {
832                 BIO *bio = BIO_new_file(cfg->pvtfile, "r");
833                 if (bio != NULL) {
834                         DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
835                         if (dh != NULL) {
836                                 if (SSL_CTX_set_tmp_dh(cfg->ssl_ctx, dh)) {
837                                         long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
838                                         options = SSL_CTX_set_options(cfg->ssl_ctx, options);
839                                         ast_verb(2, "TLS/SSL DH initialized, PFS cipher-suites enabled\n");
840                                 }
841                                 DH_free(dh);
842                         }
843                         BIO_free(bio);
844                 }
845         }
846         #ifndef SSL_CTRL_SET_ECDH_AUTO
847                 #define SSL_CTRL_SET_ECDH_AUTO 94
848         #endif
849         /* SSL_CTX_set_ecdh_auto(cfg->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
850         if (SSL_CTX_ctrl(cfg->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
851                 ast_verb(2, "TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
852         } else {
853                 /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
854                 EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
855                 if (ecdh != NULL) {
856                         if (SSL_CTX_set_tmp_ecdh(cfg->ssl_ctx, ecdh)) {
857                                 ast_verb(2, "TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
858                         }
859                         EC_KEY_free(ecdh);
860                 }
861         }
862
863 #endif /* #ifdef HAVE_OPENSSL_EC */
864
865         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 */
866         return 1;
867 #endif
868 }
869
870 int ast_ssl_setup(struct ast_tls_config *cfg)
871 {
872         return __ssl_setup(cfg, 0);
873 }
874
875 void ast_ssl_teardown(struct ast_tls_config *cfg)
876 {
877 #ifdef DO_SSL
878         if (cfg->ssl_ctx) {
879                 SSL_CTX_free(cfg->ssl_ctx);
880                 cfg->ssl_ctx = NULL;
881         }
882 #endif
883 }
884
885 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
886 {
887         struct ast_tcptls_session_args *desc;
888         int flags;
889
890         if (!(desc = tcptls_session->parent)) {
891                 goto client_start_error;
892         }
893
894         if (ast_connect(desc->accept_fd, &desc->remote_address)) {
895                 ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
896                         desc->name,
897                         ast_sockaddr_stringify(&desc->remote_address),
898                         strerror(errno));
899                 goto client_start_error;
900         }
901
902         flags = fcntl(desc->accept_fd, F_GETFL);
903         fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
904
905         if (desc->tls_cfg) {
906                 desc->tls_cfg->enabled = 1;
907                 __ssl_setup(desc->tls_cfg, 1);
908         }
909
910         return handle_tcptls_connection(tcptls_session);
911
912 client_start_error:
913         if (desc) {
914                 close(desc->accept_fd);
915                 desc->accept_fd = -1;
916         }
917         ao2_ref(tcptls_session, -1);
918         return NULL;
919
920 }
921
922 struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
923 {
924         int x = 1;
925         struct ast_tcptls_session_instance *tcptls_session = NULL;
926
927         /* Do nothing if nothing has changed */
928         if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
929                 ast_debug(1, "Nothing changed in %s\n", desc->name);
930                 return NULL;
931         }
932
933         /* If we return early, there is no connection */
934         ast_sockaddr_setnull(&desc->old_address);
935
936         if (desc->accept_fd != -1) {
937                 close(desc->accept_fd);
938         }
939
940         desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
941                                  AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
942         if (desc->accept_fd < 0) {
943                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
944                         desc->name, strerror(errno));
945                 return NULL;
946         }
947
948         /* if a local address was specified, bind to it so the connection will
949            originate from the desired address */
950         if (!ast_sockaddr_isnull(&desc->local_address)) {
951                 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
952                 if (ast_bind(desc->accept_fd, &desc->local_address)) {
953                         ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
954                                 desc->name,
955                                 ast_sockaddr_stringify(&desc->local_address),
956                                 strerror(errno));
957                         goto error;
958                 }
959         }
960
961         if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor))) {
962                 goto error;
963         }
964
965         tcptls_session->overflow_buf = ast_str_create(128);
966         tcptls_session->client = 1;
967         tcptls_session->fd = desc->accept_fd;
968         tcptls_session->parent = desc;
969         tcptls_session->parent->worker_fn = NULL;
970         ast_sockaddr_copy(&tcptls_session->remote_address,
971                           &desc->remote_address);
972
973         /* Set current info */
974         ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
975         return tcptls_session;
976
977 error:
978         close(desc->accept_fd);
979         desc->accept_fd = -1;
980         if (tcptls_session) {
981                 ao2_ref(tcptls_session, -1);
982         }
983         return NULL;
984 }
985
986 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
987 {
988         int flags;
989         int x = 1;
990
991         /* Do nothing if nothing has changed */
992         if (!ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
993                 ast_debug(1, "Nothing changed in %s\n", desc->name);
994                 return;
995         }
996
997         /* If we return early, there is no one listening */
998         ast_sockaddr_setnull(&desc->old_address);
999
1000         /* Shutdown a running server if there is one */
1001         if (desc->master != AST_PTHREADT_NULL) {
1002                 pthread_cancel(desc->master);
1003                 pthread_kill(desc->master, SIGURG);
1004                 pthread_join(desc->master, NULL);
1005         }
1006
1007         if (desc->accept_fd != -1) {
1008                 close(desc->accept_fd);
1009         }
1010
1011         /* If there's no new server, stop here */
1012         if (ast_sockaddr_isnull(&desc->local_address)) {
1013                 ast_debug(2, "Server disabled:  %s\n", desc->name);
1014                 return;
1015         }
1016
1017         desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
1018                                  AF_INET6 : AF_INET, SOCK_STREAM, 0);
1019         if (desc->accept_fd < 0) {
1020                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
1021                 return;
1022         }
1023
1024         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1025         if (ast_bind(desc->accept_fd, &desc->local_address)) {
1026                 ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
1027                         desc->name,
1028                         ast_sockaddr_stringify(&desc->local_address),
1029                         strerror(errno));
1030                 goto error;
1031         }
1032         if (listen(desc->accept_fd, 10)) {
1033                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
1034                 goto error;
1035         }
1036         flags = fcntl(desc->accept_fd, F_GETFL);
1037         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
1038         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
1039                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
1040                         desc->name,
1041                         ast_sockaddr_stringify(&desc->local_address),
1042                         strerror(errno));
1043                 goto error;
1044         }
1045
1046         /* Set current info */
1047         ast_sockaddr_copy(&desc->old_address, &desc->local_address);
1048
1049         return;
1050
1051 error:
1052         close(desc->accept_fd);
1053         desc->accept_fd = -1;
1054 }
1055
1056 void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
1057 {
1058         if (tcptls_session->f) {
1059                 fflush(tcptls_session->f);
1060                 if (fclose(tcptls_session->f)) {
1061                         ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
1062                 }
1063                 tcptls_session->f = NULL;
1064                 tcptls_session->fd = -1;
1065         } else if (tcptls_session->fd != -1) {
1066                 /*
1067                  * Issuing shutdown() is necessary here to avoid a race
1068                  * condition where the last data written may not appear
1069                  * in the TCP stream.  See ASTERISK-23548
1070                  */
1071                 shutdown(tcptls_session->fd, SHUT_RDWR);
1072                 if (close(tcptls_session->fd)) {
1073                         ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
1074                 }
1075                 tcptls_session->fd = -1;
1076         } else {
1077                 ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
1078         }
1079 }
1080
1081 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
1082 {
1083         if (desc->master != AST_PTHREADT_NULL) {
1084                 pthread_cancel(desc->master);
1085                 pthread_kill(desc->master, SIGURG);
1086                 pthread_join(desc->master, NULL);
1087                 desc->master = AST_PTHREADT_NULL;
1088         }
1089         if (desc->accept_fd != -1) {
1090                 close(desc->accept_fd);
1091         }
1092         desc->accept_fd = -1;
1093         ast_debug(2, "Stopped server :: %s\n", desc->name);
1094 }
1095
1096 int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
1097 {
1098         if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
1099                 tls_cfg->enabled = ast_true(value) ? 1 : 0;
1100         } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
1101                 ast_free(tls_cfg->certfile);
1102                 tls_cfg->certfile = ast_strdup(value);
1103         } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
1104                 ast_free(tls_cfg->pvtfile);
1105                 tls_cfg->pvtfile = ast_strdup(value);
1106         } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
1107                 ast_free(tls_cfg->cipher);
1108                 tls_cfg->cipher = ast_strdup(value);
1109         } else if (!strcasecmp(varname, "tlscafile")) {
1110                 ast_free(tls_cfg->cafile);
1111                 tls_cfg->cafile = ast_strdup(value);
1112         } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
1113                 ast_free(tls_cfg->capath);
1114                 tls_cfg->capath = ast_strdup(value);
1115         } else if (!strcasecmp(varname, "tlsverifyclient")) {
1116                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
1117         } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
1118                 ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
1119         } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
1120                 if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
1121                         ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
1122         } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
1123                 if (!strcasecmp(value, "tlsv1")) {
1124                         ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1125                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1126                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1127                 } else if (!strcasecmp(value, "sslv3")) {
1128                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1129                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1130                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1131                 } else if (!strcasecmp(value, "sslv2")) {
1132                         ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
1133                         ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
1134                         ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
1135                 }
1136         } else {
1137                 return -1;
1138         }
1139
1140         return 0;
1141 }