dtls.c 23 KB
Newer Older
1 2 3 4 5
/* Copyright (c) 2007-2009, UNINETT AS
 * Copyright (c) 2012,2016-2017, NORDUnet A/S */
/* See LICENSE for licensing information. */

#define _GNU_SOURCE
6 7 8 9 10 11 12 13 14 15 16

#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
17
#include <poll.h>
18 19 20 21 22 23 24
#include <ctype.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <regex.h>
#include <pthread.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
25 26
#include <assert.h>
#include <fcntl.h>
27 28 29 30 31 32 33 34 35 36
#include "hash.h"
#include "radsecproxy.h"

#ifdef RADPROT_DTLS
#include "debug.h"
#include "util.h"
#include "hostport.h"

static void setprotoopts(struct commonprotoopts *opts);
static char **getlistenerargs();
37
void *dtlslistener(void *arg);
38 39 40 41 42 43 44 45 46
int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
void *dtlsclientrd(void *arg);
int clientradputdtls(struct server *server, unsigned char *rad);
void addserverextradtls(struct clsrvconf *conf);
void dtlssetsrcres();
void initextradtls();

static const struct protodefs protodefs = {
    "dtls",
47
    "radsec", /* secretdefault */
48 49 50 51 52 53 54 55 56
    SOCK_DGRAM, /* socktype */
    "2083", /* portdefault */
    REQUEST_RETRY_COUNT, /* retrycountdefault */
    10, /* retrycountmax */
    REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
    60, /* retryintervalmax */
    DUPLICATE_INTERVAL, /* duplicateintervaldefault */
    setprotoopts, /* setprotoopts */
    getlistenerargs, /* getlistenerargs */
57
    dtlslistener, /* listener */
58 59 60 61
    dtlsconnect, /* connecter */
    dtlsclientrd, /* clientconnreader */
    clientradputdtls, /* clientradput */
    NULL, /* addclient */
62
    NULL, /* addserverextra */
63
    dtlssetsrcres, /* setsrcres */
64
    NULL /* initextra */
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
};

static struct addrinfo *srcres = NULL;
static uint8_t handle;
static struct commonprotoopts *protoopts = NULL;

const struct protodefs *dtlsinit(uint8_t h) {
    handle = h;
    return &protodefs;
}

static void setprotoopts(struct commonprotoopts *opts) {
    protoopts = opts;
}

static char **getlistenerargs() {
    return protoopts ? protoopts->listenargs : NULL;
}

struct dtlsservernewparams {
85
    struct sockaddr_storage addr;
86 87
    struct sockaddr_storage bind;
    SSL *ssl;
88 89 90 91
};

void dtlssetsrcres() {
    if (!srcres)
92 93 94
	srcres =
            resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL,
                                   AF_UNSPEC, NULL, protodefs.socktype);
95 96
}

