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