radsecproxy-1.6.5.
[radsecproxy.git] / tls.c
1 /*
2  * Copyright (C) 2006-2009 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 "radsecproxy.h"
30 #include "hostport.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     "radsec", /* 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 =
86             resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL,
87                                    AF_UNSPEC, NULL, protodefs.socktype);
88 }
89
90 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
91     struct timeval now;
92     time_t elapsed;
93     X509 *cert;
94     SSL_CTX *ctx = NULL;
95     unsigned long error;
96
97     debug(DBG_DBG, "tlsconnect: called from %s", text);
98     pthread_mutex_lock(&server->lock);
99     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
100         /* already reconnected, nothing to do */
101         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
102         pthread_mutex_unlock(&server->lock);
103         return 1;
104     }
105
106     for (;;) {
107         gettimeofday(&now, NULL);
108         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
109         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
110             debug(DBG_DBG, "tlsconnect: timeout");
111             if (server->sock >= 0)
112                 close(server->sock);
113             SSL_free(server->ssl);
114             server->ssl = NULL;
115             pthread_mutex_unlock(&server->lock);
116             return 0;
117         }
118         if (server->connectionok) {
119             server->connectionok = 0;
120             sleep(2);
121         } else if (elapsed < 1)
122             sleep(2);
123         else if (elapsed < 60) {
124             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
125             sleep(elapsed);
126         } else if (elapsed < 100000) {
127             debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
128             sleep(60);
129         } else
130             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
131
132         if (server->sock >= 0)
133             close(server->sock);
134         if ((server->sock = connecttcphostlist(server->conf->hostports, srcres)) < 0)
135             continue;
136
137         SSL_free(server->ssl);
138         server->ssl = NULL;
139         ctx = tlsgetctx(handle, server->conf->tlsconf);
140         if (!ctx)
141             continue;
142         server->ssl = SSL_new(ctx);
143         if (!server->ssl)
144             continue;
145
146         SSL_set_fd(server->ssl, server->sock);
147         if (SSL_connect(server->ssl) <= 0) {
148             while ((error = ERR_get_error()))
149                 debug(DBG_ERR, "tlsconnect: TLS: %s", ERR_error_string(error, NULL));
150             continue;
151         }
152         cert = verifytlscert(server->ssl);
153         if (!cert)
154             continue;
155         if (verifyconfcert(cert, server->conf)) {
156             X509_free(cert);
157             break;
158         }
159         X509_free(cert);
160     }
161     debug(DBG_WARN, "tlsconnect: TLS connection to %s up", server->conf->name);
162     server->connectionok = 1;
163     gettimeofday(&server->lastconnecttry, NULL);
164     pthread_mutex_unlock(&server->lock);
165     return 1;
166 }
167
168 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
169 /* returns 0 on timeout, -1 on error and num if ok */
170 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
171     int s, ndesc, cnt, len;
172     fd_set readfds;
173     struct timeval timer;
174
175     s = SSL_get_fd(ssl);
176     if (s < 0)
177         return -1;
178     /* make socket non-blocking? */
179     for (len = 0; len < num; len += cnt) {
180         if (SSL_pending(ssl) == 0) {
181             FD_ZERO(&readfds);
182             FD_SET(s, &readfds);
183             if (timeout) {
184                 timer.tv_sec = timeout;
185                 timer.tv_usec = 0;
186             }
187             ndesc = select(s + 1, &readfds, NULL, NULL, timeout ? &timer : NULL);
188             if (ndesc < 1)
189                 return ndesc;
190         }
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->name);
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     debug(DBG_INFO, "tlsclientrd: exiting for %s", server->conf->name);
294     ERR_remove_state(0);
295     SSL_shutdown(server->ssl);
296     shutdown(server->sock, SHUT_RDWR);
297     close(server->sock);
298
299     /* Wake up clientwr(). */
300     server->clientrdgone = 1;
301     pthread_mutex_lock(&server->newrq_mutex);
302     pthread_cond_signal(&server->newrq_cond);
303     pthread_mutex_unlock(&server->newrq_mutex);
304     return NULL;
305 }
306
307 void *tlsserverwr(void *arg) {
308     int cnt;
309     unsigned long error;
310     struct client *client = (struct client *)arg;
311     struct gqueue *replyq;
312     struct request *reply;
313
314     debug(DBG_DBG, "tlsserverwr: starting for %s", addr2string(client->addr));
315     replyq = client->replyq;
316     for (;;) {
317         pthread_mutex_lock(&replyq->mutex);
318         while (!list_first(replyq->entries)) {
319             if (client->ssl) {
320                 debug(DBG_DBG, "tlsserverwr: waiting for signal");
321                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
322                 debug(DBG_DBG, "tlsserverwr: got signal");
323             }
324             if (!client->ssl) {
325                 /* ssl might have changed while waiting */
326                 pthread_mutex_unlock(&replyq->mutex);
327                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
328                 ERR_remove_state(0);
329                 pthread_exit(NULL);
330             }
331         }
332         reply = (struct request *)list_shift(replyq->entries);
333         pthread_mutex_unlock(&replyq->mutex);
334         cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
335         if (cnt > 0)
336             debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d to %s",
337                   cnt, RADLEN(reply->replybuf), addr2string(client->addr));
338         else
339             while ((error = ERR_get_error()))
340                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
341         freerq(reply);
342     }
343 }
344
345 void tlsserverrd(struct client *client) {
346     struct request *rq;
347     uint8_t *buf;
348     pthread_t tlsserverwrth;
349
350     debug(DBG_DBG, "tlsserverrd: starting for %s", addr2string(client->addr));
351
352     if (pthread_create(&tlsserverwrth, &pthread_attr, tlsserverwr, (void *)client)) {
353         debug(DBG_ERR, "tlsserverrd: pthread_create failed");
354         return;
355     }
356
357     for (;;) {
358         buf = radtlsget(client->ssl, IDLE_TIMEOUT * 3);
359         if (!buf) {
360             debug(DBG_ERR, "tlsserverrd: connection from %s lost", addr2string(client->addr));
361             break;
362         }
363         debug(DBG_DBG, "tlsserverrd: got Radius message from %s", addr2string(client->addr));
364         rq = newrequest();
365         if (!rq) {
366             free(buf);
367             continue;
368         }
369         rq->buf = buf;
370         rq->from = client;
371         if (!radsrv(rq)) {
372             debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
373             break;
374         }
375     }
376
377     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
378     client->ssl = NULL;
379     pthread_mutex_lock(&client->replyq->mutex);
380     pthread_cond_signal(&client->replyq->cond);
381     pthread_mutex_unlock(&client->replyq->mutex);
382     debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
383     pthread_join(tlsserverwrth, NULL);
384     debug(DBG_DBG, "tlsserverrd: reader for %s exiting", addr2string(client->addr));
385 }
386
387 void *tlsservernew(void *arg) {
388     int s;
389     struct sockaddr_storage from;
390     socklen_t fromlen = sizeof(from);
391     struct clsrvconf *conf;
392     struct list_node *cur = NULL;
393     SSL *ssl = NULL;
394     X509 *cert = NULL;
395     SSL_CTX *ctx = NULL;
396     unsigned long error;
397     struct client *client;
398     struct tls *accepted_tls = NULL;
399
400     s = *(int *)arg;
401     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
402         debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
403         goto exit;
404     }
405     debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from));
406
407     conf = find_clconf(handle, (struct sockaddr *)&from, &cur);
408     if (conf) {
409         ctx = tlsgetctx(handle, conf->tlsconf);
410         if (!ctx)
411             goto exit;
412         ssl = SSL_new(ctx);
413         if (!ssl)
414             goto exit;
415         SSL_set_fd(ssl, s);
416
417         if (SSL_accept(ssl) <= 0) {
418             while ((error = ERR_get_error()))
419                 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
420             debug(DBG_ERR, "tlsservernew: SSL_accept failed");
421             goto exit;
422         }
423         cert = verifytlscert(ssl);
424         if (!cert)
425             goto exit;
426         accepted_tls = conf->tlsconf;
427     }
428
429     while (conf) {
430         if (accepted_tls == conf->tlsconf && verifyconfcert(cert, conf)) {
431             X509_free(cert);
432             client = addclient(conf, 1);
433             if (client) {
434                 client->ssl = ssl;
435                 client->addr = addr_copy((struct sockaddr *)&from);
436                 tlsserverrd(client);
437                 removeclient(client);
438             } else
439                 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
440             goto exit;
441         }
442         conf = find_clconf(handle, (struct sockaddr *)&from, &cur);
443     }
444     debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
445     if (cert)
446         X509_free(cert);
447
448 exit:
449     if (ssl) {
450         SSL_shutdown(ssl);
451         SSL_free(ssl);
452     }
453     ERR_remove_state(0);
454     shutdown(s, SHUT_RDWR);
455     close(s);
456     pthread_exit(NULL);
457 }
458
459 void *tlslistener(void *arg) {
460     pthread_t tlsserverth;
461     int s, *sp = (int *)arg;
462     struct sockaddr_storage from;
463     socklen_t fromlen = sizeof(from);
464
465     listen(*sp, 0);
466
467     for (;;) {
468         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
469         if (s < 0) {
470             debug(DBG_WARN, "accept failed");
471             continue;
472         }
473         if (pthread_create(&tlsserverth, &pthread_attr, tlsservernew, (void *)&s)) {
474             debug(DBG_ERR, "tlslistener: pthread_create failed");
475             shutdown(s, SHUT_RDWR);
476             close(s);
477             continue;
478         }
479         pthread_detach(tlsserverth);
480     }
481     free(sp);
482     return NULL;
483 }
484 #else
485 const struct protodefs *tlsinit(uint8_t h) {
486     return NULL;
487 }
488 #endif
489
490 /* Local Variables: */
491 /* c-file-style: "stroustrup" */
492 /* End: */