97 98 99 100 101 102
int dtlsread(SSL *ssl, unsigned char *buf, int num, int timeout, pthread_mutex_t *lock) {
    int len, cnt, sockerr = 0;
    socklen_t errlen = sizeof(sockerr);
    struct pollfd fds[1];
    unsigned long error;
    assert(lock);
103

104
    pthread_mutex_lock(lock);
105

106
    for (len = 0; len < num; len += cnt) {
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        if (!SSL_pending(ssl)) {
            fds[0].fd = BIO_get_fd(SSL_get_rbio(ssl), NULL);
            fds[0].events = POLLIN;

            pthread_mutex_unlock(lock);

            cnt = poll(fds, 1, timeout? timeout * 1000 : -1);
            if (cnt == 0)
                return cnt;

            pthread_mutex_lock(lock);
            if (cnt < 0 || fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
                if (fds[0].revents & POLLERR) {
                    if(!getsockopt(BIO_get_fd(SSL_get_rbio(ssl), NULL), SOL_SOCKET, SO_ERROR, (void *)&sockerr, &errlen))
                        debug(DBG_INFO, "DTLS Connection lost: %s", strerror(sockerr));
                    else
                        debug(DBG_INFO, "DTLS Connection lost: unknown error");
                } else if (fds[0].revents & POLLHUP) {
                    debug(DBG_INFO, "DTLS Connection lost: hang up");
                } else if (fds[0].revents & POLLNVAL) {
                    debug(DBG_INFO, "DTLS Connection error: fd not open");
                }

                SSL_shutdown(ssl);
                pthread_mutex_unlock(lock);
                return -1;
            }
        }
135

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        cnt = SSL_read(ssl, buf + len, num - len);
        if (cnt <= 0)
            switch (cnt = SSL_get_error(ssl, cnt)) {
                case SSL_ERROR_WANT_READ:
                case SSL_ERROR_WANT_WRITE:
                    cnt = 0;
                    continue;
                case SSL_ERROR_ZERO_RETURN:
                    debug(DBG_DBG, "dtlsread: got ssl shutdown");
                default:
                    while ((error = ERR_get_error()))
                        debug(DBG_ERR, "dtlsread: SSL: %s", ERR_error_string(error, NULL));
                    if (cnt == 0)
                        debug(DBG_INFO, "dtlsread: connection closed by remote host");
                    else {
                        debugerrno(errno, DBG_ERR, "dtlsread: connection lost");
                    }
                    /* snsure ssl connection is shutdown */
                    SSL_shutdown(ssl);
                    pthread_mutex_unlock(lock);
                    return -1;
157 158
        }
    }
159 160
    pthread_mutex_unlock(lock);
    return num;
161 162
}

163
unsigned char *raddtlsget(SSL *ssl, int timeout, pthread_mutex_t *lock) {
164 165 166
    int cnt, len;
    unsigned char buf[4], *rad;

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    cnt = dtlsread(ssl, buf, 4, timeout, lock);
    if (cnt < 1)
        return NULL;

    len = RADLEN(buf);
    if (len < 20) {
        debug(DBG_ERR, "raddtlsget: length too small, malformed packet! closing connection!");
        pthread_mutex_lock(lock);
        SSL_shutdown(ssl);
        pthread_mutex_unlock(lock);
        return NULL;
    }
    rad = malloc(len);
    if (!rad) {
        debug(DBG_ERR, "raddtlsget: malloc failed");
        return NULL;
    }
    memcpy(rad, buf, 4);
185

186 187
    cnt = dtlsread(ssl, rad + 4, len - 4, timeout, lock);
    if (cnt < 1) {
188
        free(rad);
189
        return NULL;
190
    }
191

192 193 194 195 196 197 198 199 200 201
    debug(DBG_DBG, "raddtlsget: got %d bytes", len);
    return rad;
}

void *dtlsserverwr(void *arg) {
    int cnt;
    unsigned long error;
    struct client *client = (struct client *)arg;
    struct gqueue *replyq;
    struct request *reply;
202
    char tmp[INET6_ADDRSTRLEN];
203

204
    debug(DBG_DBG, "dtlsserverwr: starting for %s", addr2string(client->addr, tmp, sizeof(tmp)));
205 206
    replyq = client->replyq;
    for (;;) {
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        pthread_mutex_lock(&replyq->mutex);
        while (!list_first(replyq->entries)) {
            if (client->ssl) {
                debug(DBG_DBG, "dtlsserverwr: waiting for signal");
                pthread_cond_wait(&replyq->cond, &replyq->mutex);
                debug(DBG_DBG, "dtlsserverwr: got signal");
            } else
                break;
        }

        reply = (struct request *)list_shift(replyq->entries);
        pthread_mutex_unlock(&replyq->mutex);

        pthread_mutex_lock(&client->lock);
        if (!client->ssl) {
            /* ssl might have changed while waiting */
            pthread_mutex_unlock(&client->lock);
            if (reply)
                freerq(reply);
            debug(DBG_DBG, "tlsserverwr: exiting as requested");
            pthread_exit(NULL);
        }

        while ((cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf))) <= 0) {
            switch (SSL_get_error(client->ssl, cnt)) {
                case SSL_ERROR_WANT_READ:
                case SSL_ERROR_WANT_WRITE:
                    continue;
                default:
                    while ((error = ERR_get_error()))
                        debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
                    pthread_mutex_unlock(&client->lock);
                    freerq(reply);
                    debug(DBG_DBG, "tlsserverwr: SSL error. exiting.");
                    pthread_exit(NULL);
            }
        }
        debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d to %s",
            cnt, RADLEN(reply->replybuf), addr2string(client->addr, tmp, sizeof(tmp)));
        pthread_mutex_unlock(&client->lock);
        freerq(reply);
