renamed struct queue to gqueue due to solaris defining queue
[libradsec.git] / tls.c
1 /*
2  * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 #include <signal.h>
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <netdb.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <limits.h>
16 #ifdef SYS_SOLARIS9
17 #include <fcntl.h>
18 #endif
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/select.h>
22 #include <ctype.h>
23 #include <sys/wait.h>
24 #include <arpa/inet.h>
25 #include <regex.h>
26 #include <pthread.h>
27 #include <openssl/ssl.h>
28 #include <openssl/err.h>
29 #include "list.h"
30 #include "radsecproxy.h"
31
32 #ifdef RADPROT_TLS
33 #include "debug.h"
34 #include "util.h"
35
36 static void setprotoopts(struct commonprotoopts *opts);
37 static char **getlistenerargs();
38 void *tlslistener(void *arg);
39 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
40 void *tlsclientrd(void *arg);
41 int clientradputtls(struct server *server, unsigned char *rad);
42 void tlssetsrcres();
43
44 static const struct protodefs protodefs = {
45     "tls",
46     "mysecret", /* secretdefault */
47     SOCK_STREAM, /* socktype */
48     "2083", /* portdefault */
49     0, /* retrycountdefault */
50     0, /* retrycountmax */
51     REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
52     60, /* retryintervalmax */
53     DUPLICATE_INTERVAL, /* duplicateintervaldefault */
54     setprotoopts, /* setprotoopts */
55     getlistenerargs, /* getlistenerargs */
56     tlslistener, /* listener */
57     tlsconnect, /* connecter */
58     tlsclientrd, /* clientconnreader */
59     clientradputtls, /* clientradput */
60     NULL, /* addclient */
61     NULL, /* addserverextra */
62     tlssetsrcres, /* setsrcres */
63     NULL /* initextra */
64 };
65
66 static struct addrinfo *srcres = NULL;
67 static uint8_t handle;
68 static struct commonprotoopts *protoopts = NULL;
69
70 const struct protodefs *tlsinit(uint8_t h) {
71     handle = h;
72     return &protodefs;
73 }
74
75 static void setprotoopts(struct commonprotoopts *opts) {
76     protoopts = opts;
77 }
78
79 static char **getlistenerargs() {
80     return protoopts ? protoopts->listenargs : NULL;
81 }
82
83 void tlssetsrcres() {
84     if (!srcres)
85         srcres = resolve_hostport_addrinfo(handle, protoopts ? protoopts->sourcearg : NULL);
86     
87 }
88
89 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
90     struct timeval now;
91     time_t elapsed;
92     X509 *cert;
93     SSL_CTX *ctx = NULL;
94     unsigned long error;
95     
96     debug(DBG_DBG, "tlsconnect: called from %s", text);
97     pthread_mutex_lock(&server->lock);
98     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
99         /* already reconnected, nothing to do */
100         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
101         pthread_mutex_unlock(&server->lock);
102         return 1;
103     }
104
105     for (;;) {
106         gettimeofday(&now, NULL);
107         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
108         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
109             debug(DBG_DBG, "tlsconnect: timeout");
110             if (server->sock >= 0)
111                 close(server->sock);
112             SSL_free(server->ssl);
113             server->ssl = NULL;
114             pthread_mutex_unlock(&server->lock);
115             return 0;
116         }
117         if (server->connectionok) {
118             server->connectionok = 0;
119             sleep(2);
120         } else if (elapsed < 1)
121             sleep(2);
122         else if (elapsed < 60) {
123             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
124             sleep(elapsed);
125         } else if (elapsed < 100000) {
126             debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
127             sleep(60);
128         } else
129             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
130         debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
131         if (server->sock >= 0)
132             close(server->sock);
133         if ((server->sock = connecttcp(server->conf->addrinfo, srcres)) < 0) {
134             debug(DBG_ERR, "tlsconnect: connecttcp failed");
135             continue;
136         }
137         
138         SSL_free(server->ssl);
139         server->ssl = NULL;
140         ctx = tlsgetctx(handle, server->conf->tlsconf);
141         if (!ctx)
142             continue;
143         server->ssl = SSL_new(ctx);
144         if (!server->ssl)
145             continue;
146
147         SSL_set_fd(server->ssl, server->sock);
148         if (SSL_connect(server->ssl) <= 0) {
149             while ((error = ERR_get_error()))
150                 debug(DBG_ERR, "tlsconnect: TLS: %s", ERR_error_string(error, NULL));
151             continue;
152         }
153         cert = verifytlscert(server->ssl);
154         if (!cert)
155             continue;
156         if (verifyconfcert(cert, server->conf)) {
157             X509_free(cert);
158             break;
159         }
160         X509_free(cert);
161     }
162     debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
163     server->connectionok = 1;
164     gettimeofday(&server->lastconnecttry, NULL);
165     pthread_mutex_unlock(&server->lock);
166     return 1;
167 }
168
169 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
170 /* returns 0 on timeout, -1 on error and num if ok */
171 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
172     int s, ndesc, cnt, len;
173     fd_set readfds, writefds;
174     struct timeval timer;
175     
176     s = SSL_get_fd(ssl);
177     if (s < 0)
178         return -1;
179     /* make socket non-blocking? */
180     for (len = 0; len < num; len += cnt) {
181         FD_ZERO(&readfds);
182         FD_SET(s, &readfds);
183         writefds = readfds;
184         if (timeout) {
185             timer.tv_sec = timeout;
186             timer.tv_usec = 0;
187         }
188         ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
189         if (ndesc < 1)
190             return ndesc;
191
192         cnt = SSL_read(ssl, buf + len, num - len);
193         if (cnt <= 0)
194             switch (SSL_get_error(ssl, cnt)) {
195             case SSL_ERROR_WANT_READ:
196             case SSL_ERROR_WANT_WRITE:
197                 cnt = 0;
198                 continue;
199             case SSL_ERROR_ZERO_RETURN:
200                 /* remote end sent close_notify, send one back */
201                 SSL_shutdown(ssl);
202                 return -1;
203             default:
204                 return -1;
205             }
206     }
207     return num;
208 }
209
210 /* timeout in seconds, 0 means no timeout (blocking) */
211 unsigned char *radtlsget(SSL *ssl, int timeout) {
212     int cnt, len;
213     unsigned char buf[4], *rad;
214
215     for (;;) {
216         cnt = sslreadtimeout(ssl, buf, 4, timeout);
217         if (cnt < 1) {
218             debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
219             return NULL;
220         }
221
222         len = RADLEN(buf);
223         rad = malloc(len);
224         if (!rad) {
225             debug(DBG_ERR, "radtlsget: malloc failed");
226             continue;
227         }
228         memcpy(rad, buf, 4);
229         
230         cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
231         if (cnt < 1) {
232             debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
233             free(rad);
234             return NULL;
235         }
236         
237         if (len >= 20)
238             break;
239         
240         free(rad);
241         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
242     }
243     
244     debug(DBG_DBG, "radtlsget: got %d bytes", len);
245     return rad;
246 }
247
248 int clientradputtls(struct server *server, unsigned char *rad) {
249     int cnt;
250     size_t len;
251     unsigned long error;
252     struct clsrvconf *conf = server->conf;
253
254     if (!server->connectionok)
255         return 0;
256     len = RADLEN(rad);
257     if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
258         while ((error = ERR_get_error()))
259             debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
260         return 0;
261     }
262
263     debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
264     return 1;
265 }
266
267 void *tlsclientrd(void *arg) {
268     struct server *server = (struct server *)arg;
269     unsigned char *buf;
270     struct timeval now, lastconnecttry;
271     
272     for (;;) {
273         /* yes, lastconnecttry is really necessary */
274         lastconnecttry = server->lastconnecttry;
275         buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
276         if (!buf) {
277             if (server->dynamiclookuparg)
278                 break;
279             tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
280             continue;
281         }
282
283         replyh(server, buf);
284
285         if (server->dynamiclookuparg) {
286             gettimeofday(&now, NULL);
287             if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
288                 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
289                 break;
290             }
291         }
292     }
293     ERR_remove_state(0);
294     server->clientrdgone = 1;
295     return NULL;
296 }
297
298 void *tlsserverwr(void *arg) {
299     int cnt;
300     unsigned long error;
301     struct client *client = (struct client *)arg;
302     struct gqueue *replyq;
303     struct request *reply;
304     
305     debug(DBG_DBG, "tlsserverwr: starting for %s", addr2string(client->addr));
306     replyq = client->replyq;
307     for (;;) {
308         pthread_mutex_lock(&replyq->mutex);
309         while (!list_first(replyq->entries)) {
310             if (client->ssl) {      
311                 debug(DBG_DBG, "tlsserverwr: waiting for signal");
312                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
313                 debug(DBG_DBG, "tlsserverwr: got signal");
314             }
315             if (!client->ssl) {
316                 /* ssl might have changed while waiting */
317                 pthread_mutex_unlock(&replyq->mutex);
318                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
319                 ERR_remove_state(0);
320                 pthread_exit(NULL);
321             }
322         }
323         reply = (struct request *)list_shift(replyq->entries);
324         pthread_mutex_unlock(&replyq->mutex);
325         cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
326         if (cnt > 0)
327             debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d to %s",
328                   cnt, RADLEN(reply->replybuf), addr2string(client->addr));
329         else
330             while ((error = ERR_get_error()))
331                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
332         freerq(reply);
333     }
334 }
335
336 void tlsserverrd(struct client *client) {
337     struct request *rq;
338     uint8_t *buf;
339     pthread_t tlsserverwrth;
340     
341     debug(DBG_DBG, "tlsserverrd: starting for %s", addr2string(client->addr));
342     
343     if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
344         debug(DBG_ERR, "tlsserverrd: pthread_create failed");
345         return;
346     }
347
348     for (;;) {
349         buf = radtlsget(client->ssl, 0);
350         if (!buf) {
351             debug(DBG_ERR, "tlsserverrd: connection from %s lost", addr2string(client->addr));
352             break;
353         }
354         debug(DBG_DBG, "tlsserverrd: got Radius message from %s", addr2string(client->addr));
355         rq = newrequest();
356         if (!rq) {
357             free(buf);
358             continue;
359         }
360         rq->buf = buf;
361         rq->from = client;
362         if (!radsrv(rq)) {
363             debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
364             break;
365         }
366     }
367     
368     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
369     client->ssl = NULL;
370     pthread_mutex_lock(&client->replyq->mutex);
371     pthread_cond_signal(&client->replyq->cond);
372     pthread_mutex_unlock(&client->replyq->mutex);
373     debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
374     pthread_join(tlsserverwrth, NULL);
375     debug(DBG_DBG, "tlsserverrd: reader for %s exiting", addr2string(client->addr));
376 }
377
378 void *tlsservernew(void *arg) {
379     int s;
380     struct sockaddr_storage from;
381     socklen_t fromlen = sizeof(from);
382     struct clsrvconf *conf;
383     struct list_node *cur = NULL;
384     SSL *ssl = NULL;
385     X509 *cert = NULL;
386     SSL_CTX *ctx = NULL;
387     unsigned long error;
388     struct client *client;
389
390     s = *(int *)arg;
391     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
392         debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
393         goto exit;
394     }
395     debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from));
396
397     conf = find_clconf(handle, (struct sockaddr *)&from, &cur);
398     if (conf) {
399         ctx = tlsgetctx(handle, conf->tlsconf);
400         if (!ctx)
401             goto exit;
402         ssl = SSL_new(ctx);
403         if (!ssl)
404             goto exit;
405         SSL_set_fd(ssl, s);
406
407         if (SSL_accept(ssl) <= 0) {
408             while ((error = ERR_get_error()))
409                 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
410             debug(DBG_ERR, "tlsservernew: SSL_accept failed");
411             goto exit;
412         }
413         cert = verifytlscert(ssl);
414         if (!cert)
415             goto exit;
416     }
417     
418     while (conf) {
419         if (verifyconfcert(cert, conf)) {
420             X509_free(cert);
421             client = addclient(conf, 1);
422             if (client) {
423                 client->ssl = ssl;
424                 client->addr = addr_copy((struct sockaddr *)&from);
425                 tlsserverrd(client);
426                 removeclient(client);
427             } else
428                 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
429             goto exit;
430         }
431         conf = find_clconf(handle, (struct sockaddr *)&from, &cur);
432     }
433     debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
434     if (cert)
435         X509_free(cert);
436
437  exit:
438     if (ssl) {
439         SSL_shutdown(ssl);
440         SSL_free(ssl);
441     }
442     ERR_remove_state(0);
443     shutdown(s, SHUT_RDWR);
444     close(s);
445     pthread_exit(NULL);
446 }
447
448 void *tlslistener(void *arg) {
449     pthread_t tlsserverth;
450     int s, *sp = (int *)arg;
451     struct sockaddr_storage from;
452     socklen_t fromlen = sizeof(from);
453
454     listen(*sp, 0);
455
456     for (;;) {
457         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
458         if (s < 0) {
459             debug(DBG_WARN, "accept failed");
460             continue;
461         }
462         if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
463             debug(DBG_ERR, "tlslistener: pthread_create failed");
464             shutdown(s, SHUT_RDWR);
465             close(s);
466             continue;
467         }
468         pthread_detach(tlsserverth);
469     }
470     free(sp);
471     return NULL;
472 }
473 #else
474 const struct protodefs *tlsinit(uint8_t h) {
475     return NULL;
476 }
477 #endif