2 * Copyright (C) 2006, 2007 Stig Venaas <venaas@uninett.no>
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.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
32 #include <sys/socket.h>
33 #include <netinet/in.h>
41 #include <openssl/ssl.h>
42 #include <openssl/rand.h>
43 #include <openssl/err.h>
44 #include <openssl/md5.h>
45 #include <openssl/hmac.h>
47 #include "radsecproxy.h"
49 static struct options options;
50 static struct client *clients = NULL;
51 static struct server *servers = NULL;
52 static struct realm *realms = NULL;
53 static struct tls *tls = NULL;
55 static int client_udp_count = 0;
56 static int client_tls_count = 0;
57 static int client_count = 0;
58 static int server_udp_count = 0;
59 static int server_tls_count = 0;
60 static int server_count = 0;
61 static int realm_count = 0;
62 static int tls_count = 0;
64 static struct peer *tcp_server_listen;
65 static struct peer *udp_server_listen;
66 static struct replyq udp_server_replyq;
67 static int udp_server_sock = -1;
68 static pthread_mutex_t *ssl_locks;
69 static long *ssl_lock_count;
73 /* callbacks for making OpenSSL thread safe */
74 unsigned long ssl_thread_id() {
75 return (unsigned long)pthread_self();
78 void ssl_locking_callback(int mode, int type, const char *file, int line) {
79 if (mode & CRYPTO_LOCK) {
80 pthread_mutex_lock(&ssl_locks[type]);
81 ssl_lock_count[type]++;
83 pthread_mutex_unlock(&ssl_locks[type]);
86 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
87 int pwdlen = strlen(userdata);
88 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
90 memcpy(buf, userdata, pwdlen);
94 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
99 err_cert = X509_STORE_CTX_get_current_cert(ctx);
100 err = X509_STORE_CTX_get_error(ctx);
101 depth = X509_STORE_CTX_get_error_depth(ctx);
103 if (depth > MAX_CERT_DEPTH) {
105 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
106 X509_STORE_CTX_set_error(ctx, err);
110 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
111 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
114 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
115 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
116 debug(DBG_WARN, "\tIssuer=%s", buf);
118 case X509_V_ERR_CERT_NOT_YET_VALID:
119 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
120 debug(DBG_WARN, "\tCertificate not yet valid");
122 case X509_V_ERR_CERT_HAS_EXPIRED:
123 debug(DBG_WARN, "Certificate has expired");
125 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
126 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
131 printf("certificate verify returns %d\n", ok);
137 void printauth(char *s, unsigned char *t) {
140 for (i = 0; i < 16; i++)
141 printf("%02x ", t[i]);
146 int resolvepeer(struct peer *peer, int ai_flags) {
147 struct addrinfo hints, *addrinfo;
149 memset(&hints, 0, sizeof(hints));
150 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
151 hints.ai_family = AF_UNSPEC;
152 hints.ai_flags = ai_flags;
153 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
154 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", peer->host, peer->port);
159 freeaddrinfo(peer->addrinfo);
160 peer->addrinfo = addrinfo;
164 int connecttoserver(struct addrinfo *addrinfo) {
166 struct addrinfo *res;
169 for (res = addrinfo; res; res = res->ai_next) {
170 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
172 debug(DBG_WARN, "connecttoserver: socket failed");
175 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
177 debug(DBG_WARN, "connecttoserver: connect failed");
184 int bindtoaddr(struct addrinfo *addrinfo) {
186 struct addrinfo *res;
188 for (res = addrinfo; res; res = res->ai_next) {
189 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
191 debug(DBG_WARN, "bindtoaddr: socket failed");
194 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
195 if (!bind(s, res->ai_addr, res->ai_addrlen))
197 debug(DBG_WARN, "bindtoaddr: bind failed");
203 /* returns the client with matching address, or NULL */
204 /* if client argument is not NULL, we only check that one client */
205 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
206 struct sockaddr_in6 *sa6 = NULL;
207 struct in_addr *a4 = NULL;
210 struct addrinfo *res;
212 if (addr->sa_family == AF_INET6) {
213 sa6 = (struct sockaddr_in6 *)addr;
214 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
215 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
217 a4 = &((struct sockaddr_in *)addr)->sin_addr;
219 c = (client ? client : clients);
220 for (i = 0; i < client_count; i++) {
221 if (c->peer.type == type)
222 for (res = c->peer.addrinfo; res; res = res->ai_next)
223 if ((a4 && res->ai_family == AF_INET &&
224 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
225 (sa6 && res->ai_family == AF_INET6 &&
226 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
235 /* returns the server with matching address, or NULL */
236 /* if server argument is not NULL, we only check that one server */
237 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
238 struct sockaddr_in6 *sa6 = NULL;
239 struct in_addr *a4 = NULL;
242 struct addrinfo *res;
244 if (addr->sa_family == AF_INET6) {
245 sa6 = (struct sockaddr_in6 *)addr;
246 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
247 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
249 a4 = &((struct sockaddr_in *)addr)->sin_addr;
251 s = (server ? server : servers);
252 for (i = 0; i < server_count; i++) {
253 if (s->peer.type == type)
254 for (res = s->peer.addrinfo; res; res = res->ai_next)
255 if ((a4 && res->ai_family == AF_INET &&
256 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
257 (sa6 && res->ai_family == AF_INET6 &&
258 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
267 /* exactly one of client and server must be non-NULL */
268 /* if *peer == NULL we return who we received from, else require it to be from peer */
269 /* return from in sa if not NULL */
270 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
273 unsigned char buf[65536], *rad;
274 struct sockaddr_storage from;
275 socklen_t fromlen = sizeof(from);
278 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
280 debug(DBG_WARN, "radudpget: recv failed");
283 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
286 debug(DBG_WARN, "radudpget: packet too small");
292 debug(DBG_WARN, "radudpget: length too small");
297 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
301 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
304 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
305 : (void *)find_server('U', (struct sockaddr *)&from, *server));
307 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
314 debug(DBG_ERR, "radudpget: malloc failed");
316 memcpy(rad, buf, len);
318 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
320 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
326 int tlsverifycert(struct peer *peer) {
334 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
335 debug(DBG_ERR, "tlsverifycert: basic validation failed");
336 while ((error = ERR_get_error()))
337 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
341 cert = SSL_get_peer_certificate(peer->ssl);
343 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
346 nm = X509_get_subject_name(cert);
349 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
352 e = X509_NAME_get_entry(nm, loc);
353 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
360 for (i = 0; i < l; i++)
365 if (l == strlen(peer->host) && !strncasecmp(peer->host, (char *)v, l)) {
366 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s, All OK", peer->host);
369 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", peer->host);
375 void tlsconnect(struct server *server, struct timeval *when, char *text) {
379 debug(DBG_DBG, "tlsconnect called from %s", text);
380 pthread_mutex_lock(&server->lock);
381 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
382 /* already reconnected, nothing to do */
383 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
384 pthread_mutex_unlock(&server->lock);
388 debug(DBG_DBG, "tlsconnect %s", text);
391 gettimeofday(&now, NULL);
392 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
393 if (server->connectionok) {
394 server->connectionok = 0;
396 } else if (elapsed < 5)
398 else if (elapsed < 300) {
399 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
401 } else if (elapsed < 100000) {
402 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
405 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
406 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->peer.host, server->peer.port);
407 if (server->sock >= 0)
409 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
410 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
414 SSL_free(server->peer.ssl);
415 server->peer.ssl = SSL_new(server->peer.ssl_ctx);
416 SSL_set_fd(server->peer.ssl, server->sock);
417 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
420 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->peer.host, server->peer.port);
421 gettimeofday(&server->lastconnecttry, NULL);
422 pthread_mutex_unlock(&server->lock);
425 unsigned char *radtlsget(SSL *ssl) {
427 unsigned char buf[4], *rad;
430 for (total = 0; total < 4; total += cnt) {
431 cnt = SSL_read(ssl, buf + total, 4 - total);
433 debug(DBG_ERR, "radtlsget: connection lost");
434 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
435 /* remote end sent close_notify, send one back */
445 debug(DBG_ERR, "radtlsget: malloc failed");
450 for (; total < len; total += cnt) {
451 cnt = SSL_read(ssl, rad + total, len - total);
453 debug(DBG_ERR, "radtlsget: connection lost");
454 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
455 /* remote end sent close_notify, send one back */
467 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
470 debug(DBG_DBG, "radtlsget: got %d bytes", total);
474 int clientradput(struct server *server, unsigned char *rad) {
478 struct timeval lastconnecttry;
481 if (server->peer.type == 'U') {
482 if (send(server->sock, rad, len, 0) >= 0) {
483 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->peer.host, server->peer.port);
486 debug(DBG_WARN, "clientradput: send failed");
490 lastconnecttry = server->lastconnecttry;
491 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
492 while ((error = ERR_get_error()))
493 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
494 tlsconnect(server, &lastconnecttry, "clientradput");
495 lastconnecttry = server->lastconnecttry;
498 server->connectionok = 1;
499 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
500 cnt, len, server->peer.host);
504 int radsign(unsigned char *rad, unsigned char *sec) {
505 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
506 static unsigned char first = 1;
507 static EVP_MD_CTX mdctx;
511 pthread_mutex_lock(&lock);
513 EVP_MD_CTX_init(&mdctx);
517 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
518 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
519 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
520 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
522 pthread_mutex_unlock(&lock);
526 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
527 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
528 static unsigned char first = 1;
529 static EVP_MD_CTX mdctx;
530 unsigned char hash[EVP_MAX_MD_SIZE];
534 pthread_mutex_lock(&lock);
536 EVP_MD_CTX_init(&mdctx);
542 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
543 EVP_DigestUpdate(&mdctx, rad, 4) &&
544 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
545 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
546 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
547 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
549 !memcmp(hash, rad + 4, 16));
550 pthread_mutex_unlock(&lock);
554 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
555 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
556 static unsigned char first = 1;
557 static HMAC_CTX hmacctx;
559 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
561 pthread_mutex_lock(&lock);
563 HMAC_CTX_init(&hmacctx);
567 memcpy(auth, authattr, 16);
568 memset(authattr, 0, 16);
570 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
571 HMAC_Update(&hmacctx, rad, RADLEN(rad));
572 HMAC_Final(&hmacctx, hash, &md_len);
573 memcpy(authattr, auth, 16);
575 debug(DBG_WARN, "message auth computation failed");
576 pthread_mutex_unlock(&lock);
580 if (memcmp(auth, hash, 16)) {
581 debug(DBG_WARN, "message authenticator, wrong value");
582 pthread_mutex_unlock(&lock);
586 pthread_mutex_unlock(&lock);
590 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
591 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
592 static unsigned char first = 1;
593 static HMAC_CTX hmacctx;
599 pthread_mutex_lock(&lock);
601 HMAC_CTX_init(&hmacctx);
605 memset(authattrval, 0, 16);
607 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
608 HMAC_Update(&hmacctx, rad, RADLEN(rad));
609 HMAC_Final(&hmacctx, authattrval, &md_len);
611 debug(DBG_WARN, "message auth computation failed");
612 pthread_mutex_unlock(&lock);
616 pthread_mutex_unlock(&lock);
620 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
622 if (ATTRTYPE(attrs) == type)
624 length -= ATTRLEN(attrs);
625 attrs += ATTRLEN(attrs);
630 void sendrq(struct server *to, struct request *rq) {
634 pthread_mutex_lock(&to->newrq_mutex);
635 /* might simplify if only try nextid, might be ok */
636 for (i = to->nextid; i < MAX_REQUESTS; i++)
637 if (!to->requests[i].buf)
639 if (i == MAX_REQUESTS) {
640 for (i = 0; i < to->nextid; i++)
641 if (!to->requests[i].buf)
643 if (i == to->nextid) {
644 debug(DBG_WARN, "No room in queue, dropping request");
646 pthread_mutex_unlock(&to->newrq_mutex);
651 rq->buf[1] = (char)i;
653 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
654 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->peer.secret)) {
656 pthread_mutex_unlock(&to->newrq_mutex);
660 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
661 to->requests[i] = *rq;
666 debug(DBG_DBG, "signalling client writer");
667 pthread_cond_signal(&to->newrq_cond);
669 pthread_mutex_unlock(&to->newrq_mutex);
672 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
673 struct replyq *replyq = to->replyq;
675 if (!radsign(buf, (unsigned char *)to->peer.secret)) {
677 debug(DBG_WARN, "sendreply: failed to sign message");
681 pthread_mutex_lock(&replyq->count_mutex);
682 if (replyq->count == replyq->size) {
683 debug(DBG_WARN, "No room in queue, dropping request");
684 pthread_mutex_unlock(&replyq->count_mutex);
689 replyq->replies[replyq->count].buf = buf;
691 replyq->replies[replyq->count].tosa = *tosa;
694 if (replyq->count == 1) {
695 debug(DBG_DBG, "signalling server writer");
696 pthread_cond_signal(&replyq->count_cond);
698 pthread_mutex_unlock(&replyq->count_mutex);
701 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
702 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
703 static unsigned char first = 1;
704 static EVP_MD_CTX mdctx;
705 unsigned char hash[EVP_MAX_MD_SIZE], *input;
707 uint8_t i, offset = 0, out[128];
709 pthread_mutex_lock(&lock);
711 EVP_MD_CTX_init(&mdctx);
717 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
718 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
719 !EVP_DigestUpdate(&mdctx, input, 16) ||
720 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
722 pthread_mutex_unlock(&lock);
725 for (i = 0; i < 16; i++)
726 out[offset + i] = hash[i] ^ in[offset + i];
727 input = out + offset - 16;
732 memcpy(in, out, len);
733 pthread_mutex_unlock(&lock);
737 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
738 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
739 static unsigned char first = 1;
740 static EVP_MD_CTX mdctx;
741 unsigned char hash[EVP_MAX_MD_SIZE], *input;
743 uint8_t i, offset = 0, out[128];
745 pthread_mutex_lock(&lock);
747 EVP_MD_CTX_init(&mdctx);
753 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
754 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
755 !EVP_DigestUpdate(&mdctx, input, 16) ||
756 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
758 pthread_mutex_unlock(&lock);
761 for (i = 0; i < 16; i++)
762 out[offset + i] = hash[i] ^ in[offset + i];
768 memcpy(in, out, len);
769 pthread_mutex_unlock(&lock);
773 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
774 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
775 static unsigned char first = 1;
776 static EVP_MD_CTX mdctx;
777 unsigned char hash[EVP_MAX_MD_SIZE];
781 pthread_mutex_lock(&lock);
783 EVP_MD_CTX_init(&mdctx);
788 printf("msppencrypt auth in: ");
789 for (i = 0; i < 16; i++)
790 printf("%02x ", auth[i]);
793 printf("msppencrypt salt in: ");
794 for (i = 0; i < 2; i++)
795 printf("%02x ", salt[i]);
798 printf("msppencrypt in: ");
799 for (i = 0; i < len; i++)
800 printf("%02x ", text[i]);
804 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
805 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
806 !EVP_DigestUpdate(&mdctx, auth, 16) ||
807 !EVP_DigestUpdate(&mdctx, salt, 2) ||
808 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
809 pthread_mutex_unlock(&lock);
814 printf("msppencrypt hash: ");
815 for (i = 0; i < 16; i++)
816 printf("%02x ", hash[i]);
820 for (i = 0; i < 16; i++)
823 for (offset = 16; offset < len; offset += 16) {
825 printf("text + offset - 16 c(%d): ", offset / 16);
826 for (i = 0; i < 16; i++)
827 printf("%02x ", (text + offset - 16)[i]);
830 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
831 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
832 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
833 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
835 pthread_mutex_unlock(&lock);
839 printf("msppencrypt hash: ");
840 for (i = 0; i < 16; i++)
841 printf("%02x ", hash[i]);
845 for (i = 0; i < 16; i++)
846 text[offset + i] ^= hash[i];
850 printf("msppencrypt out: ");
851 for (i = 0; i < len; i++)
852 printf("%02x ", text[i]);
856 pthread_mutex_unlock(&lock);
860 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
861 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
862 static unsigned char first = 1;
863 static EVP_MD_CTX mdctx;
864 unsigned char hash[EVP_MAX_MD_SIZE];
869 pthread_mutex_lock(&lock);
871 EVP_MD_CTX_init(&mdctx);
876 printf("msppdecrypt auth in: ");
877 for (i = 0; i < 16; i++)
878 printf("%02x ", auth[i]);
881 printf("msppedecrypt salt in: ");
882 for (i = 0; i < 2; i++)
883 printf("%02x ", salt[i]);
886 printf("msppedecrypt in: ");
887 for (i = 0; i < len; i++)
888 printf("%02x ", text[i]);
892 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
893 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
894 !EVP_DigestUpdate(&mdctx, auth, 16) ||
895 !EVP_DigestUpdate(&mdctx, salt, 2) ||
896 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
897 pthread_mutex_unlock(&lock);
902 printf("msppedecrypt hash: ");
903 for (i = 0; i < 16; i++)
904 printf("%02x ", hash[i]);
908 for (i = 0; i < 16; i++)
909 plain[i] = text[i] ^ hash[i];
911 for (offset = 16; offset < len; offset += 16) {
913 printf("text + offset - 16 c(%d): ", offset / 16);
914 for (i = 0; i < 16; i++)
915 printf("%02x ", (text + offset - 16)[i]);
918 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
919 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
920 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
921 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
923 pthread_mutex_unlock(&lock);
927 printf("msppedecrypt hash: ");
928 for (i = 0; i < 16; i++)
929 printf("%02x ", hash[i]);
933 for (i = 0; i < 16; i++)
934 plain[offset + i] = text[offset + i] ^ hash[i];
937 memcpy(text, plain, len);
939 printf("msppedecrypt out: ");
940 for (i = 0; i < len; i++)
941 printf("%02x ", text[i]);
945 pthread_mutex_unlock(&lock);
949 struct realm *id2realm(char *id, uint8_t len) {
951 for (i = 0; i < realm_count; i++)
952 if (!regexec(&realms[i].regex, id, 0, NULL, 0)) {
953 debug(DBG_DBG, "found matching realm: %s", realms[i].name);
959 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
962 pthread_mutex_lock(&to->newrq_mutex);
963 for (i = 0; i < MAX_REQUESTS; i++)
964 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
966 pthread_mutex_unlock(&to->newrq_mutex);
968 return i < MAX_REQUESTS;
971 int attrvalidate(unsigned char *attrs, int length) {
973 if (ATTRLEN(attrs) < 2) {
974 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
977 length -= ATTRLEN(attrs);
979 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
982 attrs += ATTRLEN(attrs);
985 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
989 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
993 if (len < 16 || len > 128 || len % 16) {
994 debug(DBG_WARN, "pwdrecrypt: invalid password length");
998 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
999 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1003 printf("pwdrecrypt: password: ");
1004 for (i = 0; i < len; i++)
1005 printf("%02x ", pwd[i]);
1008 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1009 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1015 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1018 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1019 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1022 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1023 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1029 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1030 char *oldsecret, char *newsecret) {
1031 unsigned char *attr;
1033 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1034 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1035 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1041 void respondstatusserver(struct request *rq) {
1042 unsigned char *resp;
1046 debug(DBG_ERR, "respondstatusserver: malloc failed");
1049 memcpy(resp, rq->buf, 20);
1050 resp[0] = RAD_Access_Accept;
1053 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->peer.host);
1054 sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1057 void respondreject(struct request *rq, char *message) {
1058 unsigned char *resp;
1062 len += 2 + strlen(message);
1066 debug(DBG_ERR, "respondreject: malloc failed");
1069 memcpy(resp, rq->buf, 20);
1070 resp[0] = RAD_Access_Reject;
1071 *(uint16_t *)(resp + 2) = htons(len);
1073 resp[20] = RAD_Attr_Reply_Message;
1074 resp[21] = len - 20;
1075 memcpy(resp + 22, message, len - 22);
1077 sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1080 void radsrv(struct request *rq) {
1081 uint8_t code, id, *auth, *attrs, *attr;
1083 struct server *to = NULL;
1085 unsigned char *buf, newauth[16];
1086 struct realm *realm = NULL;
1089 code = *(uint8_t *)buf;
1090 id = *(uint8_t *)(buf + 1);
1092 auth = (uint8_t *)(buf + 4);
1094 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1096 if (code != RAD_Access_Request && code != RAD_Status_Server) {
1097 debug(DBG_INFO, "radsrv: server currently accepts only access-requests and status-server, ignoring");
1105 if (!attrvalidate(attrs, len)) {
1106 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1111 if (code == RAD_Access_Request) {
1112 attr = attrget(attrs, len, RAD_Attr_User_Name);
1114 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1118 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1119 username[ATTRVALLEN(attr)] = '\0';
1120 debug(DBG_DBG, "Access Request with username: %s", username);
1122 realm = id2realm(username, strlen(username));
1124 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1130 if (to && rqinqueue(to, rq->from, id)) {
1131 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->peer.host, id);
1137 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1138 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->peer.secret))) {
1139 debug(DBG_WARN, "radsrv: message authentication failed");
1144 if (code == RAD_Status_Server) {
1145 respondstatusserver(rq);
1150 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->peer.host, username);
1151 respondreject(rq, realm->message);
1155 if (!RAND_bytes(newauth, 16)) {
1156 debug(DBG_WARN, "radsrv: failed to generate random auth");
1162 printauth("auth", auth);
1165 attr = attrget(attrs, len, RAD_Attr_User_Password);
1167 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1168 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1174 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1176 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1177 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1184 memcpy(rq->origauth, auth, 16);
1185 memcpy(auth, newauth, 16);
1189 void *clientrd(void *arg) {
1190 struct server *server = (struct server *)arg;
1191 struct client *from;
1193 unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1194 struct sockaddr_storage fromsa;
1195 struct timeval lastconnecttry;
1199 lastconnecttry = server->lastconnecttry;
1200 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1201 if (!buf && server->peer.type == 'T') {
1202 tlsconnect(server, &lastconnecttry, "clientrd");
1206 server->connectionok = 1;
1208 i = buf[1]; /* i is the id */
1211 case RAD_Access_Accept:
1212 debug(DBG_DBG, "got Access Accept with id %d", i);
1214 case RAD_Access_Reject:
1215 debug(DBG_DBG, "got Access Reject with id %d", i);
1217 case RAD_Access_Challenge:
1218 debug(DBG_DBG, "got Access Challenge with id %d", i);
1222 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1226 pthread_mutex_lock(&server->newrq_mutex);
1227 if (!server->requests[i].buf || !server->requests[i].tries) {
1228 pthread_mutex_unlock(&server->newrq_mutex);
1230 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1234 if (server->requests[i].received) {
1235 pthread_mutex_unlock(&server->newrq_mutex);
1237 debug(DBG_INFO, "clientrd: already received, ignoring");
1241 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1242 pthread_mutex_unlock(&server->newrq_mutex);
1244 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1248 from = server->requests[i].from;
1249 len = RADLEN(buf) - 20;
1252 if (!attrvalidate(attrs, len)) {
1253 pthread_mutex_unlock(&server->newrq_mutex);
1255 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1259 /* Message Authenticator */
1260 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1262 if (ATTRVALLEN(messageauth) != 16) {
1263 pthread_mutex_unlock(&server->newrq_mutex);
1265 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1268 memcpy(tmp, buf + 4, 16);
1269 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1270 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->peer.secret)) {
1271 pthread_mutex_unlock(&server->newrq_mutex);
1273 debug(DBG_WARN, "clientrd: message authentication failed");
1276 memcpy(buf + 4, tmp, 16);
1277 debug(DBG_DBG, "clientrd: message auth ok");
1280 if (*server->requests[i].buf == RAD_Status_Server) {
1281 server->requests[i].received = 1;
1282 pthread_mutex_unlock(&server->newrq_mutex);
1284 debug(DBG_INFO, "clientrd: got status server response from %s", server->peer.host);
1289 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1290 if (ATTRVALLEN(attr) <= 4)
1293 if (((uint16_t *)attr)[1] != 0 || ntohs(((uint16_t *)attr)[2]) != 311) /* 311 == MS */
1296 sublen = ATTRVALLEN(attr) - 4;
1297 subattrs = ATTRVAL(attr) + 4;
1298 if (!attrvalidate(subattrs, sublen) ||
1299 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1300 server->requests + i, server->peer.secret, from->peer.secret) ||
1301 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1302 server->requests + i, server->peer.secret, from->peer.secret))
1306 pthread_mutex_unlock(&server->newrq_mutex);
1308 debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1312 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1313 attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1314 /* we know the attribute exists */
1315 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1316 tmp[ATTRVALLEN(attr)] = '\0';
1318 case RAD_Access_Accept:
1319 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->peer.host);
1321 case RAD_Access_Reject:
1322 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->peer.host);
1327 /* once we set received = 1, requests[i] may be reused */
1328 buf[1] = (char)server->requests[i].origid;
1329 memcpy(buf + 4, server->requests[i].origauth, 16);
1331 printauth("origauth/buf+4", buf + 4);
1335 if (!createmessageauth(buf, ATTRVAL(messageauth), from->peer.secret)) {
1336 pthread_mutex_unlock(&server->newrq_mutex);
1340 debug(DBG_DBG, "clientrd: computed messageauthattr");
1343 if (from->peer.type == 'U')
1344 fromsa = server->requests[i].fromsa;
1345 server->requests[i].received = 1;
1346 pthread_mutex_unlock(&server->newrq_mutex);
1348 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1349 sendreply(from, buf, from->peer.type == 'U' ? &fromsa : NULL);
1353 void *clientwr(void *arg) {
1354 struct server *server = (struct server *)arg;
1356 pthread_t clientrdth;
1359 struct timeval now, lastsend;
1360 struct timespec timeout;
1361 struct request statsrvrq;
1362 unsigned char statsrvbuf[38];
1364 memset(&timeout, 0, sizeof(struct timespec));
1366 if (server->statusserver) {
1367 memset(&statsrvrq, 0, sizeof(struct request));
1368 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1369 statsrvbuf[0] = RAD_Status_Server;
1371 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1372 statsrvbuf[21] = 18;
1373 gettimeofday(&lastsend, NULL);
1376 if (server->peer.type == 'U') {
1377 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1378 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1380 tlsconnect(server, NULL, "new client");
1382 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1383 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1386 pthread_mutex_lock(&server->newrq_mutex);
1387 if (!server->newrq) {
1388 gettimeofday(&now, NULL);
1389 if (server->statusserver) {
1390 /* random 0-7 seconds */
1391 RAND_bytes(&rnd, 1);
1393 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1394 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1396 if (timeout.tv_sec) {
1397 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1398 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1401 debug(DBG_DBG, "clientwr: waiting for new request");
1402 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1405 if (server->newrq) {
1406 debug(DBG_DBG, "clientwr: got new request");
1409 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1410 pthread_mutex_unlock(&server->newrq_mutex);
1412 for (i = 0; i < MAX_REQUESTS; i++) {
1413 pthread_mutex_lock(&server->newrq_mutex);
1414 while (!server->requests[i].buf && i < MAX_REQUESTS)
1416 if (i == MAX_REQUESTS) {
1417 pthread_mutex_unlock(&server->newrq_mutex);
1420 rq = server->requests + i;
1423 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1425 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1427 /* setting this to NULL means that it can be reused */
1430 pthread_mutex_unlock(&server->newrq_mutex);
1434 gettimeofday(&now, NULL);
1435 if (now.tv_sec < rq->expiry.tv_sec) {
1436 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1437 timeout.tv_sec = rq->expiry.tv_sec;
1438 pthread_mutex_unlock(&server->newrq_mutex);
1442 if (rq->tries == (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1443 ? 1 : REQUEST_RETRIES)) {
1444 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1445 if (*rq->buf == RAD_Status_Server)
1446 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->peer.host);
1448 /* setting this to NULL means that it can be reused */
1450 pthread_mutex_unlock(&server->newrq_mutex);
1453 pthread_mutex_unlock(&server->newrq_mutex);
1455 rq->expiry.tv_sec = now.tv_sec +
1456 (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1457 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1458 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1459 timeout.tv_sec = rq->expiry.tv_sec;
1461 clientradput(server, server->requests[i].buf);
1462 gettimeofday(&lastsend, NULL);
1464 if (server->statusserver) {
1465 gettimeofday(&now, NULL);
1466 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1467 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1468 debug(DBG_WARN, "clientwr: failed to generate random auth");
1471 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1472 if (!statsrvrq.buf) {
1473 debug(DBG_ERR, "clientwr: malloc failed");
1476 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1477 debug(DBG_DBG, "clientwr: sending status server to %s", server->peer.host);
1478 lastsend.tv_sec = now.tv_sec;
1479 sendrq(server, &statsrvrq);
1485 void *udpserverwr(void *arg) {
1486 struct replyq *replyq = &udp_server_replyq;
1487 struct reply *reply = replyq->replies;
1489 pthread_mutex_lock(&replyq->count_mutex);
1491 while (!replyq->count) {
1492 debug(DBG_DBG, "udp server writer, waiting for signal");
1493 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1494 debug(DBG_DBG, "udp server writer, got signal");
1496 pthread_mutex_unlock(&replyq->count_mutex);
1498 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1499 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1500 debug(DBG_WARN, "sendudp: send failed");
1503 pthread_mutex_lock(&replyq->count_mutex);
1505 memmove(replyq->replies, replyq->replies + 1,
1506 replyq->count * sizeof(struct reply));
1510 void *udpserverrd(void *arg) {
1512 pthread_t udpserverwrth;
1514 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1515 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1517 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1518 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1520 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1521 debugx(1, DBG_ERR, "pthread_create failed");
1524 memset(&rq, 0, sizeof(struct request));
1525 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1530 void *tlsserverwr(void *arg) {
1532 unsigned long error;
1533 struct client *client = (struct client *)arg;
1534 struct replyq *replyq;
1536 debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1537 replyq = client->replyq;
1538 pthread_mutex_lock(&replyq->count_mutex);
1540 while (!replyq->count) {
1541 if (client->peer.ssl) {
1542 debug(DBG_DBG, "tls server writer, waiting for signal");
1543 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1544 debug(DBG_DBG, "tls server writer, got signal");
1546 if (!client->peer.ssl) {
1547 /* ssl might have changed while waiting */
1548 pthread_mutex_unlock(&replyq->count_mutex);
1549 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1553 pthread_mutex_unlock(&replyq->count_mutex);
1554 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1556 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1557 cnt, RADLEN(replyq->replies->buf));
1559 while ((error = ERR_get_error()))
1560 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1561 free(replyq->replies->buf);
1563 pthread_mutex_lock(&replyq->count_mutex);
1565 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1569 void *tlsserverrd(void *arg) {
1571 unsigned long error;
1573 struct client *client = (struct client *)arg;
1574 pthread_t tlsserverwrth;
1577 debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1578 ssl = client->peer.ssl;
1580 if (SSL_accept(ssl) <= 0) {
1581 while ((error = ERR_get_error()))
1582 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1583 debug(DBG_ERR, "SSL_accept failed");
1586 if (tlsverifycert(&client->peer)) {
1587 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1588 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1592 memset(&rq, 0, sizeof(struct request));
1593 rq.buf = radtlsget(client->peer.ssl);
1596 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1600 debug(DBG_ERR, "tlsserverrd: connection lost");
1601 /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1602 client->peer.ssl = NULL;
1603 pthread_mutex_lock(&client->replyq->count_mutex);
1604 pthread_cond_signal(&client->replyq->count_cond);
1605 pthread_mutex_unlock(&client->replyq->count_mutex);
1606 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1607 pthread_join(tlsserverwrth, NULL);
1611 s = SSL_get_fd(ssl);
1613 shutdown(s, SHUT_RDWR);
1615 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1616 client->peer.ssl = NULL;
1621 pthread_t tlsserverth;
1623 struct sockaddr_storage from;
1624 size_t fromlen = sizeof(from);
1625 struct client *client;
1627 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1628 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1631 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1632 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1635 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1637 debug(DBG_WARN, "accept failed");
1640 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1642 client = find_client('T', (struct sockaddr *)&from, NULL);
1644 debug(DBG_WARN, "ignoring request, not a known TLS client");
1645 shutdown(snew, SHUT_RDWR);
1650 if (client->peer.ssl) {
1651 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1652 shutdown(snew, SHUT_RDWR);
1656 client->peer.ssl = SSL_new(client->peer.ssl_ctx);
1657 SSL_set_fd(client->peer.ssl, snew);
1658 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1659 debug(DBG_ERR, "tlslistener: pthread_create failed");
1660 SSL_free(client->peer.ssl);
1661 shutdown(snew, SHUT_RDWR);
1663 client->peer.ssl = NULL;
1666 pthread_detach(tlsserverth);
1671 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
1675 unsigned long error;
1677 if (!certfile || !certkeyfile)
1678 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
1680 if (!cacertfile && !cacertpath)
1681 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
1684 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
1685 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1686 for (i = 0; i < CRYPTO_num_locks(); i++) {
1687 ssl_lock_count[i] = 0;
1688 pthread_mutex_init(&ssl_locks[i], NULL);
1690 CRYPTO_set_id_callback(ssl_thread_id);
1691 CRYPTO_set_locking_callback(ssl_locking_callback);
1693 SSL_load_error_strings();
1696 while (!RAND_status()) {
1697 time_t t = time(NULL);
1698 pid_t pid = getpid();
1699 RAND_seed((unsigned char *)&t, sizeof(time_t));
1700 RAND_seed((unsigned char *)&pid, sizeof(pid));
1703 ctx = SSL_CTX_new(TLSv1_method());
1705 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
1706 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
1708 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
1709 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
1710 !SSL_CTX_check_private_key(ctx) ||
1711 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
1712 while ((error = ERR_get_error()))
1713 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
1714 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
1717 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
1718 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
1721 tls = realloc(tls, tls_count * sizeof(struct tls));
1723 debugx(1, DBG_ERR, "malloc failed");
1724 new = tls + tls_count - 1;
1725 memset(new, 0, sizeof(struct tls));
1726 new->name = stringcopy(value, 0);
1728 debugx(1, DBG_ERR, "malloc failed");
1731 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
1736 for (i = 0; i < tls_count; i++)
1738 SSL_CTX_free(tls[i].ctx);
1744 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
1745 int i, c1 = -1, c2 = -1;
1746 for (i = 0; i < tls_count; i++) {
1747 if (!strcasecmp(tls[i].name, alt1)) {
1751 if (c2 == -1 && alt2 && !strcasecmp(tls[i].name, alt2))
1755 i = (c1 == -1 ? c2 : c1);
1762 void addrealm(char *value, char *server, char *message) {
1764 struct realm *realm;
1765 char *s, *regex = NULL;
1768 for (i = 0; i < server_count; i++)
1769 if (!strcasecmp(server, servers[i].peer.host))
1771 if (i == server_count)
1772 debugx(1, DBG_ERR, "addrealm failed, no server %s", server);
1775 if (*value == '/') {
1776 /* regexp, remove optional trailing / if present */
1777 if (value[strlen(value) - 1] == '/')
1778 value[strlen(value) - 1] = '\0';
1780 /* not a regexp, let us make it one */
1781 if (*value == '*' && !value[1])
1782 regex = stringcopy(".*", 0);
1784 for (n = 0, s = value; *s;)
1787 regex = malloc(strlen(value) + n + 3);
1790 for (n = 1, s = value; *s; s++) {
1800 debugx(1, DBG_ERR, "malloc failed");
1801 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
1805 realms = realloc(realms, realm_count * sizeof(struct realm));
1807 debugx(1, DBG_ERR, "malloc failed");
1808 realm = realms + realm_count - 1;
1809 memset(realm, 0, sizeof(struct realm));
1810 realm->name = stringcopy(value, 0);
1812 debugx(1, DBG_ERR, "malloc failed");
1813 if (message && strlen(message) > 253)
1814 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
1815 realm->message = message;
1817 realm->server = servers + i;
1818 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
1819 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
1822 debug(DBG_DBG, "addrealm: added realm %s for server %s", value, server);
1825 char *parsehostport(char *s, struct peer *peer) {
1830 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1834 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1836 debugx(1, DBG_ERR, "no ] matching initial [");
1840 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1843 debugx(1, DBG_ERR, "missing host/address");
1845 peer->host = stringcopy(field, p - field);
1848 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1849 debugx(1, DBG_ERR, "unexpected character after ]");
1852 /* port number or service name is specified */;
1854 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1856 debugx(1, DBG_ERR, "syntax error, : but no following port");
1857 peer->port = stringcopy(field, p - field);
1859 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1863 FILE *openconfigfile(const char *filename) {
1865 char pathname[100], *base = NULL;
1867 f = fopen(filename, "r");
1869 debug(DBG_DBG, "reading config file %s", filename);
1873 if (strlen(filename) + 1 <= sizeof(pathname)) {
1874 /* basename() might modify the string */
1875 strcpy(pathname, filename);
1876 base = basename(pathname);
1877 f = fopen(base, "r");
1881 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1883 debug(DBG_DBG, "reading config file %s", base);
1887 struct peer *server_create(char type) {
1888 struct peer *server;
1891 server = malloc(sizeof(struct peer));
1893 debugx(1, DBG_ERR, "malloc failed");
1894 memset(server, 0, sizeof(struct peer));
1895 server->type = type;
1896 conf = (type == 'T' ? options.listentcp : options.listenudp);
1898 parsehostport(conf, server);
1899 if (!strcmp(server->host, "*")) {
1901 server->host = NULL;
1904 server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1905 if (!resolvepeer(server, AI_PASSIVE))
1906 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1910 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
1911 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
1912 char *t = s, *q, *r;
1914 if (!t || !token || !del)
1916 while (*t && strchr(del, *t))
1918 if (!*t || (comment && strchr(comment, *t))) {
1920 return t + 1; /* needs to be non-NULL, but value doesn't matter */
1922 if (quote && (q = strchr(quote, *t))) {
1925 while (*t && *t != *q)
1927 if (!*t || (t[1] && !strchr(del, t[1])))
1935 while (*t && !strchr(del, *t))
1941 /* Parses config with following syntax:
1944 * option-name = value
1946 * option-name value {
1947 * option-name [=] value
1951 void getgeneralconfig(FILE *f, char *block, ...) {
1954 /* initialise lots of stuff to avoid stupid compiler warnings */
1955 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL;
1956 int type = 0, tcount, conftype = 0;
1957 void (*cbk)(FILE *, char *, char *, char *) = NULL;
1959 while (fgets(line, 1024, f)) {
1961 for (tcount = 0; tcount < 3; tcount++) {
1962 s = strtokenquote(s, &tokens[tcount], " \t\n", "\"'", tcount ? NULL : "#");
1964 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
1965 if (!tokens[tcount])
1968 if (!tcount || **tokens == '#')
1971 if (**tokens == '}') {
1974 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
1981 conftype = CONF_STR;
1984 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
1987 conftype = CONF_STR;
1990 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
1993 conftype = CONF_CBK;
1999 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2000 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2004 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2006 va_start(ap, block);
2007 while ((word = va_arg(ap, char *))) {
2008 type = va_arg(ap, int);
2011 str = va_arg(ap, char **);
2013 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2016 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2019 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2021 if (!strcasecmp(opt, word))
2028 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2029 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2032 if (type != conftype) {
2034 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2035 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2041 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2043 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2044 *str = stringcopy(val, 0);
2047 optval = malloc(strlen(opt) + strlen(val) + 2);
2049 debugx(1, DBG_ERR, "malloc failed");
2050 sprintf(optval, "%s %s", opt, val);
2051 cbk(f, optval, opt, val);
2055 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2060 void confclsrv_cb(FILE *f, char *block, char *opt, char *val) {
2061 char *type = NULL, *secret = NULL, *port = NULL, *tls = NULL, *statusserver = NULL;
2062 struct client *client = NULL;
2063 struct server *server = NULL;
2066 debug(DBG_DBG, "confclsrv_cb called for %s", block);
2068 if (!strcasecmp(opt, "client")) {
2069 getgeneralconfig(f, block,
2070 "type", CONF_STR, &type,
2071 "secret", CONF_STR, &secret,
2072 "tls", CONF_STR, &tls,
2076 clients = realloc(clients, client_count * sizeof(struct client));
2078 debugx(1, DBG_ERR, "malloc failed");
2079 client = clients + client_count - 1;
2080 memset(client, 0, sizeof(struct client));
2081 peer = &client->peer;
2083 getgeneralconfig(f, block,
2084 "type", CONF_STR, &type,
2085 "secret", CONF_STR, &secret,
2086 "port", CONF_STR, &port,
2087 "tls", CONF_STR, &tls,
2088 "StatusServer", CONF_STR, &statusserver,
2092 servers = realloc(servers, server_count * sizeof(struct server));
2094 debugx(1, DBG_ERR, "malloc failed");
2095 server = servers + server_count - 1;
2096 memset(server, 0, sizeof(struct server));
2097 peer = &server->peer;
2100 if (!strcasecmp(statusserver, "on"))
2101 server->statusserver = 1;
2102 else if (strcasecmp(statusserver, "off"))
2103 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2108 peer->host = stringcopy(val, 0);
2110 if (type && !strcasecmp(type, "udp")) {
2117 peer->port = stringcopy(DEFAULT_UDP_PORT, 0);
2119 } else if (type && !strcasecmp(type, "tls")) {
2121 peer->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2124 peer->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2127 peer->port = stringcopy(DEFAULT_TLS_PORT, 0);
2130 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2133 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2136 if (!resolvepeer(peer, 0))
2137 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
2140 if (peer->type == 'U')
2141 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2142 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2144 peer->secret = secret;
2148 if (peer->type == 'U')
2149 client->replyq = &udp_server_replyq;
2151 client->replyq = malloc(sizeof(struct replyq));
2152 if (!client->replyq)
2153 debugx(1, DBG_ERR, "malloc failed");
2154 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
2155 if (!client->replyq->replies)
2156 debugx(1, DBG_ERR, "malloc failed");
2157 client->replyq->size = MAX_REQUESTS;
2158 client->replyq->count = 0;
2159 pthread_mutex_init(&client->replyq->count_mutex, NULL);
2160 pthread_cond_init(&client->replyq->count_cond, NULL);
2163 pthread_mutex_init(&server->lock, NULL);
2165 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
2166 if (!server->requests)
2167 debugx(1, DBG_ERR, "malloc failed");
2169 pthread_mutex_init(&server->newrq_mutex, NULL);
2170 pthread_cond_init(&server->newrq_cond, NULL);
2174 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2175 char *server = NULL, *msg = NULL;
2177 debug(DBG_DBG, "confrealm_cb called for %s", block);
2179 getgeneralconfig(f, block,
2180 "server", CONF_STR, &server,
2181 "ReplyMessage", CONF_STR, &msg,
2185 addrealm(val, server, msg);
2189 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2190 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2192 debug(DBG_DBG, "conftls_cb called for %s", block);
2194 getgeneralconfig(f, block,
2195 "CACertificateFile", CONF_STR, &cacertfile,
2196 "CACertificatePath", CONF_STR, &cacertpath,
2197 "CertificateFile", CONF_STR, &certfile,
2198 "CertificateKeyFile", CONF_STR, &certkeyfile,
2199 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2203 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2211 void getmainconfig(const char *configfile) {
2213 char *loglevel = NULL;
2215 f = openconfigfile(configfile);
2216 memset(&options, 0, sizeof(options));
2218 getgeneralconfig(f, NULL,
2219 "ListenUDP", CONF_STR, &options.listenudp,
2220 "ListenTCP", CONF_STR, &options.listentcp,
2221 "LogLevel", CONF_STR, &loglevel,
2222 "LogDestination", CONF_STR, &options.logdestination,
2223 "Client", CONF_CBK, confclsrv_cb,
2224 "Server", CONF_CBK, confclsrv_cb,
2225 "Realm", CONF_CBK, confrealm_cb,
2226 "TLS", CONF_CBK, conftls_cb,
2233 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2234 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2235 options.loglevel = *loglevel - '0';
2239 if (client_udp_count) {
2240 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
2241 if (!udp_server_replyq.replies)
2242 debugx(1, DBG_ERR, "malloc failed");
2243 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
2244 udp_server_replyq.count = 0;
2245 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
2246 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
2250 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2253 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2256 *configfile = optarg;
2259 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2260 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2261 *loglevel = *optarg - '0';
2267 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2272 if (!(argc - optind))
2276 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2280 int main(int argc, char **argv) {
2281 pthread_t udpserverth;
2283 uint8_t foreground = 0, loglevel = 0;
2284 char *configfile = NULL;
2286 debug_init("radsecproxy");
2287 debug_set_level(DEBUG_LEVEL);
2288 getargs(argc, argv, &foreground, &loglevel, &configfile);
2290 debug_set_level(loglevel);
2291 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2292 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2294 options.loglevel = loglevel;
2295 else if (options.loglevel)
2296 debug_set_level(options.loglevel);
2298 options.logdestination = NULL;
2300 if (!options.logdestination)
2301 options.logdestination = "x-syslog:///";
2302 debug_set_destination(options.logdestination);
2306 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2308 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2310 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2312 if (!foreground && (daemon(0, 0) < 0))
2313 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2315 if (client_udp_count) {
2316 udp_server_listen = server_create('U');
2317 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2318 debugx(1, DBG_ERR, "pthread_create failed");
2321 for (i = 0; i < server_count; i++)
2322 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2323 debugx(1, DBG_ERR, "pthread_create failed");
2325 if (client_tls_count) {
2326 tcp_server_listen = server_create('T');
2327 return tlslistener();
2330 /* just hang around doing nothing, anything to do here? */