248 249 250 251 252 253 254
    }
}

void dtlsserverrd(struct client *client) {
    struct request *rq;
    uint8_t *buf;
    pthread_t dtlsserverwrth;
255
    char tmp[INET6_ADDRSTRLEN];
256

257
    debug(DBG_DBG, "dtlsserverrd: starting for %s", addr2string(client->addr, tmp, sizeof(tmp)));
258

259
    if (pthread_create(&dtlsserverwrth, &pthread_attr, dtlsserverwr, (void *)client)) {
260 261 262 263 264
	debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
	return;
    }

    for (;;) {
265
	buf = raddtlsget(client->ssl, IDLE_TIMEOUT * 3, &client->lock);
266
	if (!buf) {
267
	    debug(DBG_ERR, "dtlsserverrd: connection from %s lost", addr2string(client->addr, tmp, sizeof(tmp)));
268 269
	    break;
	}
270
	debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", addr2string(client->addr, tmp, sizeof(tmp)));
271 272 273 274 275 276 277 278
	rq = newrequest();
	if (!rq) {
	    free(buf);
	    continue;
	}
	rq->buf = buf;
	rq->from = client;
	if (!radsrv(rq)) {
279
	    debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr, tmp, sizeof(tmp)));
280 281 282
	    break;
	}
    }
283

284
    /* stop writer by setting ssl to NULL and give signal in case waiting for data */
285
    pthread_mutex_lock(&client->lock);
286
    client->ssl = NULL;
287
    pthread_mutex_unlock(&client->lock);
288 289 290 291 292
    pthread_mutex_lock(&client->replyq->mutex);
    pthread_cond_signal(&client->replyq->cond);
    pthread_mutex_unlock(&client->replyq->mutex);
    debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
    pthread_join(dtlsserverwrth, NULL);
293
    debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", addr2string(client->addr, tmp, sizeof(tmp)));
294 295 296 297 298 299 300 301
}

