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"
47 * replacement read/write functions for SSL support.
48 * We use wrappers rather than SSL_read/SSL_write directly so
49 * we can put in some debugging.
53 static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
55 int i = SSL_read(cookie, buf, len-1);
59 ast_verb(0, "ssl read size %d returns %d <%s>\n", (int)len, i, buf);
64 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
67 char *s = alloca(len+1);
70 ast_verb(0, "ssl write size %d <%s>\n", (int)len, s);
72 return SSL_write(cookie, buf, len);
75 static int ssl_close(void *cookie)
77 close(SSL_get_fd(cookie));
84 HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *ser, void *buf, size_t count)
87 ast_log(LOG_ERROR, "server_read called with an fd of -1\n");
94 return ssl_read(ser->ssl, buf, count);
96 return read(ser->fd, buf, count);
99 HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *ser, void *buf, size_t count)
102 ast_log(LOG_ERROR, "server_write called with an fd of -1\n");
109 return ssl_write(ser->ssl, buf, count);
111 return write(ser->fd, buf, count);
114 static void session_instance_destructor(void *obj)
116 struct ast_tcptls_session_instance *i = obj;
117 ast_mutex_destroy(&i->lock);
120 void *ast_tcptls_server_root(void *data)
122 struct server_args *desc = data;
124 struct sockaddr_in sin;
126 struct ast_tcptls_session_instance *ser;
132 if (desc->periodic_fn)
133 desc->periodic_fn(desc);
134 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
137 sinlen = sizeof(sin);
138 fd = accept(desc->accept_fd, (struct sockaddr *)&sin, &sinlen);
140 if ((errno != EAGAIN) && (errno != EINTR))
141 ast_log(LOG_WARNING, "Accept failed: %s\n", strerror(errno));
144 ser = ao2_alloc(sizeof(*ser), session_instance_destructor);
146 ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
151 ast_mutex_init(&ser->lock);
153 flags = fcntl(fd, F_GETFL);
154 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
157 memcpy(&ser->requestor, &sin, sizeof(ser->requestor));
161 if (ast_pthread_create_detached_background(&launched, NULL, ast_make_file_from_fd, ser)) {
162 ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
170 static int __ssl_setup(struct ast_tls_config *cfg, int client)
179 SSL_load_error_strings();
180 SSLeay_add_ssl_algorithms();
182 if (!(cfg->ssl_ctx = SSL_CTX_new( client ? SSLv23_client_method() : SSLv23_server_method() ))) {
183 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
187 if (!ast_strlen_zero(cfg->certfile)) {
188 if (SSL_CTX_use_certificate_file(cfg->ssl_ctx, cfg->certfile, SSL_FILETYPE_PEM) == 0 ||
189 SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, cfg->certfile, SSL_FILETYPE_PEM) == 0 ||
190 SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 ) {
192 /* Clients don't need a certificate, but if its setup we can use it */
193 ast_verb(0, "SSL cert error <%s>", cfg->certfile);
200 if (!ast_strlen_zero(cfg->cipher)) {
201 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
203 ast_verb(0, "SSL cipher error <%s>", cfg->cipher);
210 if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
211 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0)
212 ast_verb(0, "SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
215 ast_verb(0, "SSL certificate ok\n");
220 int ast_ssl_setup(struct ast_tls_config *cfg)
222 return __ssl_setup(cfg, 0);
225 /*! \brief A generic client routine for a TCP client
226 * and starts a thread for handling accept()
228 struct ast_tcptls_session_instance *ast_tcptls_client_start(struct server_args *desc)
231 struct ast_tcptls_session_instance *ser = NULL;
233 /* Do nothing if nothing has changed */
234 if(!memcmp(&desc->oldsin, &desc->sin, sizeof(desc->oldsin))) {
235 ast_debug(1, "Nothing changed in %s\n", desc->name);
239 desc->oldsin = desc->sin;
241 if (desc->accept_fd != -1)
242 close(desc->accept_fd);
244 desc->accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
245 if (desc->accept_fd < 0) {
246 ast_log(LOG_WARNING, "Unable to allocate socket for %s: %s\n",
247 desc->name, strerror(errno));
251 if (connect(desc->accept_fd, (const struct sockaddr *)&desc->sin, sizeof(desc->sin))) {
252 ast_log(LOG_ERROR, "Unable to connect %s to %s:%d: %s\n",
254 ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
259 if (!(ser = ao2_alloc(sizeof(*ser), session_instance_destructor)))
262 ast_mutex_init(&ser->lock);
264 flags = fcntl(desc->accept_fd, F_GETFL);
265 fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
267 ser->fd = desc->accept_fd;
269 ser->parent->worker_fn = NULL;
270 memcpy(&ser->requestor, &desc->sin, sizeof(ser->requestor));
275 desc->tls_cfg->enabled = 1;
276 __ssl_setup(desc->tls_cfg, 1);
280 if (!ast_make_file_from_fd(ser))
286 close(desc->accept_fd);
287 desc->accept_fd = -1;
294 * This is a generic (re)start routine for a TCP server,
295 * which does the socket/bind/listen and starts a thread for handling
298 void ast_tcptls_server_start(struct server_args *desc)
303 /* Do nothing if nothing has changed */
304 if (!memcmp(&desc->oldsin, &desc->sin, sizeof(desc->oldsin))) {
305 ast_debug(1, "Nothing changed in %s\n", desc->name);
309 desc->oldsin = desc->sin;
311 /* Shutdown a running server if there is one */
312 if (desc->master != AST_PTHREADT_NULL) {
313 pthread_cancel(desc->master);
314 pthread_kill(desc->master, SIGURG);
315 pthread_join(desc->master, NULL);
318 if (desc->accept_fd != -1)
319 close(desc->accept_fd);
321 /* If there's no new server, stop here */
322 if (desc->sin.sin_family == 0) {
323 ast_debug(2, "Server disabled: %s\n", desc->name);
327 desc->accept_fd = socket(AF_INET, SOCK_STREAM, 0);
328 if (desc->accept_fd < 0) {
329 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
333 setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
334 if (bind(desc->accept_fd, (struct sockaddr *)&desc->sin, sizeof(desc->sin))) {
335 ast_log(LOG_ERROR, "Unable to bind %s to %s:%d: %s\n",
337 ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
341 if (listen(desc->accept_fd, 10)) {
342 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
345 flags = fcntl(desc->accept_fd, F_GETFL);
346 fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
347 if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
348 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s:%d: %s\n",
350 ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
357 close(desc->accept_fd);
358 desc->accept_fd = -1;
361 /*! \brief Shutdown a running server if there is one */
362 void ast_tcptls_server_stop(struct server_args *desc)
364 if (desc->master != AST_PTHREADT_NULL) {
365 pthread_cancel(desc->master);
366 pthread_kill(desc->master, SIGURG);
367 pthread_join(desc->master, NULL);
369 if (desc->accept_fd != -1)
370 close(desc->accept_fd);
371 desc->accept_fd = -1;
372 ast_debug(2, "Stopped server :: %s\n", desc->name);
376 * creates a FILE * from the fd passed by the accept thread.
377 * This operation is potentially expensive (certificate verification),
378 * so we do it in the child thread context.
380 void *ast_make_file_from_fd(void *data)
382 struct ast_tcptls_session_instance *ser = data;
384 int (*ssl_setup)(SSL *) = (ser->client) ? SSL_connect : SSL_accept;
390 * open a FILE * as appropriate.
392 if (!ser->parent->tls_cfg)
393 ser->f = fdopen(ser->fd, "w+");
395 else if ( (ser->ssl = SSL_new(ser->parent->tls_cfg->ssl_ctx)) ) {
396 SSL_set_fd(ser->ssl, ser->fd);
397 if ((ret = ssl_setup(ser->ssl)) <= 0) {
398 ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
400 #if defined(HAVE_FUNOPEN) /* the BSD interface */
401 ser->f = funopen(ser->ssl, ssl_read, ssl_write, NULL, ssl_close);
403 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
404 static const cookie_io_functions_t cookie_funcs = {
405 ssl_read, ssl_write, NULL, ssl_close
407 ser->f = fopencookie(ser->ssl, "w+", cookie_funcs);
409 /* could add other methods here */
410 ast_debug(2, "no ser->f methods attempted!");
412 if ((ser->client && !ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
413 || (!ser->client && ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
416 peer = SSL_get_peer_certificate(ser->ssl);
418 ast_log(LOG_WARNING, "No peer SSL certificate\n");
419 res = SSL_get_verify_result(ser->ssl);
420 if (res != X509_V_OK)
421 ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
422 if (!ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
425 X509_NAME *name = X509_get_subject_name(peer);
430 /* Walk the certificate to check all available "Common Name" */
431 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
432 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
435 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
436 ASN1_STRING_to_UTF8(&str2, str);
438 if (!strcasecmp(ser->parent->hostname, (char *) str2))
440 ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", ser->parent->hostname, str2);
447 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", ser->parent->hostname);
458 if (!ser->f) /* no success opening descriptor stacking */
465 ast_log(LOG_WARNING, "FILE * open failed!\n");
470 if (ser && ser->parent->worker_fn)
471 return ser->parent->worker_fn(ser);