separated tcp
[radsecproxy.git] / dtls.c
1 /*
2  * Copyright (C) 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 "debug.h"
30 #include "list.h"
31 #include "util.h"
32 #include "radsecproxy.h"
33 #include "dtls.h"
34
35 int udp2bio(int s, struct queue *q, int cnt) {
36     unsigned char *buf;
37     BIO *rbio;
38
39     if (cnt < 1)
40         return 0;
41     
42     buf = malloc(cnt);
43     if (!buf) {
44         unsigned char err;
45         debug(DBG_ERR, "udp2bio: malloc failed");
46         recv(s, &err, 1, 0);
47         return 0;
48     }
49
50     cnt = recv(s, buf, cnt, 0);
51     if (cnt < 1) {
52         debug(DBG_WARN, "udp2bio: recv failed");
53         free(buf);
54         return 0;
55     }
56
57     rbio = BIO_new_mem_buf(buf, cnt);
58     BIO_set_mem_eof_return(rbio, -1);
59
60     pthread_mutex_lock(&q->mutex);
61     if (!list_push(q->entries, rbio)) {
62         BIO_free(rbio);
63         pthread_mutex_unlock(&q->mutex);
64         return 0;
65     }
66     pthread_cond_signal(&q->cond);
67     pthread_mutex_unlock(&q->mutex);
68     return 1;
69 }
70
71 BIO *getrbio(SSL *ssl, struct queue *q, int timeout) {
72     BIO *rbio;
73     struct timeval now;
74     struct timespec to;
75
76     pthread_mutex_lock(&q->mutex);
77     if (!(rbio = (BIO *)list_shift(q->entries))) {
78         if (timeout) {
79             gettimeofday(&now, NULL);
80             memset(&to, 0, sizeof(struct timespec));
81             to.tv_sec = now.tv_sec + timeout;
82             pthread_cond_timedwait(&q->cond, &q->mutex, &to);
83         } else
84             pthread_cond_wait(&q->cond, &q->mutex);
85         rbio = (BIO *)list_shift(q->entries);
86     }
87     pthread_mutex_unlock(&q->mutex);
88     return rbio;
89 }
90
91 void *udpdtlsserverrd(void *arg) {
92     int cnt, s = *(int *)arg;
93     unsigned char buf[4];
94     struct sockaddr_storage from;
95     socklen_t fromlen = sizeof(from);
96     struct clsrvconf *conf;
97     struct list_node *node;
98     struct client *client;
99     fd_set readfds;
100     pthread_t dtlsserverth;
101
102     for (;;) {
103         FD_ZERO(&readfds);
104         FD_SET(s, &readfds);
105         if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
106             continue;
107         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
108         if (cnt == -1) {
109             debug(DBG_WARN, "udpdtlsserverrd: recv failed");
110             continue;
111         }
112         conf = find_clconf(RAD_DTLS, (struct sockaddr *)&from, NULL);
113         if (!conf) {
114             debug(DBG_WARN, "udpdtlsserverrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
115             recv(s, buf, 4, 0);
116             continue;
117         }
118         
119         node = list_first(conf->clients);
120         if (node)
121             client = (struct client *)node->data;
122         else {
123             client = addclient(conf);
124             if (!client) {
125                 recv(s, buf, 4, 0);
126                 continue;
127             }
128             client->sock = s;
129             memcpy(&client->addr, &from, fromlen);
130             if (pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)client)) {
131                 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
132                 removeclient(client);
133                 recv(s, buf, 4, 0);
134                 continue;
135             }
136             pthread_detach(dtlsserverth);
137         }
138         if (udp2bio(s, client->rbios, cnt))
139             debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
140     }
141 }
142
143 void *dtlsserverwr(void *arg) {
144     int cnt;
145     unsigned long error;
146     struct client *client = (struct client *)arg;
147     struct queue *replyq;
148     struct reply *reply;
149     
150     debug(DBG_DBG, "dtlsserverwr: starting for %s", client->conf->host);
151     replyq = client->replyq;
152     for (;;) {
153         pthread_mutex_lock(&replyq->mutex);
154         while (!list_first(replyq->entries)) {
155             if (client->ssl) {      
156                 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
157                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
158                 debug(DBG_DBG, "dtlsserverwr: got signal");
159             }
160             if (!client->ssl) {
161                 /* ssl might have changed while waiting */
162                 pthread_mutex_unlock(&replyq->mutex);
163                 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
164                 ERR_remove_state(0);
165                 pthread_exit(NULL);
166             }
167         }
168         reply = (struct reply *)list_shift(replyq->entries);
169         pthread_mutex_unlock(&replyq->mutex);
170         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
171         if (cnt > 0)
172             debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d",
173                   cnt, RADLEN(reply->buf));
174         else
175             while ((error = ERR_get_error()))
176                 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
177         free(reply->buf);
178         free(reply);
179     }
180 }
181
182 int dtlsread(SSL *ssl, struct queue *q, unsigned char *buf, int num) {
183     int len, cnt;
184
185     for (len = 0; len < num; len += cnt) {
186         cnt = SSL_read(ssl, buf + len, num - len);
187         if (cnt <= 0)
188             switch (cnt = SSL_get_error(ssl, cnt)) {
189             case SSL_ERROR_WANT_READ:
190                 BIO_free(ssl->rbio);            
191                 ssl->rbio = getrbio(ssl, q, 0);
192                 if (!ssl->rbio)
193                     return -1;
194                 cnt = 0;
195                 continue;
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 unsigned char *raddtlsget(SSL *ssl, struct queue *rbios) {
211     int cnt, len;
212     unsigned char buf[4], *rad;
213
214     for (;;) {
215         cnt = dtlsread(ssl, rbios, buf, 4);
216         if (cnt < 1) {
217             debug(DBG_DBG, "raddtlsget: connection lost");
218             return NULL;
219         }
220
221         len = RADLEN(buf);
222         rad = malloc(len);
223         if (!rad) {
224             debug(DBG_ERR, "raddtlsget: malloc failed");
225             continue;
226         }
227         memcpy(rad, buf, 4);
228         
229         cnt = dtlsread(ssl, rbios, rad + 4, len - 4);
230         if (cnt < 1) {
231             debug(DBG_DBG, "raddtlsget: connection lost");
232             free(rad);
233             return NULL;
234         }
235         
236         if (len >= 20)
237             break;
238         
239         free(rad);
240         debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
241     }
242     
243     debug(DBG_DBG, "raddtlsget: got %d bytes", len);
244     return rad;
245 }
246
247 void dtlsserverrd(struct client *client) {
248     struct request rq;
249     pthread_t dtlsserverwrth;
250     
251     debug(DBG_DBG, "dtlsserverrd: starting for %s", client->conf->host);
252
253     if (pthread_create(&dtlsserverwrth, NULL, dtlsserverwr, (void *)client)) {
254         debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
255         return;
256     }
257
258     for (;;) {
259         memset(&rq, 0, sizeof(struct request));
260         rq.buf = raddtlsget(client->ssl, client->rbios);
261         if (!rq.buf) {
262             debug(DBG_ERR, "dtlsserverrd: connection from %s lost", client->conf->host);
263             break;
264         }
265         debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", client->conf->host);
266         rq.from = client;
267         if (!radsrv(&rq)) {
268             debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
269             break;
270         }
271     }
272     
273     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
274     client->ssl = NULL;
275
276     pthread_mutex_lock(&client->replyq->mutex);
277     pthread_cond_signal(&client->replyq->cond);
278     pthread_mutex_unlock(&client->replyq->mutex);
279     debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
280     pthread_join(dtlsserverwrth, NULL);
281     removeclientrqs(client);
282     debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", client->conf->host);
283 }
284
285 /* accept if acc == 1, else connect */
286 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct queue *rbios) {
287     SSL *ssl;
288     int i, res;
289     unsigned long error;
290     BIO *mem0bio, *wbio;
291     
292     ssl = SSL_new(ctx);
293     if (!ssl)
294         return NULL;
295     
296     mem0bio = BIO_new(BIO_s_mem());
297     BIO_set_mem_eof_return(mem0bio, -1);
298     wbio = BIO_new_dgram(s, BIO_NOCLOSE);
299     BIO_dgram_set_peer(wbio, addr);
300     SSL_set_bio(ssl, mem0bio, wbio);
301
302     for (i = 0; i < 5; i++) {
303         res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
304         if (res > 0)
305             return ssl;
306         if (res == 0)
307             break;
308         if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
309             BIO_free(ssl->rbio);
310             ssl->rbio = getrbio(ssl, rbios, 5);
311             if (!ssl->rbio)
312                 break;
313         }
314         while ((error = ERR_get_error()))
315             debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
316     }
317
318     SSL_free(ssl);
319     return NULL;
320 }
321
322 void *dtlsservernew(void *arg) {
323     struct client *client = (struct client *)arg;
324     X509 *cert = NULL;
325
326     client->ssl = dtlsacccon(1, client->conf->ssl_ctx, client->sock, (struct sockaddr *)&client->addr, client->rbios);
327     if (!client->ssl)
328         goto exit;
329     cert = verifytlscert(client->ssl);
330     if (!cert)
331         goto exit;
332     if (verifyconfcert(cert, client->conf)) {
333         X509_free(cert);
334         dtlsserverrd(client);
335         removeclient(client);
336     } else
337         debug(DBG_WARN, "dtlsservernew: ignoring request, certificate validation failed");
338     if (cert)
339         X509_free(cert);
340
341  exit:
342     SSL_free(client->ssl);
343     ERR_remove_state(0);
344     pthread_exit(NULL);
345 }
346
347 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
348     struct timeval now;
349     time_t elapsed;
350     X509 *cert;
351     
352     debug(DBG_DBG, "dtlsconnect: called from %s", text);
353     pthread_mutex_lock(&server->lock);
354     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
355         /* already reconnected, nothing to do */
356         debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
357         pthread_mutex_unlock(&server->lock);
358         return 1;
359     }
360
361     for (;;) {
362         gettimeofday(&now, NULL);
363         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
364
365         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
366             debug(DBG_DBG, "dtlsconnect: timeout");
367             SSL_free(server->ssl);
368             server->ssl = NULL;
369             pthread_mutex_unlock(&server->lock);
370             return 0;
371         }
372
373         if (server->connectionok) {
374             server->connectionok = 0;
375             sleep(2);
376         } else if (elapsed < 1)
377             sleep(2);
378         else if (elapsed < 60) {
379             debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
380             sleep(elapsed);
381         } else if (elapsed < 100000) {
382             debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
383             sleep(60);
384         } else
385             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
386         debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", server->conf->host, server->conf->port);
387
388         SSL_free(server->ssl);
389         server->ssl = dtlsacccon(0, server->conf->ssl_ctx, server->sock, server->conf->addrinfo->ai_addr, server->rbios);
390         if (!server->ssl)
391             continue;
392         debug(DBG_DBG, "dtlsconnect: DTLS: ok");
393         
394         cert = verifytlscert(server->ssl);
395         if (!cert)
396             continue;
397         
398         if (verifyconfcert(cert, server->conf))
399             break;
400         X509_free(cert);
401     }
402     X509_free(cert);
403     debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", server->conf->host, server->conf->port);
404     gettimeofday(&server->lastconnecttry, NULL);
405     pthread_mutex_unlock(&server->lock);
406     return 1;
407 }
408
409 int clientradputdtls(struct server *server, unsigned char *rad) {
410     int cnt;
411     size_t len;
412     unsigned long error;
413     struct clsrvconf *conf = server->conf;
414     
415     len = RADLEN(rad);
416     while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
417         while ((error = ERR_get_error()))
418             debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
419     }
420     debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->host);
421     return 1;
422 }
423
424 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
425 void *udpdtlsclientrd(void *arg) {
426     int cnt, s = *(int *)arg;
427     unsigned char buf[4];
428     struct sockaddr_storage from;
429     socklen_t fromlen = sizeof(from);
430     struct clsrvconf *conf;
431     fd_set readfds;
432     
433     for (;;) {
434         FD_ZERO(&readfds);
435         FD_SET(s, &readfds);
436         if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
437             continue;
438         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
439         if (cnt == -1) {
440             debug(DBG_WARN, "udpdtlsclientrd: recv failed");
441             continue;
442         }
443         
444         conf = find_srvconf(RAD_DTLS, (struct sockaddr *)&from, NULL);
445         if (!conf) {
446             debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
447             recv(s, buf, 4, 0);
448             continue;
449         }
450         if (udp2bio(s, conf->servers->rbios, cnt))
451             debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
452     }
453 }
454
455 void *dtlsclientrd(void *arg) {
456     struct server *server = (struct server *)arg;
457     unsigned char *buf;
458     struct timeval lastconnecttry;
459     
460     for (;;) {
461         /* yes, lastconnecttry is really necessary */
462         lastconnecttry = server->lastconnecttry;
463         buf = raddtlsget(server->ssl, server->rbios);
464         if (!buf) {
465             dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
466             continue;
467         }
468
469         if (!replyh(server, buf))
470             free(buf);
471     }
472 }