void *dtlsservernew(void *arg) {
    struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
    struct client *client;
    struct clsrvconf *conf;
    struct list_node *cur = NULL;
    X509 *cert = NULL;
302
    struct tls *accepted_tls = NULL;
303 304 305 306 307 308 309
    int s = -1;
    unsigned long error;
    struct timeval timeout;
    struct addrinfo tmpsrvaddr;
    char tmp[INET6_ADDRSTRLEN];

    debug(DBG_WARN, "dtlsservernew: incoming DTLS connection from %s", addr2string((struct sockaddr *)&params->addr, tmp, sizeof(tmp)));
310 311

    conf = find_clconf(handle, (struct sockaddr *)&params->addr, NULL);
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    if (!conf)
        goto exit;

    if (!srcres)
        dtlssetsrcres();
    memcpy(&tmpsrvaddr, srcres, sizeof(struct addrinfo));
    tmpsrvaddr.ai_addr = (struct sockaddr *)&params->bind;
    tmpsrvaddr.ai_addrlen = SOCKADDR_SIZE(params->bind);
    if ((s = bindtoaddr(&tmpsrvaddr, params->addr.ss_family, 1)) < 0)
        goto exit;
    if (connect(s, (struct sockaddr *)&params->addr, SOCKADDR_SIZE(params->addr)))
        goto exit;

    BIO_set_fd(SSL_get_rbio(params->ssl), s, BIO_NOCLOSE);
    BIO_ctrl(SSL_get_rbio(params->ssl), BIO_CTRL_DGRAM_SET_CONNECTED, 0,(struct sockaddr *)&params->addr);

    if (sslaccepttimeout(params->ssl, 30) <= 0) {
        while ((error = ERR_get_error()))
            debug(DBG_ERR, "dtlsservernew: SSL accept from %s failed: %s", conf->name, ERR_error_string(error, NULL));
        debug(DBG_ERR, "dtlsservernew: SSL_accept failed");
        goto exit;
333
    }
334 335 336 337 338 339 340 341 342
    timeout.tv_sec = 5;
    timeout.tv_usec = 0;
    if (BIO_ctrl(SSL_get_rbio(params->ssl), BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout) == -1)
        debug(DBG_WARN, "dtlsservernew: BIO_CTRL_DGRAM_SET_RECV_TIMEOUT failed");

    cert = verifytlscert(params->ssl);
    if (!cert)
        goto exit;
    accepted_tls = conf->tlsconf;
343 344

    while (conf) {
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
        if (accepted_tls == conf->tlsconf && verifyconfcert(cert, conf)) {
            X509_free(cert);
            client = addclient(conf, 1);
            if (client) {
                client->sock = s;
                client->addr = addr_copy((struct sockaddr *)&params->addr);
                client->ssl = params->ssl;
                dtlsserverrd(client);
                removeclient(client);
            } else {
                debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
            }
            goto exit;
        }
        conf = find_clconf(handle, (struct sockaddr *)&params->addr, &cur);
360 361 362 363
    }
    debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");

    if (cert)
364
    X509_free(cert);
365

366
exit:
367 368 369
    if (params->ssl) {
        SSL_shutdown(params->ssl);
        SSL_free(params->ssl);
370
    }
371 372
    if(s >= 0)
        close(s);
373 374
    free(params);
    debug(DBG_DBG, "dtlsservernew: exiting");
375
    pthread_exit(NULL);
376 377
}

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
int getConnectionInfo(int socket, struct sockaddr *from, socklen_t fromlen, struct sockaddr *to, socklen_t tolen) {
    uint8_t controlbuf[128];
    int ret, toaddrfound = 0;
    struct cmsghdr *ctrlhdr;
    struct msghdr msghdr;
    struct in6_pktinfo *info6;

    char tmp[48];

    msghdr.msg_name = from;
    msghdr.msg_namelen = fromlen;
    msghdr.msg_iov = NULL;
    msghdr.msg_iovlen = 0;
    msghdr.msg_control = controlbuf;
    msghdr.msg_controllen = sizeof(controlbuf);
    msghdr.msg_flags = 0;

    if ((ret = recvmsg(socket, &msghdr, MSG_PEEK | MSG_TRUNC)) < 0)
        return ret;

    debug(DBG_DBG, "udp packet from %s", addr2string(from, tmp, sizeof(tmp)));

    if (getsockname(socket, to, &tolen))
        return -1;
    for (ctrlhdr = CMSG_FIRSTHDR(&msghdr); ctrlhdr; ctrlhdr = CMSG_NXTHDR(&msghdr, ctrlhdr)) {
        if(ctrlhdr->cmsg_level == IPPROTO_IP && ctrlhdr->cmsg_type == IP_PKTINFO) {
            debug(DBG_DBG, "udp packet to: %s", inet_ntop(AF_INET, &((struct in_pktinfo *)CMSG_DATA(ctrlhdr))->ipi_addr, tmp, sizeof(tmp)));

            ((struct sockaddr_in *)to)->sin_addr = ((struct in_pktinfo *)CMSG_DATA(ctrlhdr))->ipi_addr;
            toaddrfound = 1;
        } else if(ctrlhdr->cmsg_level == IPPROTO_IPV6 && ctrlhdr->cmsg_type == IPV6_RECVPKTINFO) {
            info6 = (struct in6_pktinfo *)CMSG_DATA(ctrlhdr);
            debug(DBG_DBG, "udp packet to: %x", inet_ntop(AF_INET6, &info6->ipi6_addr, tmp, sizeof(tmp)));

            ((struct sockaddr_in6 *)to)->sin6_addr = info6->ipi6_addr;
            ((struct sockaddr_in6 *)to)->sin6_scope_id = info6->ipi6_ifindex;
            toaddrfound = 1;
        }
416
    }
417
    return toaddrfound ? ret : -1;
418 419
}

