Don't wait for _writable_ when _reading_ an SSL socket.
[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     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, &pthread_attr, 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     struct tls *accepted_tls = NULL;
390
391     s = *(int *)arg;
392     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
393         debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
394         goto exit;
395     }
396     debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from));
397
398     conf = find_clconf(handle, (struct sockaddr *)&from, &cur);
399     if (conf) {
400         ctx = tlsgetctx(handle, conf->tlsconf);
401         if (!ctx)
402             goto exit;
403         ssl = SSL_new(ctx);
404         if (!ssl)
405             goto exit;
406         SSL_set_fd(ssl, s);
407
408         if (SSL_accept(ssl) <= 0) {
409             while ((error = ERR_get_error()))
410                 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
411             debug(DBG_ERR, "tlsservernew: SSL_accept failed");
412             goto exit;
413         }
414         cert = verifytlscert(ssl);
415         if (!cert)
416             goto exit;
417         accepted_tls = conf->tlsconf;
418     }
419
420     while (conf) {
421         if (accepted_tls == conf->tlsconf && verifyconfcert(cert, conf)) {
422             X509_free(cert);
423             client = addclient(conf, 1);
424             if (client) {
425                 client->ssl = ssl;
426                 client->addr = addr_copy((struct sockaddr *)&from);
427                 tlsserverrd(client);
428                 removeclient(client);
429             } else
430                 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
431             goto exit;
432         }
433         conf = find_clconf(handle, (struct sockaddr *)&from, &cur);
434     }
435     debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
436     if (cert)
437         X509_free(cert);
438
439 exit:
440     if (ssl) {
441         SSL_shutdown(ssl);
442         SSL_free(ssl);
443     }
444     ERR_remove_state(0);
445     shutdown(s, SHUT_RDWR);
446     close(s);
447     pthread_exit(NULL);
448 }
449
450 void *tlslistener(void *arg) {
451     pthread_t tlsserverth;
452     int s, *sp = (int *)arg;
453     struct sockaddr_storage from;
454     socklen_t fromlen = sizeof(from);
455
456     listen(*sp, 0);
457
458     for (;;) {
459         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
460         if (s < 0) {
461             debug(DBG_WARN, "accept failed");
462             continue;
463         }
464         if (pthread_create(&tlsserverth, &pthread_attr, tlsservernew, (void *)&s)) {
465             debug(DBG_ERR, "tlslistener: pthread_create failed");
466             shutdown(s, SHUT_RDWR);
467             close(s);
468             continue;
469         }
470         pthread_detach(tlsserverth);
471     }
472     free(sp);
473     return NULL;
474 }
475 #else
476 const struct protodefs *tlsinit(uint8_t h) {
477     return NULL;
478 }
479 #endif
480
481 /* Local Variables: */
482 /* c-file-style: "stroustrup" */
483 /* End: */