More public API name changes to use an appropriate ast_ prefix
[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 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #ifdef HAVE_FCNTL_H
33 #include <fcntl.h>
34 #endif
35
36 #include <sys/signal.h>
37
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
46 /*! \brief
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.
50  */
51
52 #ifdef DO_SSL
53 static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
54 {
55         int i = SSL_read(cookie, buf, len-1);
56 #if 0
57         if (i >= 0)
58                 buf[i] = '\0';
59         ast_verb(0, "ssl read size %d returns %d <%s>\n", (int)len, i, buf);
60 #endif
61         return i;
62 }
63
64 static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
65 {
66 #if 0
67         char *s = alloca(len+1);
68         strncpy(s, buf, len);
69         s[len] = '\0';
70         ast_verb(0, "ssl write size %d <%s>\n", (int)len, s);
71 #endif
72         return SSL_write(cookie, buf, len);
73 }
74
75 static int ssl_close(void *cookie)
76 {
77         close(SSL_get_fd(cookie));
78         SSL_shutdown(cookie);
79         SSL_free(cookie);
80         return 0;
81 }
82 #endif  /* DO_SSL */
83
84 HOOK_T ast_tcptls_server_read(struct ast_tcptls_server_instance *ser, void *buf, size_t count)
85 {
86 #ifdef DO_SSL
87         if (ser->ssl)
88                 return ssl_read(ser->ssl, buf, count);
89 #endif
90         return read(ser->fd, buf, count);
91 }
92
93 HOOK_T ast_tcptls_server_write(struct ast_tcptls_server_instance *ser, void *buf, size_t count)
94 {
95 #ifdef DO_SSL
96         if (ser->ssl)
97                 return ssl_write(ser->ssl, buf, count);
98 #endif
99         return write(ser->fd, buf, count);
100 }
101
102 void *ast_tcptls_server_root(void *data)
103 {
104         struct server_args *desc = data;
105         int fd;
106         struct sockaddr_in sin;
107         socklen_t sinlen;
108         struct ast_tcptls_server_instance *ser;
109         pthread_t launched;
110         
111         for (;;) {
112                 int i, flags;
113
114                 if (desc->periodic_fn)
115                         desc->periodic_fn(desc);
116                 i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
117                 if (i <= 0)
118                         continue;
119                 sinlen = sizeof(sin);
120                 fd = accept(desc->accept_fd, (struct sockaddr *)&sin, &sinlen);
121                 if (fd < 0) {
122                         if ((errno != EAGAIN) && (errno != EINTR))
123                                 ast_log(LOG_WARNING, "Accept failed: %s\n", strerror(errno));
124                         continue;
125                 }
126                 ser = ast_calloc(1, sizeof(*ser));
127                 if (!ser) {
128                         ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
129                         close(fd);
130                         continue;
131                 }
132                 flags = fcntl(fd, F_GETFL);
133                 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
134                 ser->fd = fd;
135                 ser->parent = desc;
136                 memcpy(&ser->requestor, &sin, sizeof(ser->requestor));
137
138                 ser->client = 0;
139                         
140                 if (ast_pthread_create_detached_background(&launched, NULL, ast_make_file_from_fd, ser)) {
141                         ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
142                         close(ser->fd);
143                         ast_free(ser);
144                 }
145         }
146         return NULL;
147 }
148
149 static int __ssl_setup(struct ast_tls_config *cfg, int client)
150 {
151 #ifndef DO_SSL
152         cfg->enabled = 0;
153         return 0;
154 #else
155         if (!cfg->enabled)
156                 return 0;
157
158         SSL_load_error_strings();
159         SSLeay_add_ssl_algorithms();
160
161         if (!(cfg->ssl_ctx = SSL_CTX_new( client ? SSLv23_client_method() : SSLv23_server_method() ))) {
162                 ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
163                 cfg->enabled = 0;
164                 return 0;
165         }
166         if (!ast_strlen_zero(cfg->certfile)) {
167                 if (SSL_CTX_use_certificate_file(cfg->ssl_ctx, cfg->certfile, SSL_FILETYPE_PEM) == 0 ||
168                     SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, cfg->certfile, SSL_FILETYPE_PEM) == 0 ||
169                     SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 ) {
170                         if (!client) {
171                                 /* Clients don't need a certificate, but if its setup we can use it */
172                                 ast_verb(0, "SSL cert error <%s>", cfg->certfile);
173                                 sleep(2);
174                                 cfg->enabled = 0;
175                                 return 0;
176                         }
177                 }
178         }
179         if (!ast_strlen_zero(cfg->cipher)) {
180                 if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
181                         if (!client) {
182                                 ast_verb(0, "SSL cipher error <%s>", cfg->cipher);
183                                 sleep(2);
184                                 cfg->enabled = 0;
185                                 return 0;
186                         }
187                 }
188         }
189         if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
190                 if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0)
191                         ast_verb(0, "SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
192         }
193
194         ast_verb(0, "SSL certificate ok\n");
195         return 1;
196 #endif
197 }
198
199 int ast_ssl_setup(struct ast_tls_config *cfg)
200 {
201         return __ssl_setup(cfg, 0);
202 }
203
204 /*! \brief A generic client routine for a TCP client
205  *  and starts a thread for handling accept()
206  */
207 struct ast_tcptls_server_instance *ast_tcptls_client_start(struct server_args *desc)
208 {
209         int flags;
210         struct ast_tcptls_server_instance *ser = NULL;
211
212         /* Do nothing if nothing has changed */
213         if(!memcmp(&desc->oldsin, &desc->sin, sizeof(desc->oldsin))) {
214                 ast_debug(1, "Nothing changed in %s\n", desc->name);
215                 return NULL;
216         }
217
218         desc->oldsin = desc->sin;
219
220         if (desc->accept_fd != -1)
221                 close(desc->accept_fd);
222
223         desc->accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
224         if (desc->accept_fd < 0) {
225                 ast_log(LOG_WARNING, "Unable to allocate socket for %s: %s\n",
226                         desc->name, strerror(errno));
227                 return NULL;
228         }
229
230         if (connect(desc->accept_fd, (const struct sockaddr *)&desc->sin, sizeof(desc->sin))) {
231                 ast_log(LOG_ERROR, "Unable to connect %s to %s:%d: %s\n",
232                         desc->name,
233                         ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
234                         strerror(errno));
235                 goto error;
236         }
237
238         if (!(ser = ast_calloc(1, sizeof(*ser))))
239                 goto error;
240
241         flags = fcntl(desc->accept_fd, F_GETFL);
242         fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
243
244         ser->fd = desc->accept_fd;
245         ser->parent = desc;
246         ser->parent->worker_fn = NULL;
247         memcpy(&ser->requestor, &desc->sin, sizeof(ser->requestor));
248
249         ser->client = 1;
250
251         if (desc->tls_cfg) {
252                 desc->tls_cfg->enabled = 1;
253                 __ssl_setup(desc->tls_cfg, 1);
254         }
255
256         if (!ast_make_file_from_fd(ser))
257                 goto error;
258
259         return ser;
260
261 error:
262         close(desc->accept_fd);
263         desc->accept_fd = -1;
264         if (ser)
265                 ast_free(ser);
266         return NULL;
267 }
268
269 /*! \brief
270  * This is a generic (re)start routine for a TCP server,
271  * which does the socket/bind/listen and starts a thread for handling
272  * accept().
273  */
274 void ast_tcptls_server_start(struct server_args *desc)
275 {
276         int flags;
277         int x = 1;
278         
279         /* Do nothing if nothing has changed */
280         if (!memcmp(&desc->oldsin, &desc->sin, sizeof(desc->oldsin))) {
281                 ast_debug(1, "Nothing changed in %s\n", desc->name);
282                 return;
283         }
284         
285         desc->oldsin = desc->sin;
286         
287         /* Shutdown a running server if there is one */
288         if (desc->master != AST_PTHREADT_NULL) {
289                 pthread_cancel(desc->master);
290                 pthread_kill(desc->master, SIGURG);
291                 pthread_join(desc->master, NULL);
292         }
293         
294         if (desc->accept_fd != -1)
295                 close(desc->accept_fd);
296
297         /* If there's no new server, stop here */
298         if (desc->sin.sin_family == 0)
299                 return;
300
301         desc->accept_fd = socket(AF_INET, SOCK_STREAM, 0);
302         if (desc->accept_fd < 0) {
303                 ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
304                         desc->name, strerror(errno));
305                 return;
306         }
307         
308         setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
309         if (bind(desc->accept_fd, (struct sockaddr *)&desc->sin, sizeof(desc->sin))) {
310                 ast_log(LOG_ERROR, "Unable to bind %s to %s:%d: %s\n",
311                         desc->name,
312                         ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
313                         strerror(errno));
314                 goto error;
315         }
316         if (listen(desc->accept_fd, 10)) {
317                 ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
318                 goto error;
319         }
320         flags = fcntl(desc->accept_fd, F_GETFL);
321         fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
322         if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
323                 ast_log(LOG_ERROR, "Unable to launch thread for %s on %s:%d: %s\n",
324                         desc->name,
325                         ast_inet_ntoa(desc->sin.sin_addr), ntohs(desc->sin.sin_port),
326                         strerror(errno));
327                 goto error;
328         }
329         return;
330
331 error:
332         close(desc->accept_fd);
333         desc->accept_fd = -1;
334 }
335
336 /*! \brief Shutdown a running server if there is one */
337 void ast_tcptls_server_stop(struct server_args *desc)
338 {
339         if (desc->master != AST_PTHREADT_NULL) {
340                 pthread_cancel(desc->master);
341                 pthread_kill(desc->master, SIGURG);
342                 pthread_join(desc->master, NULL);
343         }
344         if (desc->accept_fd != -1)
345                 close(desc->accept_fd);
346         desc->accept_fd = -1;
347 }
348
349 /*! \brief
350 * creates a FILE * from the fd passed by the accept thread.
351 * This operation is potentially expensive (certificate verification),
352 * so we do it in the child thread context.
353 */
354 void *ast_make_file_from_fd(void *data)
355 {
356         struct ast_tcptls_server_instance *ser = data;
357 #ifdef DO_SSL
358         int (*ssl_setup)(SSL *) = (ser->client) ? SSL_connect : SSL_accept;
359         int ret;
360         char err[256];
361 #endif
362
363         /*
364         * open a FILE * as appropriate.
365         */
366         if (!ser->parent->tls_cfg)
367                 ser->f = fdopen(ser->fd, "w+");
368 #ifdef DO_SSL
369         else if ( (ser->ssl = SSL_new(ser->parent->tls_cfg->ssl_ctx)) ) {
370                 SSL_set_fd(ser->ssl, ser->fd);
371                 if ((ret = ssl_setup(ser->ssl)) <= 0) {
372                         ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
373                 } else {
374 #if defined(HAVE_FUNOPEN)       /* the BSD interface */
375                         ser->f = funopen(ser->ssl, ssl_read, ssl_write, NULL, ssl_close);
376
377 #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
378                         static const cookie_io_functions_t cookie_funcs = {
379                                 ssl_read, ssl_write, NULL, ssl_close
380                         };
381                         ser->f = fopencookie(ser->ssl, "w+", cookie_funcs);
382 #else
383                         /* could add other methods here */
384                         ast_debug(2, "no ser->f methods attempted!");
385 #endif
386                         if ((ser->client && !ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
387                                 || (!ser->client && ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
388                                 X509 *peer;
389                                 long res;
390                                 peer = SSL_get_peer_certificate(ser->ssl);
391                                 if (!peer)
392                                         ast_log(LOG_WARNING, "No peer SSL certificate\n");
393                                 res = SSL_get_verify_result(ser->ssl);
394                                 if (res != X509_V_OK)
395                                         ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
396                                 if (!ast_test_flag(&ser->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
397                                         ASN1_STRING *str;
398                                         unsigned char *str2;
399                                         X509_NAME *name = X509_get_subject_name(peer);
400                                         int pos = -1;
401                                         int found = 0;
402                                 
403                                         for (;;) {
404                                                 /* Walk the certificate to check all available "Common Name" */
405                                                 /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
406                                                 pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
407                                                 if (pos < 0)
408                                                         break;
409                                                 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
410                                                 ASN1_STRING_to_UTF8(&str2, str);
411                                                 if (str2) {
412                                                         if (!strcasecmp(ser->parent->hostname, (char *) str2))
413                                                                 found = 1;
414                                                         ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", ser->parent->hostname, str2);
415                                                         OPENSSL_free(str2);
416                                                 }
417                                                 if (found)
418                                                         break;
419                                         }
420                                         if (!found) {
421                                                 ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", ser->parent->hostname);
422                                                 if (peer)
423                                                         X509_free(peer);
424                                                 fclose(ser->f);
425                                                 return NULL;
426                                         }
427                                 }
428                                 if (peer)
429                                         X509_free(peer);
430                         }
431                 }
432                 if (!ser->f)    /* no success opening descriptor stacking */
433                         SSL_free(ser->ssl);
434    }
435 #endif /* DO_SSL */
436
437         if (!ser->f) {
438                 close(ser->fd);
439                 ast_log(LOG_WARNING, "FILE * open failed!\n");
440                 ast_free(ser);
441                 return NULL;
442         }
443
444         if (ser && ser->parent->worker_fn)
445                 return ser->parent->worker_fn(ser);
446         else
447                 return ser;
448 }