420 421
void *dtlslistener(void *arg) {
    int ndesc, flags, s = *(int *)arg;
422
    unsigned char buf[4];
423
    struct sockaddr_storage from, to;
424
    struct dtlsservernewparams *params;
425
    struct pollfd fds[1];
426
    pthread_t dtlsserverth;
427 428 429 430 431 432 433
    BIO *bio;
    struct clsrvconf *conf;
    SSL *ssl;
    SSL_CTX *ctx;
    char tmp[INET6_ADDRSTRLEN];

    debug(DBG_DBG, "dtlslistener: starting");
434

435 436 437 438
    if ((flags = fcntl(s,F_GETFL)) == -1)
        debugx(1, DBG_ERR, "dtlslistener: failed to get socket flags");
    if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
        debugx(1, DBG_ERR, "dtlslistener: failed to set non-blocking");
439

440
    for (;;) {
441 442 443 444 445 446 447 448 449 450
        fds[0].fd = s;
        fds[0].events = POLLIN;
    	ndesc = poll(fds, 1, -1);
        if (ndesc < 0)
            continue;

        if (getConnectionInfo(s, (struct sockaddr *)&from, sizeof(from), (struct sockaddr *)&to, sizeof(to)) < 0) {
            debug(DBG_DBG, "dtlslistener: getConnectionInfo failed");
            continue;
        }
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        conf = find_clconf(handle, (struct sockaddr *)&from, NULL);
        if (!conf) {
            debug(DBG_INFO, "dtlslistener: got UDP from unknown peer %s, ignoring", addr2string((struct sockaddr *)&from, tmp, sizeof(tmp)));
            if (recv(s, buf, 4, 0) == -1)
                debug(DBG_ERR, "dtlslistener: recv failed - %s", strerror(errno));
            continue;
        }

        pthread_mutex_lock(&conf->tlsconf->lock);
        if (!conf->tlsconf->dtlssslprep) {
            debug(DBG_DBG, "dtlslistener: no cached ssl object for this context, create new");
            ctx = tlsgetctx(handle, conf->tlsconf);
            if (!ctx) {
                pthread_mutex_unlock(&conf->tlsconf->lock);
                continue;
            }
            ssl = SSL_new(ctx);
            if (!ssl) {
                pthread_mutex_unlock(&conf->tlsconf->lock);
                continue;
            }
            bio = BIO_new_dgram(s, BIO_NOCLOSE);
            SSL_set_bio(ssl, bio, bio);
            SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
            conf->tlsconf->dtlssslprep = ssl;
        } else {
            debug(DBG_DBG, "dtlslistener: reusing cached ssl object");
            BIO_set_fd(SSL_get_rbio(conf->tlsconf->dtlssslprep), s, BIO_NOCLOSE);
        }

#if OPENSSL_VERSION_NUMBER < 0x10100000
        if(DTLSv1_listen(conf->tlsconf->dtlssslprep, &from) > 0) {
#else
        if(DTLSv1_listen(conf->tlsconf->dtlssslprep, (BIO_ADDR *)&from) > 0) {
#endif
            params = malloc(sizeof(struct dtlsservernewparams));
            memcpy(&params->addr, &from, sizeof(from));
            memcpy(&params->bind, &to, sizeof(to));
            params->ssl = conf->tlsconf->dtlssslprep;;
            if (!pthread_create(&dtlsserverth, &pthread_attr, dtlsservernew, (void *)params)) {
    		    pthread_detach(dtlsserverth);
                conf->tlsconf->dtlssslprep = NULL;
                pthread_mutex_unlock(&conf->tlsconf->lock);
                continue;
            } else {
                free(params);
            }
        }
        pthread_mutex_unlock(&conf->tlsconf->lock);
501
    }
502
    return NULL;
503 504 505
}

int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
506 507
    struct timeval socktimeout, now, start = {0,0};
    time_t wait;
508 509 510
    X509 *cert;
    SSL_CTX *ctx = NULL;
    struct hostportres *hp;
511 512
    unsigned long error;
    BIO *bio;
513

514 515
    debug(DBG_DBG, "dtlsconnect: called from %s", text);
    pthread_mutex_lock(&server->lock);
516 517 518 519 520

    if (server->state == RSP_SERVER_STATE_CONNECTED)
        server->state = RSP_SERVER_STATE_RECONNECTING;

    pthread_mutex_unlock(&server->lock);
521 522

    hp = (struct hostportres *)list_first(server->conf->hostports)->data;
523 524 525 526 527 528 529

    gettimeofday(&now, NULL);
    if (when && (now.tv_sec - when->tv_sec) < 30 ) {
        /* last connection was less than 30s ago. Delay next attempt */
        start.tv_sec = now.tv_sec + 30 - (now.tv_sec - when->tv_sec);
    }

530
    for (;;) {
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
        /* ensure previous connection is properly closed */
        if (server->ssl)
            SSL_shutdown(server->ssl);
        if (server->sock >= 0)
            close(server->sock);
        if (server->ssl)
            SSL_free(server->ssl);
        server->ssl = NULL;

        /* no sleep at startup or at first try */
        if (start.tv_sec) {
            gettimeofday(&now, NULL);
            wait = abs(now.tv_sec - start.tv_sec);
            wait = wait > 60 ? 60 : wait;

            if (timeout && (now.tv_sec - start.tv_sec) > timeout) {
                debug(DBG_DBG, "tlsconnect: timeout");
                return 0;
            }

            if (wait < 1)
                sleep(2);
            else {
                debug(DBG_INFO, "Next connection attempt to %s in %lds", server->conf->name, wait);
                sleep(wait);
            }
            debug(DBG_INFO, "tlsconnect: retry connecting to %s", server->conf->name);
        } else {
            gettimeofday(&start, NULL);
        }
        /* done sleeping */
562

563
        debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", hp->host, hp->port);
564

565 566 567 568
        if ((server->sock = bindtoaddr(srcres, hp->addrinfo->ai_family, 0)) < 0)
            continue;
        if (connect(server->sock, hp->addrinfo->ai_addr, hp->addrinfo->ai_addrlen))
            continue;
569

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        pthread_mutex_lock(&server->conf->tlsconf->lock);
        if (!(ctx = tlsgetctx(handle, server->conf->tlsconf))){
            pthread_mutex_unlock(&server->conf->tlsconf->lock);
            continue;
        }

        server->ssl = SSL_new(ctx);
        pthread_mutex_unlock(&server->conf->tlsconf->lock);
        if (!server->ssl)
            continue;

        bio = BIO_new_dgram(server->sock, BIO_CLOSE);
        BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, hp->addrinfo->ai_addr);
        SSL_set_bio(server->ssl, bio, bio);
        if (sslconnecttimeout(server->ssl, 5) <= 0) {
            while ((error = ERR_get_error()))
                debug(DBG_ERR, "dtlsconnect: SSL connect to %s failed: %s", server->conf->name, ERR_error_string(error, NULL));
            debug(DBG_ERR, "dtlsconnect: SSL connect to %s failed", server->conf->name, ERR_error_string(error, NULL));
            continue;
        }
        socktimeout.tv_sec = 5;
        socktimeout.tv_usec = 0;
        if (BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &socktimeout) == -1)
            debug(DBG_WARN, "dtlsconnect: BIO_CTRL_DGRAM_SET_RECV_TIMEOUT failed");

        cert = verifytlscert(server->ssl);
        if (!cert)
            continue;
        if (verifyconfcert(cert, server->conf)) {
            X509_free(cert);
            break;
        }
        X509_free(cert);
