2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2007 - 2008, Digium, Inc.
6 * Luigi Rizzo (TCP and TLS server code)
7 * Brett Bryant <brettbryant@gmail.com> (updated for client support)
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.
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.
22 * \brief Code to support TCP and TLS server/client
25 * \author Brett Bryant <brettbryant@gmail.com>
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36 #include <sys/signal.h>
38 #include "asterisk/compat.h"
39 #include "asterisk/tcptls.h"
40 #include "asterisk/http.h"
41 #include "asterisk/utils.h"
42 #include "asterisk/strings.h"
43 #include "asterisk/options.h"
44 #include "asterisk/manager.h"
45 #include "asterisk/astobj2.h"
48 * replacement read/write functions for SSL support.
49 * We use wrappers rather than SSL_read/SSL_write directly so
50 * we can put in some debugging.
54 static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
56 int i = SSL_read(cookie, buf, len-1);
60 ast_verb(0, "ssl read size %d returns %d <%s>\n", (int)len, i, buf);
65 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
68 char *s = alloca(len+1);
71 ast_verb(0, "ssl write size %d <%s>\n", (int)len, s);
73 return SSL_write(cookie, buf, len);
76 static int ssl_close(void *cookie)
78 close(SSL_get_fd(cookie));
85 HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *tcptls_session, void *buf, size_t count)
87 if (tcptls_session->fd == -1) {
88 ast_log(LOG_ERROR, "server_read called with an fd of -1\n");
94 if (tcptls_session->ssl)
95 return ssl_read(tcptls_session->ssl, buf, count);
97 return read(tcptls_session->fd, buf, count);
100 HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t count)
102 if (tcptls_session->fd == -1) {
103 ast_log(LOG_ERROR, "server_write called with an fd of -1\n");
109 if (tcptls_session->ssl)
110 return ssl_write(tcptls_session->ssl, buf, count);
112 return write(tcptls_session->fd, buf, count);
115 static void session_instance_destructor(void *obj)
117 struct ast_tcptls_session_instance *i = obj;
118 ast_mutex_destroy(&i->lock);
122 * creates a FILE * from the fd passed by the accept thread.
123 * This operation is potentially expensive (certificate verification),
124 * so we do it in the child thread context.
126 static void *handle_tls_connection(void *data)
128 struct ast_tcptls_session_instance *tcptls_session = data;
130 int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
136 * open a FILE * as appropriate.
138 if (!tcptls_session->parent->tls_cfg) {
139 tcptls_session->f = fdopen(tcptls_session->fd, "w+");
140 setvbuf(tcptls_session->f, NULL, _IONBF, 0);
143 else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
144 SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
145 if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
146 ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
148 #if defined(HAVE_FUNOPEN) /* the BSD interface */
149 tcptls_session->f = funopen(tcptls_session->ssl, ssl_read, ssl_write, NULL, ssl_close);
151 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
152 static const cookie_io_functions_t cookie_funcs = {
153 ssl_read, ssl_write, NULL, ssl_close
155 tcptls_session->f = fopencookie(tcptls_session->ssl, "w+", cookie_funcs);
157 /* could add other methods here */
158 ast_debug(2, "no tcptls_session->f methods attempted!");
160 if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
161 || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
164 peer = SSL_get_peer_certificate(tcptls_session->ssl);
166 ast_log(LOG_WARNING, "No peer SSL certificate\n");
167 res = SSL_get_verify_result(tcptls_session->ssl);
168 if (res != X509_V_OK)
169 ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
170 if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
173 X509_NAME *name = X509_get_subject_name(peer);
178 /* Walk the certificate to check all available "Common Name" */
179 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
180 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
183 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
184 ASN1_STRING_to_UTF8(&str2, str);
186 if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2))
188 ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
195 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
198 fclose(tcptls_session->f);
206 if (!tcptls_session->f) /* no success opening descriptor stacking */
207 SSL_free(tcptls_session->ssl);
211 if (!tcptls_session->f) {
212 close(tcptls_session->fd);
213 ast_log(LOG_WARNING, "FILE * open failed!\n");
214 ao2_ref(tcptls_session, -1);
218 if (tcptls_session && tcptls_session->parent->worker_fn)
219 return tcptls_session->parent->worker_fn(tcptls_session);
221 return tcptls_session;
224 void *ast_tcptls_server_root(void *data)
226 struct ast_tcptls_session_args *desc = data;
228 struct sockaddr_in sin;
230 struct ast_tcptls_session_instance *tcptls_session;
236 if (desc->periodic_fn)
237 desc->periodic_fn(desc);
238 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
241 sinlen = sizeof(sin);
242 fd = accept(desc->accept_fd, (struct sockaddr *) &sin, &sinlen);
244 if ((errno != EAGAIN) && (errno != EINTR))
245 ast_log(LOG_WARNING, "Accept failed: %s\n", strerror(errno));
248 tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
249 if (!tcptls_session) {
250 ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
255 ast_mutex_init(&tcptls_session->lock);
257 flags = fcntl(fd, F_GETFL);
258 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
259 tcptls_session->fd = fd;
260 tcptls_session->parent = desc;
261 memcpy(&tcptls_session->remote_address, &sin, sizeof(tcptls_session->remote_address));
263 tcptls_session->client = 0;
265 if (ast_pthread_create_detached_background(&launched, NULL, handle_tls_connection, tcptls_session)) {
266 ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
267 close(tcptls_session->fd);
268 ao2_ref(tcptls_session, -1);
274 static int __ssl_setup(struct ast_tls_config *cfg, int client)
283 SSL_load_error_strings();
284 SSLeay_add_ssl_algorithms();
286 if (!(cfg->ssl_ctx = SSL_CTX_new( client ? SSLv23_client_method() : SSLv23_server_method() ))) {
287 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
291 if (!ast_strlen_zero(cfg->certfile)) {
292 char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
293 if (SSL_CTX_use_certificate_file(cfg->ssl_ctx, cfg->certfile, SSL_FILETYPE_PEM) == 0) {
295 /* Clients don't need a certificate, but if its setup we can use it */
296 ast_verb(0, "SSL error loading cert file. <%s>", cfg->certfile);
302 if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
304 /* Clients don't need a private key, but if its setup we can use it */
305 ast_verb(0, "SSL error loading private key file. <%s>", tmpprivate);
312 if (!ast_strlen_zero(cfg->cipher)) {
313 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
315 ast_verb(0, "SSL cipher error <%s>", cfg->cipher);
322 if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
323 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0)
324 ast_verb(0, "SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
327 ast_verb(0, "SSL certificate ok\n");
332 int ast_ssl_setup(struct ast_tls_config *cfg)
334 return __ssl_setup(cfg, 0);
337 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_args *desc)
341 struct ast_tcptls_session_instance *tcptls_session = NULL;
343 /* Do nothing if nothing has changed */
344 if (!memcmp(&desc->old_address, &desc->remote_address, sizeof(desc->old_address))) {
345 ast_debug(1, "Nothing changed in %s\n", desc->name);
349 desc->old_address = desc->remote_address;
351 if (desc->accept_fd != -1)
352 close(desc->accept_fd);
354 desc->accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
355 if (desc->accept_fd < 0) {
356 ast_log(LOG_WARNING, "Unable to allocate socket for %s: %s\n",
357 desc->name, strerror(errno));
361 /* if a local address was specified, bind to it so the connection will
362 originate from the desired address */
363 if (desc->local_address.sin_family != 0) {
364 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
365 if (bind(desc->accept_fd, (struct sockaddr *) &desc->local_address, sizeof(desc->local_address))) {
366 ast_log(LOG_ERROR, "Unable to bind %s to %s:%d: %s\n",
368 ast_inet_ntoa(desc->local_address.sin_addr), ntohs(desc->local_address.sin_port),
374 if (connect(desc->accept_fd, (const struct sockaddr *) &desc->remote_address, sizeof(desc->remote_address))) {
375 ast_log(LOG_ERROR, "Unable to connect %s to %s:%d: %s\n",
377 ast_inet_ntoa(desc->remote_address.sin_addr), ntohs(desc->remote_address.sin_port),
382 if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor)))
385 ast_mutex_init(&tcptls_session->lock);
387 flags = fcntl(desc->accept_fd, F_GETFL);
388 fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
390 tcptls_session->fd = desc->accept_fd;
391 tcptls_session->parent = desc;
392 tcptls_session->parent->worker_fn = NULL;
393 memcpy(&tcptls_session->remote_address, &desc->remote_address, sizeof(tcptls_session->remote_address));
395 tcptls_session->client = 1;
398 desc->tls_cfg->enabled = 1;
399 __ssl_setup(desc->tls_cfg, 1);
402 ao2_ref(tcptls_session, +1);
403 if (!handle_tls_connection(tcptls_session))
406 return tcptls_session;
409 close(desc->accept_fd);
410 desc->accept_fd = -1;
412 ao2_ref(tcptls_session, -1);
416 void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
421 /* Do nothing if nothing has changed */
422 if (!memcmp(&desc->old_address, &desc->local_address, sizeof(desc->old_address))) {
423 ast_debug(1, "Nothing changed in %s\n", desc->name);
427 desc->old_address = desc->local_address;
429 /* Shutdown a running server if there is one */
430 if (desc->master != AST_PTHREADT_NULL) {
431 pthread_cancel(desc->master);
432 pthread_kill(desc->master, SIGURG);
433 pthread_join(desc->master, NULL);
436 if (desc->accept_fd != -1)
437 close(desc->accept_fd);
439 /* If there's no new server, stop here */
440 if (desc->local_address.sin_family == 0) {
441 ast_debug(2, "Server disabled: %s\n", desc->name);
445 desc->accept_fd = socket(AF_INET, SOCK_STREAM, 0);
446 if (desc->accept_fd < 0) {
447 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
451 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
452 if (bind(desc->accept_fd, (struct sockaddr *) &desc->local_address, sizeof(desc->local_address))) {
453 ast_log(LOG_ERROR, "Unable to bind %s to %s:%d: %s\n",
455 ast_inet_ntoa(desc->local_address.sin_addr), ntohs(desc->local_address.sin_port),
459 if (listen(desc->accept_fd, 10)) {
460 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
463 flags = fcntl(desc->accept_fd, F_GETFL);
464 fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
465 if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
466 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s:%d: %s\n",
468 ast_inet_ntoa(desc->local_address.sin_addr), ntohs(desc->local_address.sin_port),
475 close(desc->accept_fd);
476 desc->accept_fd = -1;
479 void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
481 if (desc->master != AST_PTHREADT_NULL) {
482 pthread_cancel(desc->master);
483 pthread_kill(desc->master, SIGURG);
484 pthread_join(desc->master, NULL);
486 if (desc->accept_fd != -1)
487 close(desc->accept_fd);
488 desc->accept_fd = -1;
489 ast_debug(2, "Stopped server :: %s\n", desc->name);