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.
11 * radius keep alives (server status)
12 * setsockopt(keepalive...), check if openssl has some keepalive feature
15 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
16 * rd is responsible for init and launching wr
17 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
18 * each tlsserverrd launches tlsserverwr
19 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
20 * for init and launching rd
22 * serverrd will receive a request, processes it and puts it in the requestq of
23 * the appropriate clientwr
24 * clientwr monitors its requestq and sends requests
25 * clientrd looks for responses, processes them and puts them in the replyq of
26 * the peer the request came from
27 * serverwr monitors its reply and sends replies
29 * In addition to the main thread, we have:
30 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
31 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
32 * For each TLS peer connecting to us there will be 2 more TLS threads
33 * This is only for connected peers
34 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
35 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 #include <sys/socket.h>
39 #include <netinet/in.h>
47 #include <openssl/ssl.h>
48 #include <openssl/rand.h>
49 #include <openssl/err.h>
50 #include <openssl/md5.h>
51 #include <openssl/hmac.h>
53 #include "radsecproxy.h"
55 static struct options options;
56 static struct client *clients = NULL;
57 static struct server *servers = NULL;
58 static struct realm *realms = NULL;
60 static int client_udp_count = 0;
61 static int client_tls_count = 0;
62 static int client_count = 0;
63 static int server_udp_count = 0;
64 static int server_tls_count = 0;
65 static int server_count = 0;
66 static int realm_count = 0;
68 static struct peer *tcp_server_listen;
69 static struct peer *udp_server_listen;
70 static struct replyq udp_server_replyq;
71 static int udp_server_sock = -1;
72 static pthread_mutex_t *ssl_locks;
73 static long *ssl_lock_count;
74 static SSL_CTX *ssl_ctx = NULL;
78 /* callbacks for making OpenSSL thread safe */
79 unsigned long ssl_thread_id() {
80 return (unsigned long)pthread_self();
83 void ssl_locking_callback(int mode, int type, const char *file, int line) {
84 if (mode & CRYPTO_LOCK) {
85 pthread_mutex_lock(&ssl_locks[type]);
86 ssl_lock_count[type]++;
88 pthread_mutex_unlock(&ssl_locks[type]);
91 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
92 int pwdlen = strlen(userdata);
93 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
95 memcpy(buf, userdata, pwdlen);
99 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
104 err_cert = X509_STORE_CTX_get_current_cert(ctx);
105 err = X509_STORE_CTX_get_error(ctx);
106 depth = X509_STORE_CTX_get_error_depth(ctx);
108 if (depth > MAX_CERT_DEPTH) {
110 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
111 X509_STORE_CTX_set_error(ctx, err);
115 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
116 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
119 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
120 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
121 debug(DBG_WARN, "\tIssuer=%s", buf);
123 case X509_V_ERR_CERT_NOT_YET_VALID:
124 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
125 debug(DBG_WARN, "\tCertificate not yet valid");
127 case X509_V_ERR_CERT_HAS_EXPIRED:
128 debug(DBG_WARN, "Certificate has expired");
130 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
131 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
136 printf("certificate verify returns %d\n", ok);
141 SSL_CTX *ssl_init() {
146 if (!options.tlscertificatefile || !options.tlscertificatekeyfile)
147 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS");
149 if (!options.tlscacertificatefile && !options.tlscacertificatepath)
150 debugx(1, DBG_ERR, "CA Certificate file/path need to be configured");
152 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
153 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
154 for (i = 0; i < CRYPTO_num_locks(); i++) {
155 ssl_lock_count[i] = 0;
156 pthread_mutex_init(&ssl_locks[i], NULL);
158 CRYPTO_set_id_callback(ssl_thread_id);
159 CRYPTO_set_locking_callback(ssl_locking_callback);
161 SSL_load_error_strings();
164 while (!RAND_status()) {
165 time_t t = time(NULL);
166 pid_t pid = getpid();
167 RAND_seed((unsigned char *)&t, sizeof(time_t));
168 RAND_seed((unsigned char *)&pid, sizeof(pid));
171 ctx = SSL_CTX_new(TLSv1_method());
172 if (options.tlscertificatekeypassword) {
173 SSL_CTX_set_default_passwd_cb_userdata(ctx, options.tlscertificatekeypassword);
174 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
176 if (SSL_CTX_use_certificate_chain_file(ctx, options.tlscertificatefile) &&
177 SSL_CTX_use_PrivateKey_file(ctx, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) &&
178 SSL_CTX_check_private_key(ctx) &&
179 SSL_CTX_load_verify_locations(ctx, options.tlscacertificatefile, options.tlscacertificatepath)) {
180 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
181 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
185 while ((error = ERR_get_error()))
186 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
187 debug(DBG_ERR, "Error initialising SSL/TLS");
192 void printauth(char *s, unsigned char *t) {
195 for (i = 0; i < 16; i++)
196 printf("%02x ", t[i]);
201 int resolvepeer(struct peer *peer, int ai_flags) {
202 struct addrinfo hints, *addrinfo;
204 memset(&hints, 0, sizeof(hints));
205 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
206 hints.ai_family = AF_UNSPEC;
207 hints.ai_flags = ai_flags;
208 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
209 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", peer->host, peer->port);
214 freeaddrinfo(peer->addrinfo);
215 peer->addrinfo = addrinfo;
219 int connecttoserver(struct addrinfo *addrinfo) {
221 struct addrinfo *res;
223 for (res = addrinfo; res; res = res->ai_next) {
224 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
226 debug(DBG_WARN, "connecttoserver: socket failed");
229 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
231 debug(DBG_WARN, "connecttoserver: connect failed");
238 int bindtoaddr(struct addrinfo *addrinfo) {
240 struct addrinfo *res;
242 for (res = addrinfo; res; res = res->ai_next) {
243 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
245 debug(DBG_WARN, "bindtoaddr: socket failed");
248 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
249 if (!bind(s, res->ai_addr, res->ai_addrlen))
251 debug(DBG_WARN, "bindtoaddr: bind failed");
257 /* returns the client with matching address, or NULL */
258 /* if client argument is not NULL, we only check that one client */
259 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
260 struct sockaddr_in6 *sa6;
261 struct in_addr *a4 = NULL;
264 struct addrinfo *res;
266 if (addr->sa_family == AF_INET6) {
267 sa6 = (struct sockaddr_in6 *)addr;
268 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
269 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
271 a4 = &((struct sockaddr_in *)addr)->sin_addr;
273 c = (client ? client : clients);
274 for (i = 0; i < client_count; i++) {
275 if (c->peer.type == type)
276 for (res = c->peer.addrinfo; res; res = res->ai_next)
277 if ((a4 && res->ai_family == AF_INET &&
278 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
279 (res->ai_family == AF_INET6 &&
280 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
289 /* returns the server with matching address, or NULL */
290 /* if server argument is not NULL, we only check that one server */
291 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
292 struct sockaddr_in6 *sa6;
293 struct in_addr *a4 = NULL;
296 struct addrinfo *res;
298 if (addr->sa_family == AF_INET6) {
299 sa6 = (struct sockaddr_in6 *)addr;
300 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
301 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
303 a4 = &((struct sockaddr_in *)addr)->sin_addr;
305 s = (server ? server : servers);
306 for (i = 0; i < server_count; i++) {
307 if (s->peer.type == type)
308 for (res = s->peer.addrinfo; res; res = res->ai_next)
309 if ((a4 && res->ai_family == AF_INET &&
310 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
311 (res->ai_family == AF_INET6 &&
312 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
321 /* exactly one of client and server must be non-NULL */
322 /* if *peer == NULL we return who we received from, else require it to be from peer */
323 /* return from in sa if not NULL */
324 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
327 unsigned char buf[65536], *rad;
328 struct sockaddr_storage from;
329 socklen_t fromlen = sizeof(from);
332 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
334 debug(DBG_WARN, "radudpget: recv failed");
337 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
340 debug(DBG_WARN, "radudpget: packet too small");
346 debug(DBG_WARN, "radudpget: length too small");
351 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
355 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
358 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
359 : (void *)find_server('U', (struct sockaddr *)&from, *server));
361 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
368 debug(DBG_ERR, "radudpget: malloc failed");
370 memcpy(rad, buf, len);
372 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
374 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
380 int tlsverifycert(struct peer *peer) {
388 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
389 debug(DBG_ERR, "tlsverifycert: basic validation failed");
390 while ((error = ERR_get_error()))
391 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
395 cert = SSL_get_peer_certificate(peer->ssl);
397 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
400 nm = X509_get_subject_name(cert);
403 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
406 e = X509_NAME_get_entry(nm, loc);
407 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
414 for (i = 0; i < l; i++)
419 if (l == strlen(peer->host) && !strncasecmp(peer->host, (char *)v, l)) {
420 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s, All OK", peer->host);
423 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", peer->host);
429 void tlsconnect(struct server *server, struct timeval *when, char *text) {
433 debug(DBG_DBG, "tlsconnect called from %s", text);
434 pthread_mutex_lock(&server->lock);
435 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
436 /* already reconnected, nothing to do */
437 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
438 pthread_mutex_unlock(&server->lock);
442 debug(DBG_DBG, "tlsconnect %s", text);
445 gettimeofday(&now, NULL);
446 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
447 if (server->connectionok) {
448 server->connectionok = 0;
450 } else if (elapsed < 5)
452 else if (elapsed < 300) {
453 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
455 } else if (elapsed < 100000) {
456 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
459 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
460 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->peer.host, server->peer.port);
461 if (server->sock >= 0)
463 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
464 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
468 SSL_free(server->peer.ssl);
469 server->peer.ssl = SSL_new(ssl_ctx);
470 SSL_set_fd(server->peer.ssl, server->sock);
471 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
474 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->peer.host, server->peer.port);
475 gettimeofday(&server->lastconnecttry, NULL);
476 pthread_mutex_unlock(&server->lock);
479 unsigned char *radtlsget(SSL *ssl) {
481 unsigned char buf[4], *rad;
484 for (total = 0; total < 4; total += cnt) {
485 cnt = SSL_read(ssl, buf + total, 4 - total);
487 debug(DBG_ERR, "radtlsget: connection lost");
488 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
489 /* remote end sent close_notify, send one back */
499 debug(DBG_ERR, "radtlsget: malloc failed");
504 for (; total < len; total += cnt) {
505 cnt = SSL_read(ssl, rad + total, len - total);
507 debug(DBG_ERR, "radtlsget: connection lost");
508 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
509 /* remote end sent close_notify, send one back */
521 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
524 debug(DBG_DBG, "radtlsget: got %d bytes", total);
528 int clientradput(struct server *server, unsigned char *rad) {
532 struct timeval lastconnecttry;
535 if (server->peer.type == 'U') {
536 if (send(server->sock, rad, len, 0) >= 0) {
537 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->peer.host, server->peer.port);
540 debug(DBG_WARN, "clientradput: send failed");
544 lastconnecttry = server->lastconnecttry;
545 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
546 while ((error = ERR_get_error()))
547 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
548 tlsconnect(server, &lastconnecttry, "clientradput");
549 lastconnecttry = server->lastconnecttry;
552 server->connectionok = 1;
553 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
554 cnt, len, server->peer.host);
558 int radsign(unsigned char *rad, unsigned char *sec) {
559 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
560 static unsigned char first = 1;
561 static EVP_MD_CTX mdctx;
565 pthread_mutex_lock(&lock);
567 EVP_MD_CTX_init(&mdctx);
571 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
572 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
573 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
574 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
576 pthread_mutex_unlock(&lock);
580 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
581 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
582 static unsigned char first = 1;
583 static EVP_MD_CTX mdctx;
584 unsigned char hash[EVP_MAX_MD_SIZE];
588 pthread_mutex_lock(&lock);
590 EVP_MD_CTX_init(&mdctx);
596 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
597 EVP_DigestUpdate(&mdctx, rad, 4) &&
598 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
599 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
600 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
601 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
603 !memcmp(hash, rad + 4, 16));
604 pthread_mutex_unlock(&lock);
608 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
609 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
610 static unsigned char first = 1;
611 static HMAC_CTX hmacctx;
613 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
615 pthread_mutex_lock(&lock);
617 HMAC_CTX_init(&hmacctx);
621 memcpy(auth, authattr, 16);
622 memset(authattr, 0, 16);
624 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
625 HMAC_Update(&hmacctx, rad, RADLEN(rad));
626 HMAC_Final(&hmacctx, hash, &md_len);
627 memcpy(authattr, auth, 16);
629 debug(DBG_WARN, "message auth computation failed");
630 pthread_mutex_unlock(&lock);
634 if (memcmp(auth, hash, 16)) {
635 debug(DBG_WARN, "message authenticator, wrong value");
636 pthread_mutex_unlock(&lock);
640 pthread_mutex_unlock(&lock);
644 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
645 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
646 static unsigned char first = 1;
647 static HMAC_CTX hmacctx;
653 pthread_mutex_lock(&lock);
655 HMAC_CTX_init(&hmacctx);
659 memset(authattrval, 0, 16);
661 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
662 HMAC_Update(&hmacctx, rad, RADLEN(rad));
663 HMAC_Final(&hmacctx, authattrval, &md_len);
665 debug(DBG_WARN, "message auth computation failed");
666 pthread_mutex_unlock(&lock);
670 pthread_mutex_unlock(&lock);
674 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type, uint8_t *len) {
676 if (attrs[RAD_Attr_Type] == type) {
678 *len = attrs[RAD_Attr_Length] - 2;
679 return &attrs[RAD_Attr_Value];
681 length -= attrs[RAD_Attr_Length];
682 attrs += attrs[RAD_Attr_Length];
687 void sendrq(struct server *to, struct client *from, struct request *rq) {
691 pthread_mutex_lock(&to->newrq_mutex);
692 /* might simplify if only try nextid, might be ok */
693 for (i = to->nextid; i < MAX_REQUESTS; i++)
694 if (!to->requests[i].buf)
696 if (i == MAX_REQUESTS) {
697 for (i = 0; i < to->nextid; i++)
698 if (!to->requests[i].buf)
700 if (i == to->nextid) {
701 debug(DBG_WARN, "No room in queue, dropping request");
702 pthread_mutex_unlock(&to->newrq_mutex);
708 rq->buf[1] = (char)i;
709 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
711 attrval = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator, NULL);
712 if (attrval && !createmessageauth(rq->buf, attrval, to->peer.secret))
715 to->requests[i] = *rq;
719 debug(DBG_DBG, "signalling client writer");
720 pthread_cond_signal(&to->newrq_cond);
722 pthread_mutex_unlock(&to->newrq_mutex);
725 void sendreply(struct client *to, struct server *from, unsigned char *buf, struct sockaddr_storage *tosa) {
726 struct replyq *replyq = to->replyq;
728 pthread_mutex_lock(&replyq->count_mutex);
729 if (replyq->count == replyq->size) {
730 debug(DBG_WARN, "No room in queue, dropping request");
731 pthread_mutex_unlock(&replyq->count_mutex);
735 replyq->replies[replyq->count].buf = buf;
737 replyq->replies[replyq->count].tosa = *tosa;
740 if (replyq->count == 1) {
741 debug(DBG_DBG, "signalling client writer");
742 pthread_cond_signal(&replyq->count_cond);
744 pthread_mutex_unlock(&replyq->count_mutex);
747 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
748 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
749 static unsigned char first = 1;
750 static EVP_MD_CTX mdctx;
751 unsigned char hash[EVP_MAX_MD_SIZE], *input;
753 uint8_t i, offset = 0, out[128];
755 pthread_mutex_lock(&lock);
757 EVP_MD_CTX_init(&mdctx);
763 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
764 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
765 !EVP_DigestUpdate(&mdctx, input, 16) ||
766 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
768 pthread_mutex_unlock(&lock);
771 for (i = 0; i < 16; i++)
772 out[offset + i] = hash[i] ^ in[offset + i];
773 input = out + offset - 16;
778 memcpy(in, out, len);
779 pthread_mutex_unlock(&lock);
783 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
784 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
785 static unsigned char first = 1;
786 static EVP_MD_CTX mdctx;
787 unsigned char hash[EVP_MAX_MD_SIZE], *input;
789 uint8_t i, offset = 0, out[128];
791 pthread_mutex_lock(&lock);
793 EVP_MD_CTX_init(&mdctx);
799 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
800 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
801 !EVP_DigestUpdate(&mdctx, input, 16) ||
802 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
804 pthread_mutex_unlock(&lock);
807 for (i = 0; i < 16; i++)
808 out[offset + i] = hash[i] ^ in[offset + i];
814 memcpy(in, out, len);
815 pthread_mutex_unlock(&lock);
819 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
820 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
821 static unsigned char first = 1;
822 static EVP_MD_CTX mdctx;
823 unsigned char hash[EVP_MAX_MD_SIZE];
827 pthread_mutex_lock(&lock);
829 EVP_MD_CTX_init(&mdctx);
834 printf("msppencrypt auth in: ");
835 for (i = 0; i < 16; i++)
836 printf("%02x ", auth[i]);
839 printf("msppencrypt salt in: ");
840 for (i = 0; i < 2; i++)
841 printf("%02x ", salt[i]);
844 printf("msppencrypt in: ");
845 for (i = 0; i < len; i++)
846 printf("%02x ", text[i]);
850 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
851 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
852 !EVP_DigestUpdate(&mdctx, auth, 16) ||
853 !EVP_DigestUpdate(&mdctx, salt, 2) ||
854 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
855 pthread_mutex_unlock(&lock);
860 printf("msppencrypt hash: ");
861 for (i = 0; i < 16; i++)
862 printf("%02x ", hash[i]);
866 for (i = 0; i < 16; i++)
869 for (offset = 16; offset < len; offset += 16) {
871 printf("text + offset - 16 c(%d): ", offset / 16);
872 for (i = 0; i < 16; i++)
873 printf("%02x ", (text + offset - 16)[i]);
876 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
877 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
878 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
879 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
881 pthread_mutex_unlock(&lock);
885 printf("msppencrypt hash: ");
886 for (i = 0; i < 16; i++)
887 printf("%02x ", hash[i]);
891 for (i = 0; i < 16; i++)
892 text[offset + i] ^= hash[i];
896 printf("msppencrypt out: ");
897 for (i = 0; i < len; i++)
898 printf("%02x ", text[i]);
902 pthread_mutex_unlock(&lock);
906 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
907 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
908 static unsigned char first = 1;
909 static EVP_MD_CTX mdctx;
910 unsigned char hash[EVP_MAX_MD_SIZE];
915 pthread_mutex_lock(&lock);
917 EVP_MD_CTX_init(&mdctx);
922 printf("msppdecrypt auth in: ");
923 for (i = 0; i < 16; i++)
924 printf("%02x ", auth[i]);
927 printf("msppedecrypt salt in: ");
928 for (i = 0; i < 2; i++)
929 printf("%02x ", salt[i]);
932 printf("msppedecrypt in: ");
933 for (i = 0; i < len; i++)
934 printf("%02x ", text[i]);
938 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
939 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
940 !EVP_DigestUpdate(&mdctx, auth, 16) ||
941 !EVP_DigestUpdate(&mdctx, salt, 2) ||
942 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
943 pthread_mutex_unlock(&lock);
948 printf("msppedecrypt hash: ");
949 for (i = 0; i < 16; i++)
950 printf("%02x ", hash[i]);
954 for (i = 0; i < 16; i++)
955 plain[i] = text[i] ^ hash[i];
957 for (offset = 16; offset < len; offset += 16) {
959 printf("text + offset - 16 c(%d): ", offset / 16);
960 for (i = 0; i < 16; i++)
961 printf("%02x ", (text + offset - 16)[i]);
964 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
965 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
966 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
967 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
969 pthread_mutex_unlock(&lock);
973 printf("msppedecrypt hash: ");
974 for (i = 0; i < 16; i++)
975 printf("%02x ", hash[i]);
979 for (i = 0; i < 16; i++)
980 plain[offset + i] = text[offset + i] ^ hash[i];
983 memcpy(text, plain, len);
985 printf("msppedecrypt out: ");
986 for (i = 0; i < len; i++)
987 printf("%02x ", text[i]);
991 pthread_mutex_unlock(&lock);
995 struct server *id2server(char *id, uint8_t len) {
999 struct server *deflt = NULL;
1001 idrealm = strchr(id, '@');
1004 len -= idrealm - id;
1010 for (i = 0; i < realm_count; i++) {
1011 if (!deflt && realms[i].name[0] == '*' && realms[i].name[1] == '\0')
1012 deflt = realms[i].server;
1013 else if (!strncasecmp(idrealm, realms[i].name, len)) {
1014 debug(DBG_DBG, "found matching realm: %s, host %s", realms[i].name, realms[i].server->peer.host);
1015 return realms[i].server;
1021 for (i = 0; i < realm_count; i++)
1022 if (!regexec(&realms[i].regex, id, 0, NULL, 0)) {
1023 debug(DBG_DBG, "found matching realm: %s, host %s", realms[i].name, realms[i].server->peer.host);
1024 return realms[i].server;
1030 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1033 pthread_mutex_lock(&to->newrq_mutex);
1034 for (i = 0; i < MAX_REQUESTS; i++)
1035 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1037 pthread_mutex_unlock(&to->newrq_mutex);
1039 return i < MAX_REQUESTS;
1042 int attrvalidate(unsigned char *attrs, int length) {
1043 while (length > 1) {
1044 if (attrs[RAD_Attr_Length] < 2) {
1045 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", attrs[RAD_Attr_Length]);
1048 length -= attrs[RAD_Attr_Length];
1050 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", attrs[RAD_Attr_Length]);
1053 attrs += attrs[RAD_Attr_Length];
1056 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1060 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1064 if (len < 16 || len > 128 || len % 16) {
1065 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1069 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1070 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1074 printf("pwdrecrypt: password: ");
1075 for (i = 0; i < len; i++)
1076 printf("%02x ", pwd[i]);
1079 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1080 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1086 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1089 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1090 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1093 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1094 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1100 struct server *radsrv(struct request *rq, unsigned char *buf, struct client *from) {
1101 uint8_t code, id, *auth, *attrs, attrvallen, *attrval;
1105 unsigned char newauth[16];
1107 code = *(uint8_t *)buf;
1108 id = *(uint8_t *)(buf + 1);
1110 auth = (uint8_t *)(buf + 4);
1112 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1114 if (code != RAD_Access_Request) {
1115 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, ignoring");
1122 if (!attrvalidate(attrs, len)) {
1123 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1127 attrval = attrget(attrs, len, RAD_Attr_User_Name, &attrvallen);
1129 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1132 memcpy(username, attrval, attrvallen);
1133 username[attrvallen] = '\0';
1134 debug(DBG_DBG, "Access Request with username: %s", username);
1136 to = id2server(username, attrvallen);
1138 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1142 if (rqinqueue(to, from, id)) {
1143 debug(DBG_INFO, "radsrv: ignoring request from host %s with id %d, already got one", from->peer.host, id);
1147 attrval = attrget(attrs, len, RAD_Attr_Message_Authenticator, &attrvallen);
1148 if (attrval && (attrvallen != 16 || !checkmessageauth(buf, attrval, from->peer.secret))) {
1149 debug(DBG_WARN, "radsrv: message authentication failed");
1153 if (!RAND_bytes(newauth, 16)) {
1154 debug(DBG_WARN, "radsrv: failed to generate random auth");
1159 printauth("auth", auth);
1160 printauth("newauth", newauth);
1163 attrval = attrget(attrs, len, RAD_Attr_User_Password, &attrvallen);
1165 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attrvallen);
1166 if (!pwdrecrypt(attrval, attrvallen, from->peer.secret, to->peer.secret, auth, newauth))
1170 attrval = attrget(attrs, len, RAD_Attr_Tunnel_Password, &attrvallen);
1172 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attrvallen);
1173 if (!pwdrecrypt(attrval, attrvallen, from->peer.secret, to->peer.secret, auth, newauth))
1180 memcpy(rq->origauth, auth, 16);
1181 memcpy(auth, newauth, 16);
1183 printauth("rq->origauth", (unsigned char *)rq->origauth);
1184 printauth("auth", auth);
1189 void *clientrd(void *arg) {
1190 struct server *server = (struct server *)arg;
1191 struct client *from;
1193 unsigned char *buf, *messageauth, *subattrs, *attrs, *attrval;
1195 struct sockaddr_storage fromsa;
1196 struct timeval lastconnecttry;
1200 lastconnecttry = server->lastconnecttry;
1201 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1202 if (!buf && server->peer.type == 'T') {
1203 tlsconnect(server, &lastconnecttry, "clientrd");
1207 server->connectionok = 1;
1209 i = buf[1]; /* i is the id */
1212 case RAD_Access_Accept:
1213 debug(DBG_DBG, "got Access Accept with id %d", i);
1215 case RAD_Access_Reject:
1216 debug(DBG_DBG, "got Access Reject with id %d", i);
1218 case RAD_Access_Challenge:
1219 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);
1229 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1233 if (server->requests[i].received) {
1234 pthread_mutex_unlock(&server->newrq_mutex);
1235 debug(DBG_INFO, "clientrd: already received, ignoring");
1239 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1240 pthread_mutex_unlock(&server->newrq_mutex);
1241 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1245 from = server->requests[i].from;
1246 len = RADLEN(buf) - 20;
1249 if (!attrvalidate(attrs, len)) {
1250 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1254 /* Message Authenticator */
1255 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator, &attrvallen);
1257 if (attrvallen != 16) {
1258 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1261 memcpy(tmp, buf + 4, 16);
1262 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1263 if (!checkmessageauth(buf, messageauth, server->peer.secret)) {
1264 debug(DBG_WARN, "clientrd: message authentication failed");
1267 memcpy(buf + 4, tmp, 16);
1268 debug(DBG_DBG, "clientrd: message auth ok");
1272 attrval = attrget(attrs, len, RAD_Attr_Vendor_Specific, &attrvallen);
1273 if (attrval && attrvallen > 4 && ((uint16_t *)attrval)[0] == 0 && ntohs(((uint16_t *)attrval)[1]) == 311) { /* 311 == MS */
1274 sublen = attrvallen - 4;
1275 subattrs = attrval + 4;
1276 if (!attrvalidate(subattrs, sublen)) {
1277 debug(DBG_WARN, "clientrd: MS attribute validation failed, ignoring packet");
1281 attrval = attrget(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, &attrvallen);
1283 debug(DBG_DBG, "clientrd: Got MS MPPE Send Key");
1284 if (!msmpprecrypt(attrval, attrvallen, server->peer.secret, from->peer.secret,
1285 server->requests[i].buf + 4, server->requests[i].origauth))
1289 attrval = attrget(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, &attrvallen);
1291 debug(DBG_DBG, "clientrd: Got MS MPPE Recv Key");
1292 if (!msmpprecrypt(attrval, attrvallen, server->peer.secret, from->peer.secret,
1293 server->requests[i].buf + 4, server->requests[i].origauth))
1298 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1299 attrval = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name, &attrvallen);
1300 /* we know the attribute exists */
1301 memcpy(tmp, attrval, attrvallen);
1302 tmp[attrvallen] = '\0';
1304 case RAD_Access_Accept:
1305 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->peer.host);
1307 case RAD_Access_Reject:
1308 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->peer.host);
1313 /* once we set received = 1, requests[i] may be reused */
1314 buf[1] = (char)server->requests[i].origid;
1315 memcpy(buf + 4, server->requests[i].origauth, 16);
1317 printauth("origauth/buf+4", buf + 4);
1321 if (!createmessageauth(buf, messageauth, from->peer.secret))
1323 debug(DBG_DBG, "clientrd: computed messageauthattr");
1326 if (from->peer.type == 'U')
1327 fromsa = server->requests[i].fromsa;
1328 server->requests[i].received = 1;
1329 pthread_mutex_unlock(&server->newrq_mutex);
1331 if (!radsign(buf, (unsigned char *)from->peer.secret)) {
1332 debug(DBG_WARN, "clientrd: failed to sign message");
1336 printauth("signedorigauth/buf+4", buf + 4);
1338 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1339 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1343 void *clientwr(void *arg) {
1344 struct server *server = (struct server *)arg;
1346 pthread_t clientrdth;
1349 struct timeval now, lastsend;
1350 struct timespec timeout;
1352 memset(&lastsend, 0, sizeof(struct timeval));
1353 memset(&timeout, 0, sizeof(struct timespec));
1355 if (server->peer.type == 'U') {
1356 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1357 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1359 tlsconnect(server, NULL, "new client");
1361 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1362 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1365 pthread_mutex_lock(&server->newrq_mutex);
1366 if (!server->newrq) {
1367 gettimeofday(&now, NULL);
1368 if (timeout.tv_sec) {
1369 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1370 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1372 } else if (options.statusserver) {
1373 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD;
1374 /* add random 0-7 seconds to timeout */
1375 RAND_bytes(&rnd, 1);
1376 timeout.tv_sec += rnd / 32;
1377 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1380 debug(DBG_DBG, "clientwr: waiting for new request");
1381 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1384 if (server->newrq) {
1385 debug(DBG_DBG, "clientwr: got new request");
1388 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1389 pthread_mutex_unlock(&server->newrq_mutex);
1391 for (i = 0; i < MAX_REQUESTS; i++) {
1392 pthread_mutex_lock(&server->newrq_mutex);
1393 while (!server->requests[i].buf && i < MAX_REQUESTS)
1395 if (i == MAX_REQUESTS) {
1396 pthread_mutex_unlock(&server->newrq_mutex);
1399 rq = server->requests + i;
1402 debug(DBG_DBG, "clientwr: removing received packet from queue");
1404 /* setting this to NULL means that it can be reused */
1406 pthread_mutex_unlock(&server->newrq_mutex);
1410 gettimeofday(&now, NULL);
1411 if (now.tv_sec <= rq->expiry.tv_sec) {
1412 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1413 timeout.tv_sec = rq->expiry.tv_sec;
1414 pthread_mutex_unlock(&server->newrq_mutex);
1418 if (rq->tries == (server->peer.type == 'T' ? 1 : REQUEST_RETRIES)) {
1419 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1421 /* setting this to NULL means that it can be reused */
1423 pthread_mutex_unlock(&server->newrq_mutex);
1426 pthread_mutex_unlock(&server->newrq_mutex);
1428 rq->expiry.tv_sec = now.tv_sec +
1429 (server->peer.type == 'T' ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1430 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1431 timeout.tv_sec = rq->expiry.tv_sec;
1433 clientradput(server, server->requests[i].buf);
1434 gettimeofday(&lastsend, NULL);
1437 if (options.statusserver) {
1438 gettimeofday(&now, NULL);
1439 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1440 lastsend.tv_sec = now.tv_sec;
1441 debug(DBG_DBG, "clientwr: should send status to %s here", server->peer.host);
1447 void *udpserverwr(void *arg) {
1448 struct replyq *replyq = &udp_server_replyq;
1449 struct reply *reply = replyq->replies;
1451 pthread_mutex_lock(&replyq->count_mutex);
1453 while (!replyq->count) {
1454 debug(DBG_DBG, "udp server writer, waiting for signal");
1455 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1456 debug(DBG_DBG, "udp server writer, got signal");
1458 pthread_mutex_unlock(&replyq->count_mutex);
1460 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1461 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1462 debug(DBG_WARN, "sendudp: send failed");
1465 pthread_mutex_lock(&replyq->count_mutex);
1467 memmove(replyq->replies, replyq->replies + 1,
1468 replyq->count * sizeof(struct reply));
1472 void *udpserverrd(void *arg) {
1477 pthread_t udpserverwrth;
1479 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1480 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1482 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1483 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1485 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1486 debugx(1, DBG_ERR, "pthread_create failed");
1490 memset(&rq, 0, sizeof(struct request));
1491 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1492 to = radsrv(&rq, buf, fr);
1494 debug(DBG_INFO, "udpserverrd: ignoring request, no place to send it");
1497 sendrq(to, fr, &rq);
1501 void *tlsserverwr(void *arg) {
1503 unsigned long error;
1504 struct client *client = (struct client *)arg;
1505 struct replyq *replyq;
1507 debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1508 replyq = client->replyq;
1509 pthread_mutex_lock(&replyq->count_mutex);
1511 while (!replyq->count) {
1512 if (client->peer.ssl) {
1513 debug(DBG_DBG, "tls server writer, waiting for signal");
1514 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1515 debug(DBG_DBG, "tls server writer, got signal");
1517 if (!client->peer.ssl) {
1518 /* ssl might have changed while waiting */
1519 pthread_mutex_unlock(&replyq->count_mutex);
1520 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1524 pthread_mutex_unlock(&replyq->count_mutex);
1525 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1527 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1528 cnt, RADLEN(replyq->replies->buf));
1530 while ((error = ERR_get_error()))
1531 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1532 free(replyq->replies->buf);
1534 pthread_mutex_lock(&replyq->count_mutex);
1536 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1540 void *tlsserverrd(void *arg) {
1543 unsigned long error;
1546 struct client *client = (struct client *)arg;
1547 pthread_t tlsserverwrth;
1550 debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1551 ssl = client->peer.ssl;
1553 if (SSL_accept(ssl) <= 0) {
1554 while ((error = ERR_get_error()))
1555 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1556 debug(DBG_ERR, "SSL_accept failed");
1559 if (tlsverifycert(&client->peer)) {
1560 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1561 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1565 buf = radtlsget(client->peer.ssl);
1568 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1569 memset(&rq, 0, sizeof(struct request));
1570 to = radsrv(&rq, buf, client);
1572 debug(DBG_INFO, "tlsserverrd: ignoring request, no place to send it");
1575 sendrq(to, client, &rq);
1577 debug(DBG_ERR, "tlsserverrd: connection lost");
1578 /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1579 client->peer.ssl = NULL;
1580 pthread_mutex_lock(&client->replyq->count_mutex);
1581 pthread_cond_signal(&client->replyq->count_cond);
1582 pthread_mutex_unlock(&client->replyq->count_mutex);
1583 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1584 pthread_join(tlsserverwrth, NULL);
1588 s = SSL_get_fd(ssl);
1590 shutdown(s, SHUT_RDWR);
1592 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1593 client->peer.ssl = NULL;
1598 pthread_t tlsserverth;
1600 struct sockaddr_storage from;
1601 size_t fromlen = sizeof(from);
1602 struct client *client;
1604 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1605 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1608 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1609 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1612 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1614 debug(DBG_WARN, "accept failed");
1617 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1619 client = find_client('T', (struct sockaddr *)&from, NULL);
1621 debug(DBG_WARN, "ignoring request, not a known TLS client");
1622 shutdown(snew, SHUT_RDWR);
1627 if (client->peer.ssl) {
1628 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1629 shutdown(snew, SHUT_RDWR);
1633 client->peer.ssl = SSL_new(ssl_ctx);
1634 SSL_set_fd(client->peer.ssl, snew);
1635 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1636 debug(DBG_ERR, "tlslistener: pthread_create failed");
1637 SSL_free(client->peer.ssl);
1638 shutdown(snew, SHUT_RDWR);
1640 client->peer.ssl = NULL;
1643 pthread_detach(tlsserverth);
1648 void addrealm(char *value, char *server) {
1650 struct realm *realm;
1652 for (i = 0; i < server_count; i++)
1653 if (!strcasecmp(server, servers[i].peer.host))
1655 if (i == server_count)
1656 debugx(1, DBG_ERR, "addrealm failed, no server %s", server);
1659 realms = realloc(realms, realm_count * sizeof(struct realm));
1661 debugx(1, DBG_ERR, "malloc failed");
1662 realm = realms + realm_count - 1;
1663 memset(realm, 0, sizeof(struct realm));
1664 realm->name = stringcopy(value, 0);
1665 realm->server = servers + i;
1666 if (regcomp(&realm->regex, value, REG_ICASE | REG_NOSUB))
1667 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", value);
1668 debug(DBG_DBG, "addrealm: added realm %s for server %s", value, server);
1671 char *parsehostport(char *s, struct peer *peer) {
1676 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1680 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1682 debugx(1, DBG_ERR, "no ] matching initial [");
1686 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1689 debugx(1, DBG_ERR, "missing host/address");
1691 peer->host = stringcopy(field, p - field);
1694 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1695 debugx(1, DBG_ERR, "unexpected character after ]");
1698 /* port number or service name is specified */;
1700 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1702 debugx(1, DBG_ERR, "syntax error, : but no following port");
1703 peer->port = stringcopy(field, p - field);
1705 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1709 /* TODO remove this */
1710 /* * is default, else longest match ... ";" used for separator */
1711 char *parserealmlist(char *s, struct server *server) {
1718 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1723 debugx(1, DBG_ERR, "realm list must be specified");
1725 realmdata = stringcopy(s, l);
1726 realms = malloc((1+n) * sizeof(char *));
1728 debugx(1, DBG_ERR, "malloc failed");
1729 realms[0] = realmdata;
1730 for (n = 1, i = 0; i < l; i++)
1731 if (realmdata[i] == ';') {
1732 realmdata[i] = '\0';
1733 realms[n++] = realmdata + i + 1;
1735 for (i = 0; i < n; i++)
1736 addrealm(realms[i], server->peer.host);
1744 for (start = s;; s++)
1745 if (!*s || *s == ';' || *s == ' ' || *s == '\t' || *s == '\n') {
1746 if (s - start > 0) {
1747 realm = stringcopy(start, s - start);
1748 addrealm(realm, server->peer.host);
1758 FILE *openconfigfile(const char *filename) {
1760 char pathname[100], *base;
1762 f = fopen(filename, "r");
1764 debug(DBG_DBG, "reading config file %s", filename);
1768 if (strlen(filename) + 1 <= sizeof(pathname)) {
1769 /* basename() might modify the string */
1770 strcpy(pathname, filename);
1771 base = basename(pathname);
1772 f = fopen(base, "r");
1776 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1778 debug(DBG_DBG, "reading config file %s", base);
1782 /* exactly one argument must be non-NULL */
1783 void getconfig(const char *serverfile, const char *clientfile) {
1787 struct client *client;
1788 struct server *server;
1790 int i, count, *ucount, *tcount;
1792 f = openconfigfile(serverfile ? serverfile : clientfile);
1794 ucount = &server_udp_count;
1795 tcount = &server_tls_count;
1797 ucount = &client_udp_count;
1798 tcount = &client_tls_count;
1800 while (fgets(line, 1024, f)) {
1801 for (p = line; *p == ' ' || *p == '\t'; p++);
1813 debugx(1, DBG_ERR, "type must be U or T, got %c", *p);
1818 count = server_count = server_udp_count + server_tls_count;
1819 servers = calloc(count, sizeof(struct server));
1821 debugx(1, DBG_ERR, "malloc failed");
1823 if (client_udp_count) {
1824 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
1825 if (!udp_server_replyq.replies)
1826 debugx(1, DBG_ERR, "malloc failed");
1827 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
1828 udp_server_replyq.count = 0;
1829 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1830 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1833 count = client_count = client_udp_count + client_tls_count;
1834 clients = calloc(count, sizeof(struct client));
1836 debugx(1, DBG_ERR, "malloc failed");
1840 for (i = 0; i < count && fgets(line, 1024, f);) {
1842 server = &servers[i];
1843 peer = &server->peer;
1845 client = &clients[i];
1846 peer = &client->peer;
1848 for (p = line; *p == ' ' || *p == '\t'; p++);
1849 if (*p == '#' || *p == '\n')
1851 peer->type = *p; /* we already know it must be U or T */
1852 for (p++; *p == ' ' || *p == '\t'; p++);
1853 p = parsehostport(p, peer);
1854 for (; *p == ' ' || *p == '\t'; p++);
1856 p = parserealmlist(p, server);
1857 for (; *p == ' ' || *p == '\t'; p++);
1860 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1862 /* no secret set and end of line, line is complete if TLS */
1863 if (peer->type == 'U')
1864 debugx(1, DBG_ERR, "secret must be specified for UDP");
1865 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1867 peer->secret = stringcopy(field, p - field);
1868 /* check that rest of line only white space */
1869 for (; *p == ' ' || *p == '\t'; p++);
1870 if (*p && *p != '\n')
1871 debugx(1, DBG_ERR, "max 4 fields per line, found a 5th");
1874 if ((serverfile && !resolvepeer(&server->peer, 0)) ||
1875 (clientfile && !resolvepeer(&client->peer, 0)))
1876 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
1879 pthread_mutex_init(&server->lock, NULL);
1881 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1882 if (!server->requests)
1883 debugx(1, DBG_ERR, "malloc failed");
1885 pthread_mutex_init(&server->newrq_mutex, NULL);
1886 pthread_cond_init(&server->newrq_cond, NULL);
1888 if (peer->type == 'U')
1889 client->replyq = &udp_server_replyq;
1891 client->replyq = malloc(sizeof(struct replyq));
1892 if (!client->replyq)
1893 debugx(1, DBG_ERR, "malloc failed");
1894 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1895 if (!client->replyq->replies)
1896 debugx(1, DBG_ERR, "malloc failed");
1897 client->replyq->size = MAX_REQUESTS;
1898 client->replyq->count = 0;
1899 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1900 pthread_cond_init(&client->replyq->count_cond, NULL);
1903 debug(DBG_DBG, "got type %c, host %s, port %s, secret %s", peer->type, peer->host, peer->port, peer->secret);
1909 struct peer *server_create(char type) {
1910 struct peer *server;
1913 server = malloc(sizeof(struct peer));
1915 debugx(1, DBG_ERR, "malloc failed");
1916 memset(server, 0, sizeof(struct peer));
1917 server->type = type;
1918 conf = (type == 'T' ? options.listentcp : options.listenudp);
1920 parsehostport(conf, server);
1921 if (!strcmp(server->host, "*")) {
1923 server->host = NULL;
1926 server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1927 if (!resolvepeer(server, AI_PASSIVE))
1928 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1932 /* Parses config with following syntax:
1935 * option-name = value
1937 * option-name value {
1938 * option-name [=] value
1942 void getgeneralconfig(FILE *f, char *block, ...) {
1945 char *tokens[3], *opt, *val, *word, **str;
1946 int type, tcount, conftype;
1947 void (*cbk)(FILE *, char *, char *);
1949 while (fgets(line, 1024, f)) {
1950 tokens[0] = strtok(line, " \t\n");
1951 if (!*tokens || **tokens == '#')
1953 for (tcount = 1; tcount < 3 && (tokens[tcount] = strtok(NULL, " \t\n")); tcount++);
1955 if (tcount && **tokens == '}') {
1958 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
1965 conftype = CONF_STR;
1968 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
1971 conftype = CONF_STR;
1974 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
1977 conftype = CONF_CBK;
1983 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
1984 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
1987 va_start(ap, block);
1988 while ((word = va_arg(ap, char *))) {
1989 type = va_arg(ap, int);
1992 str = va_arg(ap, char **);
1994 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
1997 cbk = va_arg(ap, void (*)(FILE *, char *, char *));
2000 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2002 if (!strcasecmp(opt, word))
2009 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2010 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2013 if (type != conftype) {
2015 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2016 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2022 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2024 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2025 *str = stringcopy(val, 0);
2031 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2036 void confclsrv_cb(FILE *f, char *opt, char *val) {
2037 char *type = NULL, *secret = NULL, *port = NULL;
2039 struct client *client = NULL;
2040 struct server *server = NULL;
2043 block = malloc(strlen(opt) + strlen(val) + 2);
2045 debugx(1, DBG_ERR, "malloc failed");
2046 sprintf(block, "%s %s", opt, val);
2047 debug(DBG_DBG, "confclsrv_cb called for %s", block);
2049 if (!strcasecmp(opt, "client")) {
2050 getgeneralconfig(f, block,
2051 "type", CONF_STR, &type,
2052 "secret", CONF_STR, &secret,
2056 clients = realloc(clients, client_count * sizeof(struct client));
2058 debugx(1, DBG_ERR, "malloc failed");
2059 client = clients + client_count - 1;
2060 memset(client, 0, sizeof(struct client));
2061 peer = &client->peer;
2063 getgeneralconfig(f, block,
2064 "type", CONF_STR, &type,
2065 "secret", CONF_STR, &secret,
2066 "port", CONF_STR, &port,
2070 servers = realloc(servers, server_count * sizeof(struct server));
2072 debugx(1, DBG_ERR, "malloc failed");
2073 server = servers + server_count - 1;
2074 memset(server, 0, sizeof(struct server));
2075 peer = &server->peer;
2079 peer->host = stringcopy(val, 0);
2081 if (type && !strcasecmp(type, "udp")) {
2088 peer->port = stringcopy(DEFAULT_UDP_PORT, 0);
2090 } else if (type && !strcasecmp(type, "tls")) {
2097 peer->port = stringcopy(DEFAULT_TLS_PORT, 0);
2100 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2103 if (!resolvepeer(peer, 0))
2104 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
2107 if (peer->type == 'U')
2108 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2109 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2111 peer->secret = secret;
2115 if (peer->type == 'U')
2116 client->replyq = &udp_server_replyq;
2118 client->replyq = malloc(sizeof(struct replyq));
2119 if (!client->replyq)
2120 debugx(1, DBG_ERR, "malloc failed");
2121 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
2122 if (!client->replyq->replies)
2123 debugx(1, DBG_ERR, "malloc failed");
2124 client->replyq->size = MAX_REQUESTS;
2125 client->replyq->count = 0;
2126 pthread_mutex_init(&client->replyq->count_mutex, NULL);
2127 pthread_cond_init(&client->replyq->count_cond, NULL);
2130 pthread_mutex_init(&server->lock, NULL);
2132 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
2133 if (!server->requests)
2134 debugx(1, DBG_ERR, "malloc failed");
2136 pthread_mutex_init(&server->newrq_mutex, NULL);
2137 pthread_cond_init(&server->newrq_cond, NULL);
2143 void confrealm_cb(FILE *f, char *opt, char *val) {
2144 char *server = NULL;
2147 block = malloc(strlen(opt) + strlen(val) + 2);
2149 debugx(1, DBG_ERR, "malloc failed");
2150 sprintf(block, "%s %s", opt, val);
2151 debug(DBG_DBG, "confrealm_cb called for %s", block);
2153 getgeneralconfig(f, block,
2154 "server", CONF_STR, &server,
2158 debugx(1, DBG_ERR, "error in block %s, server must be specified", block);
2160 addrealm(val, server);
2165 void getmainconfig(const char *configfile) {
2167 char *statusserver = NULL, *loglevel = NULL;
2169 f = openconfigfile(configfile);
2170 memset(&options, 0, sizeof(options));
2172 getgeneralconfig(f, NULL,
2173 "TLSCACertificateFile", CONF_STR, &options.tlscacertificatefile,
2174 "TLSCACertificatePath", CONF_STR, &options.tlscacertificatepath,
2175 "TLSCertificateFile", CONF_STR, &options.tlscertificatefile,
2176 "TLSCertificateKeyFile", CONF_STR, &options.tlscertificatekeyfile,
2177 "TLSCertificateKeyPassword", CONF_STR, &options.tlscertificatekeypassword,
2178 "ListenUDP", CONF_STR, &options.listenudp,
2179 "ListenTCP", CONF_STR, &options.listentcp,
2180 "StatusServer", CONF_STR, &statusserver,
2181 "LogLevel", CONF_STR, &loglevel,
2182 "LogDestination", CONF_STR, &options.logdestination,
2183 "Client", CONF_CBK, confclsrv_cb,
2184 "Server", CONF_CBK, confclsrv_cb,
2185 "Realm", CONF_CBK, confrealm_cb,
2191 if (!strcasecmp(statusserver, "on"))
2192 options.statusserver = 1;
2193 else if (strcasecmp(statusserver, "off"))
2194 debugx(1, DBG_ERR, "error in %s, value of option StatusServer is %s, must be on or off", configfile, statusserver);
2198 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2199 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2200 options.loglevel = *loglevel - '0';
2204 if (client_udp_count) {
2205 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
2206 if (!udp_server_replyq.replies)
2207 debugx(1, DBG_ERR, "malloc failed");
2208 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
2209 udp_server_replyq.count = 0;
2210 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
2211 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
2215 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2218 while ((c = getopt(argc, argv, "c:d:f")) != -1) {
2221 *configfile = optarg;
2224 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2225 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2226 *loglevel = *optarg - '0';
2235 if (!(argc - optind))
2239 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ]", argv[0]);
2243 int main(int argc, char **argv) {
2244 pthread_t udpserverth;
2246 uint8_t foreground = 0, loglevel = 0;
2247 char *configfile = NULL;
2249 debug_init("radsecproxy");
2250 debug_set_level(DEBUG_LEVEL);
2251 getargs(argc, argv, &foreground, &loglevel, &configfile);
2253 debug_set_level(loglevel);
2254 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2256 options.loglevel = loglevel;
2257 else if (options.loglevel)
2258 debug_set_level(options.loglevel);
2260 options.logdestination = NULL;
2262 if (!options.logdestination)
2263 options.logdestination = "x-syslog://";
2264 debug_set_destination(options.logdestination);
2267 /* TODO remove getconfig completely when all use new config method */
2269 getconfig(CONFIG_SERVERS, NULL);
2271 getconfig(NULL, CONFIG_CLIENTS);
2273 /* TODO exit if not at least one client and one server configured */
2275 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2277 if (!foreground && (daemon(0, 0) < 0))
2278 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2280 if (client_udp_count) {
2281 udp_server_listen = server_create('U');
2282 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2283 debugx(1, DBG_ERR, "pthread_create failed");
2286 if (client_tls_count || server_tls_count)
2287 ssl_ctx = ssl_init();
2289 for (i = 0; i < server_count; i++)
2290 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2291 debugx(1, DBG_ERR, "pthread_create failed");
2293 if (client_tls_count) {
2294 tcp_server_listen = server_create('T');
2295 return tlslistener();
2298 /* just hang around doing nothing, anything to do here? */