603
    }
604 605 606 607
    debug(DBG_WARN, "dtlsconnect: DTLS connection to %s up", server->conf->name);

    pthread_mutex_lock(&server->lock);
    server->state = RSP_SERVER_STATE_CONNECTED;
608 609
    gettimeofday(&server->lastconnecttry, NULL);
    pthread_mutex_unlock(&server->lock);
610 611 612 613
    pthread_mutex_lock(&server->newrq_mutex);
    server->conreset = 1;
    pthread_cond_signal(&server->newrq_cond);
    pthread_mutex_unlock(&server->newrq_mutex);
614 615 616 617 618 619 620 621 622
    return 1;
}

int clientradputdtls(struct server *server, unsigned char *rad) {
    int cnt;
    size_t len;
    unsigned long error;
    struct clsrvconf *conf = server->conf;

623 624 625 626 627 628
    pthread_mutex_lock(&server->lock);
    if (server->state != RSP_SERVER_STATE_CONNECTED) {
        pthread_mutex_unlock(&server->lock);
        return 0;
    }

629
    len = RADLEN(rad);
630 631 632 633 634 635 636 637 638 639 640
    while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
        switch (SSL_get_error(server->ssl, cnt)) {
            case SSL_ERROR_WANT_READ:
            case SSL_ERROR_WANT_WRITE:
                continue;
            default:
                while ((error = ERR_get_error()))
                    debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
                pthread_mutex_unlock(&server->lock);
                return 0;
        }
641 642
    }
    debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->name);
643
    pthread_mutex_unlock(&server->lock);
644 645 646 647 648 649 650
    return 1;
}

void *dtlsclientrd(void *arg) {
    struct server *server = (struct server *)arg;
    unsigned char *buf;
    struct timeval lastconnecttry;
651

652 653 654
    for (;;) {
	/* yes, lastconnecttry is really necessary */
	lastconnecttry = server->lastconnecttry;
655
    buf = raddtlsget(server->ssl, 5, &server->lock);
656
	if (!buf) {
657 658 659 660 661 662 663 664
        if(SSL_get_shutdown(server->ssl) || server->lostrqs) {
            if (SSL_get_shutdown(server->ssl))
                debug (DBG_WARN, "tlscleintrd: connection to server %s lost", server->conf->name);
            else if (server->lostrqs)
                debug (DBG_WARN, "dtlsclientrd: server %s did not respond, closing connection.", server->conf->name);
    	    dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
            server->lostrqs = 0;
        }
665 666 667 668
	    continue;
	}
	replyh(server, buf);
    }
669 670 671 672 673 674 675

    debug(DBG_INFO, "dtlsclientrd: exiting for %s", server->conf->name);
    pthread_mutex_lock(&server->lock);
    SSL_shutdown(server->ssl);
    close(server->sock);

    /* Wake up clientwr(). */
676
    server->clientrdgone = 1;
677 678 679 680
    pthread_mutex_lock(&server->newrq_mutex);
    pthread_cond_signal(&server->newrq_cond);
    pthread_mutex_unlock(&server->newrq_mutex);
    pthread_mutex_unlock(&server->lock);
681 682 683 684 685 686 687 688
    return NULL;
}

#else
const struct protodefs *dtlsinit(uint8_t h) {
    return NULL;
}
#endif
689 690 691 692

/* Local Variables: */
/* c-file-style: "stroustrup" */
/* End: */