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>
46 #include <openssl/ssl.h>
47 #include <openssl/rand.h>
48 #include <openssl/err.h>
49 #include <openssl/md5.h>
50 #include <openssl/hmac.h>
52 #include "radsecproxy.h"
54 static struct options options;
55 static struct client *clients;
56 static struct server *servers;
58 static int client_udp_count = 0;
59 static int client_tls_count = 0;
60 static int client_count = 0;
61 static int server_udp_count = 0;
62 static int server_tls_count = 0;
63 static int server_count = 0;
65 static struct peer *tcp_server_listen;
66 static struct peer *udp_server_listen;
67 static struct replyq udp_server_replyq;
68 static int udp_server_sock = -1;
69 static pthread_mutex_t *ssl_locks;
70 static long *ssl_lock_count;
71 static SSL_CTX *ssl_ctx = NULL;
75 /* callbacks for making OpenSSL thread safe */
76 unsigned long ssl_thread_id() {
77 return (unsigned long)pthread_self();
80 void ssl_locking_callback(int mode, int type, const char *file, int line) {
81 if (mode & CRYPTO_LOCK) {
82 pthread_mutex_lock(&ssl_locks[type]);
83 ssl_lock_count[type]++;
85 pthread_mutex_unlock(&ssl_locks[type]);
88 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
89 int pwdlen = strlen(userdata);
90 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
92 memcpy(buf, userdata, pwdlen);
96 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
101 err_cert = X509_STORE_CTX_get_current_cert(ctx);
102 err = X509_STORE_CTX_get_error(ctx);
103 depth = X509_STORE_CTX_get_error_depth(ctx);
105 if (depth > MAX_CERT_DEPTH) {
107 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
108 X509_STORE_CTX_set_error(ctx, err);
112 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
113 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
116 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
117 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
118 debug(DBG_WARN, "\tIssuer=%s", buf);
120 case X509_V_ERR_CERT_NOT_YET_VALID:
121 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
122 debug(DBG_WARN, "\tCertificate not yet valid");
124 case X509_V_ERR_CERT_HAS_EXPIRED:
125 debug(DBG_WARN, "Certificate has expired");
127 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
128 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
133 printf("certificate verify returns %d\n", ok);
138 SSL_CTX *ssl_init() {
143 if (!options.tlscertificatefile || !options.tlscertificatekeyfile)
144 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS");
146 if (!options.tlscacertificatefile && !options.tlscacertificatepath)
147 debugx(1, DBG_ERR, "CA Certificate file/path need to be configured");
149 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
150 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
151 for (i = 0; i < CRYPTO_num_locks(); i++) {
152 ssl_lock_count[i] = 0;
153 pthread_mutex_init(&ssl_locks[i], NULL);
155 CRYPTO_set_id_callback(ssl_thread_id);
156 CRYPTO_set_locking_callback(ssl_locking_callback);
158 SSL_load_error_strings();
161 while (!RAND_status()) {
162 time_t t = time(NULL);
163 pid_t pid = getpid();
164 RAND_seed((unsigned char *)&t, sizeof(time_t));
165 RAND_seed((unsigned char *)&pid, sizeof(pid));
168 ctx = SSL_CTX_new(TLSv1_method());
169 if (options.tlscertificatekeypassword) {
170 SSL_CTX_set_default_passwd_cb_userdata(ctx, options.tlscertificatekeypassword);
171 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
173 if (SSL_CTX_use_certificate_chain_file(ctx, options.tlscertificatefile) &&
174 SSL_CTX_use_PrivateKey_file(ctx, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) &&
175 SSL_CTX_check_private_key(ctx) &&
176 SSL_CTX_load_verify_locations(ctx, options.tlscacertificatefile, options.tlscacertificatepath)) {
177 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
178 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
182 while ((error = ERR_get_error()))
183 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
184 debug(DBG_ERR, "Error initialising SSL/TLS");
189 void printauth(char *s, unsigned char *t) {
192 for (i = 0; i < 16; i++)
193 printf("%02x ", t[i]);
198 int resolvepeer(struct peer *peer, int ai_flags) {
199 struct addrinfo hints, *addrinfo;
201 memset(&hints, 0, sizeof(hints));
202 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
203 hints.ai_family = AF_UNSPEC;
204 hints.ai_flags = ai_flags;
205 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
206 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", peer->host, peer->port);
211 freeaddrinfo(peer->addrinfo);
212 peer->addrinfo = addrinfo;
216 int connecttoserver(struct addrinfo *addrinfo) {
218 struct addrinfo *res;
220 for (res = addrinfo; res; res = res->ai_next) {
221 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
223 debug(DBG_WARN, "connecttoserver: socket failed");
226 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
228 debug(DBG_WARN, "connecttoserver: connect failed");
235 int bindtoaddr(struct addrinfo *addrinfo) {
237 struct addrinfo *res;
239 for (res = addrinfo; res; res = res->ai_next) {
240 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
242 debug(DBG_WARN, "bindtoaddr: socket failed");
245 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
246 if (!bind(s, res->ai_addr, res->ai_addrlen))
248 debug(DBG_WARN, "bindtoaddr: bind failed");
254 /* returns the client with matching address, or NULL */
255 /* if client argument is not NULL, we only check that one client */
256 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
257 struct sockaddr_in6 *sa6;
258 struct in_addr *a4 = NULL;
261 struct addrinfo *res;
263 if (addr->sa_family == AF_INET6) {
264 sa6 = (struct sockaddr_in6 *)addr;
265 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
266 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
268 a4 = &((struct sockaddr_in *)addr)->sin_addr;
270 c = (client ? client : clients);
271 for (i = 0; i < client_count; i++) {
272 if (c->peer.type == type)
273 for (res = c->peer.addrinfo; res; res = res->ai_next)
274 if ((a4 && res->ai_family == AF_INET &&
275 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
276 (res->ai_family == AF_INET6 &&
277 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
286 /* returns the server with matching address, or NULL */
287 /* if server argument is not NULL, we only check that one server */
288 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
289 struct sockaddr_in6 *sa6;
290 struct in_addr *a4 = NULL;
293 struct addrinfo *res;
295 if (addr->sa_family == AF_INET6) {
296 sa6 = (struct sockaddr_in6 *)addr;
297 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
298 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
300 a4 = &((struct sockaddr_in *)addr)->sin_addr;
302 s = (server ? server : servers);
303 for (i = 0; i < server_count; i++) {
304 if (s->peer.type == type)
305 for (res = s->peer.addrinfo; res; res = res->ai_next)
306 if ((a4 && res->ai_family == AF_INET &&
307 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
308 (res->ai_family == AF_INET6 &&
309 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
318 /* exactly one of client and server must be non-NULL */
319 /* if *peer == NULL we return who we received from, else require it to be from peer */
320 /* return from in sa if not NULL */
321 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
324 unsigned char buf[65536], *rad;
325 struct sockaddr_storage from;
326 socklen_t fromlen = sizeof(from);
329 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
331 debug(DBG_WARN, "radudpget: recv failed");
334 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
337 debug(DBG_WARN, "radudpget: packet too small");
343 debug(DBG_WARN, "radudpget: length too small");
348 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
352 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
355 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
356 : (void *)find_server('U', (struct sockaddr *)&from, *server));
358 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
365 debug(DBG_ERR, "radudpget: malloc failed");
367 memcpy(rad, buf, len);
369 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
371 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
377 int tlsverifycert(struct peer *peer) {
385 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
386 debug(DBG_ERR, "tlsverifycert: basic validation failed");
387 while ((error = ERR_get_error()))
388 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
392 cert = SSL_get_peer_certificate(peer->ssl);
394 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
397 nm = X509_get_subject_name(cert);
400 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
403 e = X509_NAME_get_entry(nm, loc);
404 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
411 for (i = 0; i < l; i++)
416 if (l == strlen(peer->host) && !strncasecmp(peer->host, (char *)v, l)) {
417 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s, All OK", peer->host);
420 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", peer->host);
426 void tlsconnect(struct server *server, struct timeval *when, char *text) {
430 debug(DBG_DBG, "tlsconnect called from %s", text);
431 pthread_mutex_lock(&server->lock);
432 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
433 /* already reconnected, nothing to do */
434 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
435 pthread_mutex_unlock(&server->lock);
439 debug(DBG_DBG, "tlsconnect %s", text);
442 gettimeofday(&now, NULL);
443 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
444 if (server->connectionok) {
445 server->connectionok = 0;
447 } else if (elapsed < 5)
449 else if (elapsed < 600) {
450 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
452 } else if (elapsed < 1000) {
453 debug(DBG_INFO, "tlsconnect: sleeping %ds", 900);
456 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
457 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->peer.host, server->peer.port);
458 if (server->sock >= 0)
460 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
461 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
465 SSL_free(server->peer.ssl);
466 server->peer.ssl = SSL_new(ssl_ctx);
467 SSL_set_fd(server->peer.ssl, server->sock);
468 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
471 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->peer.host, server->peer.port);
472 gettimeofday(&server->lastconnecttry, NULL);
473 pthread_mutex_unlock(&server->lock);
476 unsigned char *radtlsget(SSL *ssl) {
478 unsigned char buf[4], *rad;
481 for (total = 0; total < 4; total += cnt) {
482 cnt = SSL_read(ssl, buf + total, 4 - total);
484 debug(DBG_ERR, "radtlsget: connection lost");
485 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
486 /* remote end sent close_notify, send one back */
496 debug(DBG_ERR, "radtlsget: malloc failed");
501 for (; total < len; total += cnt) {
502 cnt = SSL_read(ssl, rad + total, len - total);
504 debug(DBG_ERR, "radtlsget: connection lost");
505 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
506 /* remote end sent close_notify, send one back */
518 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
521 debug(DBG_DBG, "radtlsget: got %d bytes", total);
525 int clientradput(struct server *server, unsigned char *rad) {
529 struct timeval lastconnecttry;
532 if (server->peer.type == 'U') {
533 if (send(server->sock, rad, len, 0) >= 0) {
534 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->peer.host, server->peer.port);
537 debug(DBG_WARN, "clientradput: send failed");
541 lastconnecttry = server->lastconnecttry;
542 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
543 while ((error = ERR_get_error()))
544 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
545 tlsconnect(server, &lastconnecttry, "clientradput");
546 lastconnecttry = server->lastconnecttry;
549 server->connectionok = 1;
550 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
551 cnt, len, server->peer.host);
555 int radsign(unsigned char *rad, unsigned char *sec) {
556 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
557 static unsigned char first = 1;
558 static EVP_MD_CTX mdctx;
562 pthread_mutex_lock(&lock);
564 EVP_MD_CTX_init(&mdctx);
568 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
569 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
570 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
571 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
573 pthread_mutex_unlock(&lock);
577 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
578 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
579 static unsigned char first = 1;
580 static EVP_MD_CTX mdctx;
581 unsigned char hash[EVP_MAX_MD_SIZE];
585 pthread_mutex_lock(&lock);
587 EVP_MD_CTX_init(&mdctx);
593 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
594 EVP_DigestUpdate(&mdctx, rad, 4) &&
595 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
596 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
597 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
598 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
600 !memcmp(hash, rad + 4, 16));
601 pthread_mutex_unlock(&lock);
605 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
606 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
607 static unsigned char first = 1;
608 static HMAC_CTX hmacctx;
610 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
612 pthread_mutex_lock(&lock);
614 HMAC_CTX_init(&hmacctx);
618 memcpy(auth, authattr, 16);
619 memset(authattr, 0, 16);
621 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
622 HMAC_Update(&hmacctx, rad, RADLEN(rad));
623 HMAC_Final(&hmacctx, hash, &md_len);
624 memcpy(authattr, auth, 16);
626 debug(DBG_WARN, "message auth computation failed");
627 pthread_mutex_unlock(&lock);
631 if (memcmp(auth, hash, 16)) {
632 debug(DBG_WARN, "message authenticator, wrong value");
633 pthread_mutex_unlock(&lock);
637 pthread_mutex_unlock(&lock);
641 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
642 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
643 static unsigned char first = 1;
644 static HMAC_CTX hmacctx;
650 pthread_mutex_lock(&lock);
652 HMAC_CTX_init(&hmacctx);
656 memset(authattrval, 0, 16);
658 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
659 HMAC_Update(&hmacctx, rad, RADLEN(rad));
660 HMAC_Final(&hmacctx, authattrval, &md_len);
662 debug(DBG_WARN, "message auth computation failed");
663 pthread_mutex_unlock(&lock);
667 pthread_mutex_unlock(&lock);
671 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type, uint8_t *len) {
673 if (attrs[RAD_Attr_Type] == type) {
675 *len = attrs[RAD_Attr_Length] - 2;
676 return &attrs[RAD_Attr_Value];
678 length -= attrs[RAD_Attr_Length];
679 attrs += attrs[RAD_Attr_Length];
684 void sendrq(struct server *to, struct client *from, struct request *rq) {
688 pthread_mutex_lock(&to->newrq_mutex);
689 /* might simplify if only try nextid, might be ok */
690 for (i = to->nextid; i < MAX_REQUESTS; i++)
691 if (!to->requests[i].buf)
693 if (i == MAX_REQUESTS) {
694 for (i = 0; i < to->nextid; i++)
695 if (!to->requests[i].buf)
697 if (i == to->nextid) {
698 debug(DBG_WARN, "No room in queue, dropping request");
699 pthread_mutex_unlock(&to->newrq_mutex);
705 rq->buf[1] = (char)i;
706 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
708 attrval = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator, NULL);
709 if (attrval && !createmessageauth(rq->buf, attrval, to->peer.secret))
712 to->requests[i] = *rq;
716 debug(DBG_DBG, "signalling client writer");
717 pthread_cond_signal(&to->newrq_cond);
719 pthread_mutex_unlock(&to->newrq_mutex);
722 void sendreply(struct client *to, struct server *from, unsigned char *buf, struct sockaddr_storage *tosa) {
723 struct replyq *replyq = to->replyq;
725 pthread_mutex_lock(&replyq->count_mutex);
726 if (replyq->count == replyq->size) {
727 debug(DBG_WARN, "No room in queue, dropping request");
728 pthread_mutex_unlock(&replyq->count_mutex);
732 replyq->replies[replyq->count].buf = buf;
734 replyq->replies[replyq->count].tosa = *tosa;
737 if (replyq->count == 1) {
738 debug(DBG_DBG, "signalling client writer");
739 pthread_cond_signal(&replyq->count_cond);
741 pthread_mutex_unlock(&replyq->count_mutex);
744 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
745 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
746 static unsigned char first = 1;
747 static EVP_MD_CTX mdctx;
748 unsigned char hash[EVP_MAX_MD_SIZE], *input;
750 uint8_t i, offset = 0, out[128];
752 pthread_mutex_lock(&lock);
754 EVP_MD_CTX_init(&mdctx);
760 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
761 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
762 !EVP_DigestUpdate(&mdctx, input, 16) ||
763 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
765 pthread_mutex_unlock(&lock);
768 for (i = 0; i < 16; i++)
769 out[offset + i] = hash[i] ^ in[offset + i];
770 input = out + offset - 16;
775 memcpy(in, out, len);
776 pthread_mutex_unlock(&lock);
780 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
781 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
782 static unsigned char first = 1;
783 static EVP_MD_CTX mdctx;
784 unsigned char hash[EVP_MAX_MD_SIZE], *input;
786 uint8_t i, offset = 0, out[128];
788 pthread_mutex_lock(&lock);
790 EVP_MD_CTX_init(&mdctx);
796 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
797 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
798 !EVP_DigestUpdate(&mdctx, input, 16) ||
799 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
801 pthread_mutex_unlock(&lock);
804 for (i = 0; i < 16; i++)
805 out[offset + i] = hash[i] ^ in[offset + i];
811 memcpy(in, out, len);
812 pthread_mutex_unlock(&lock);
816 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
817 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
818 static unsigned char first = 1;
819 static EVP_MD_CTX mdctx;
820 unsigned char hash[EVP_MAX_MD_SIZE];
824 pthread_mutex_lock(&lock);
826 EVP_MD_CTX_init(&mdctx);
831 printf("msppencrypt auth in: ");
832 for (i = 0; i < 16; i++)
833 printf("%02x ", auth[i]);
836 printf("msppencrypt salt in: ");
837 for (i = 0; i < 2; i++)
838 printf("%02x ", salt[i]);
841 printf("msppencrypt in: ");
842 for (i = 0; i < len; i++)
843 printf("%02x ", text[i]);
847 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
848 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
849 !EVP_DigestUpdate(&mdctx, auth, 16) ||
850 !EVP_DigestUpdate(&mdctx, salt, 2) ||
851 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
852 pthread_mutex_unlock(&lock);
857 printf("msppencrypt hash: ");
858 for (i = 0; i < 16; i++)
859 printf("%02x ", hash[i]);
863 for (i = 0; i < 16; i++)
866 for (offset = 16; offset < len; offset += 16) {
868 printf("text + offset - 16 c(%d): ", offset / 16);
869 for (i = 0; i < 16; i++)
870 printf("%02x ", (text + offset - 16)[i]);
873 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
874 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
875 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
876 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
878 pthread_mutex_unlock(&lock);
882 printf("msppencrypt hash: ");
883 for (i = 0; i < 16; i++)
884 printf("%02x ", hash[i]);
888 for (i = 0; i < 16; i++)
889 text[offset + i] ^= hash[i];
893 printf("msppencrypt out: ");
894 for (i = 0; i < len; i++)
895 printf("%02x ", text[i]);
899 pthread_mutex_unlock(&lock);
903 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
904 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
905 static unsigned char first = 1;
906 static EVP_MD_CTX mdctx;
907 unsigned char hash[EVP_MAX_MD_SIZE];
912 pthread_mutex_lock(&lock);
914 EVP_MD_CTX_init(&mdctx);
919 printf("msppdecrypt auth in: ");
920 for (i = 0; i < 16; i++)
921 printf("%02x ", auth[i]);
924 printf("msppedecrypt salt in: ");
925 for (i = 0; i < 2; i++)
926 printf("%02x ", salt[i]);
929 printf("msppedecrypt in: ");
930 for (i = 0; i < len; i++)
931 printf("%02x ", text[i]);
935 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
936 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
937 !EVP_DigestUpdate(&mdctx, auth, 16) ||
938 !EVP_DigestUpdate(&mdctx, salt, 2) ||
939 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
940 pthread_mutex_unlock(&lock);
945 printf("msppedecrypt hash: ");
946 for (i = 0; i < 16; i++)
947 printf("%02x ", hash[i]);
951 for (i = 0; i < 16; i++)
952 plain[i] = text[i] ^ hash[i];
954 for (offset = 16; offset < len; offset += 16) {
956 printf("text + offset - 16 c(%d): ", offset / 16);
957 for (i = 0; i < 16; i++)
958 printf("%02x ", (text + offset - 16)[i]);
961 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
962 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
963 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
964 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
966 pthread_mutex_unlock(&lock);
970 printf("msppedecrypt hash: ");
971 for (i = 0; i < 16; i++)
972 printf("%02x ", hash[i]);
976 for (i = 0; i < 16; i++)
977 plain[offset + i] = text[offset + i] ^ hash[i];
980 memcpy(text, plain, len);
982 printf("msppedecrypt out: ");
983 for (i = 0; i < len; i++)
984 printf("%02x ", text[i]);
988 pthread_mutex_unlock(&lock);
992 struct server *id2server(char *id, uint8_t len) {
994 char **realm, *idrealm;
996 idrealm = strchr(id, '@');
1004 for (i = 0; i < server_count; i++) {
1005 for (realm = servers[i].realms; *realm; realm++) {
1006 if ((strlen(*realm) == 1 && **realm == '*') ||
1007 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
1008 debug(DBG_DBG, "found matching realm: %s, host %s", *realm, servers[i].peer.host);
1016 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1019 pthread_mutex_lock(&to->newrq_mutex);
1020 for (i = 0; i < MAX_REQUESTS; i++)
1021 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1023 pthread_mutex_unlock(&to->newrq_mutex);
1025 return i < MAX_REQUESTS;
1028 int attrvalidate(unsigned char *attrs, int length) {
1029 while (length > 1) {
1030 if (attrs[RAD_Attr_Length] < 2) {
1031 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", attrs[RAD_Attr_Length]);
1034 length -= attrs[RAD_Attr_Length];
1036 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", attrs[RAD_Attr_Length]);
1039 attrs += attrs[RAD_Attr_Length];
1042 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1046 struct server *radsrv(struct request *rq, unsigned char *buf, struct client *from) {
1047 uint8_t code, id, *auth, *attrs, attrvallen, *attrval;
1051 unsigned char newauth[16];
1056 code = *(uint8_t *)buf;
1057 id = *(uint8_t *)(buf + 1);
1059 auth = (uint8_t *)(buf + 4);
1061 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1063 if (code != RAD_Access_Request) {
1064 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, ignoring");
1071 if (!attrvalidate(attrs, len)) {
1072 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1076 attrval = attrget(attrs, len, RAD_Attr_User_Name, &attrvallen);
1078 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1081 memcpy(username, attrval, attrvallen);
1082 username[attrvallen] = '\0';
1083 debug(DBG_DBG, "Access Request with username: %s", username);
1085 to = id2server(username, attrvallen);
1087 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1091 if (rqinqueue(to, from, id)) {
1092 debug(DBG_INFO, "radsrv: ignoring request from host %s with id %d, already got one", from->peer.host, id);
1096 attrval = attrget(attrs, len, RAD_Attr_Message_Authenticator, &attrvallen);
1097 if (attrval && (attrvallen != 16 || !checkmessageauth(buf, attrval, from->peer.secret))) {
1098 debug(DBG_WARN, "radsrv: message authentication failed");
1102 if (!RAND_bytes(newauth, 16)) {
1103 debug(DBG_WARN, "radsrv: failed to generate random auth");
1108 printauth("auth", auth);
1109 printauth("newauth", newauth);
1112 attrval = attrget(attrs, len, RAD_Attr_User_Password, &attrvallen);
1114 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attrvallen);
1115 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1116 debug(DBG_WARN, "radsrv: invalid user password length");
1120 if (!pwddecrypt(attrval, attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1121 debug(DBG_WARN, "radsrv: cannot decrypt password");
1125 printf("radsrv: password: ");
1126 for (i = 0; i < attrvallen; i++)
1127 printf("%02x ", attrval[i]);
1130 if (!pwdencrypt(attrval, attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1131 debug(DBG_WARN, "radsrv: cannot encrypt password");
1136 attrval = attrget(attrs, len, RAD_Attr_Tunnel_Password, &attrvallen);
1138 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attrvallen);
1139 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1140 debug(DBG_WARN, "radsrv: invalid user password length");
1144 if (!pwddecrypt(attrval, attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1145 debug(DBG_WARN, "radsrv: cannot decrypt password");
1149 printf("radsrv: password: ");
1150 for (i = 0; i < attrvallen; i++)
1151 printf("%02x ", attrval[i]);
1154 if (!pwdencrypt(attrval, attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1155 debug(DBG_WARN, "radsrv: cannot encrypt password");
1163 memcpy(rq->origauth, auth, 16);
1164 memcpy(auth, newauth, 16);
1166 printauth("rq->origauth", (unsigned char *)rq->origauth);
1167 printauth("auth", auth);
1172 void *clientrd(void *arg) {
1173 struct server *server = (struct server *)arg;
1174 struct client *from;
1176 unsigned char *buf, *messageauth, *subattrs, *attrs, *attrval;
1178 struct sockaddr_storage fromsa;
1179 struct timeval lastconnecttry;
1183 lastconnecttry = server->lastconnecttry;
1184 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1185 if (!buf && server->peer.type == 'T') {
1186 tlsconnect(server, &lastconnecttry, "clientrd");
1190 server->connectionok = 1;
1192 i = buf[1]; /* i is the id */
1195 case RAD_Access_Accept:
1196 debug(DBG_DBG, "got Access Accept with id %d", i);
1198 case RAD_Access_Reject:
1199 debug(DBG_DBG, "got Access Reject with id %d", i);
1201 case RAD_Access_Challenge:
1202 debug(DBG_DBG, "got Access Challenge with id %d", i);
1205 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1209 pthread_mutex_lock(&server->newrq_mutex);
1210 if (!server->requests[i].buf || !server->requests[i].tries) {
1211 pthread_mutex_unlock(&server->newrq_mutex);
1212 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1216 if (server->requests[i].received) {
1217 pthread_mutex_unlock(&server->newrq_mutex);
1218 debug(DBG_INFO, "clientrd: already received, ignoring");
1222 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1223 pthread_mutex_unlock(&server->newrq_mutex);
1224 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1228 from = server->requests[i].from;
1229 len = RADLEN(buf) - 20;
1232 if (!attrvalidate(attrs, len)) {
1233 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1237 /* Message Authenticator */
1238 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator, &attrvallen);
1240 if (attrvallen != 16) {
1241 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1244 memcpy(tmp, buf + 4, 16);
1245 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1246 if (!checkmessageauth(buf, messageauth, server->peer.secret)) {
1247 debug(DBG_WARN, "clientrd: message authentication failed");
1250 memcpy(buf + 4, tmp, 16);
1251 debug(DBG_DBG, "clientrd: message auth ok");
1255 attrval = attrget(attrs, len, RAD_Attr_Vendor_Specific, &attrvallen);
1256 if (attrval && attrvallen > 4 && ((uint16_t *)attrval)[0] == 0 && ntohs(((uint16_t *)attrval)[1]) == 311) { /* 311 == MS */
1257 sublen = attrvallen - 4;
1258 subattrs = attrval + 4;
1259 if (!attrvalidate(subattrs, sublen)) {
1260 debug(DBG_WARN, "radsrv: MS attribute validation failed, ignoring packet");
1264 attrval = attrget(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, &attrvallen);
1266 debug(DBG_DBG, "clientrd: Got MS MPPE");
1267 if (attrvallen < 18)
1269 if (!msmppdecrypt(attrval + 2, attrvallen - 2, (unsigned char *)server->peer.secret,
1270 strlen(server->peer.secret), server->requests[i].buf + 4, attrval)) {
1271 debug(DBG_WARN, "clientrd: failed to decrypt msppe key");
1274 if (!msmppencrypt(attrval + 2, attrvallen - 2, (unsigned char *)from->peer.secret,
1275 strlen(from->peer.secret), (unsigned char *)server->requests[i].origauth, attrval)) {
1276 debug(DBG_WARN, "clientrd: failed to encrypt msppe key");
1281 attrval = attrget(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, &attrvallen);
1283 debug(DBG_DBG, "clientrd: Got MS MPPE");
1284 if (attrvallen < 18)
1286 if (!msmppdecrypt(attrval + 2, attrvallen - 2, (unsigned char *)server->peer.secret,
1287 strlen(server->peer.secret), server->requests[i].buf + 4, attrval)) {
1288 debug(DBG_WARN, "clientrd: failed to decrypt msppe key");
1291 if (!msmppencrypt(attrval + 2, attrvallen - 2, (unsigned char *)from->peer.secret,
1292 strlen(from->peer.secret), (unsigned char *)server->requests[i].origauth, attrval)) {
1293 debug(DBG_WARN, "clientrd: failed to encrypt msppe key");
1299 /* log DBG_INFO that received access accept/reject and username attr from original request */
1301 /* once we set received = 1, requests[i] may be reused */
1302 buf[1] = (char)server->requests[i].origid;
1303 memcpy(buf + 4, server->requests[i].origauth, 16);
1305 printauth("origauth/buf+4", buf + 4);
1309 if (!createmessageauth(buf, messageauth, from->peer.secret))
1311 debug(DBG_DBG, "clientrd: computed messageauthattr");
1314 if (from->peer.type == 'U')
1315 fromsa = server->requests[i].fromsa;
1316 server->requests[i].received = 1;
1317 pthread_mutex_unlock(&server->newrq_mutex);
1319 if (!radsign(buf, (unsigned char *)from->peer.secret)) {
1320 debug(DBG_WARN, "clientrd: failed to sign message");
1324 printauth("signedorigauth/buf+4", buf + 4);
1326 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1327 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1331 void *clientwr(void *arg) {
1332 struct server *server = (struct server *)arg;
1334 pthread_t clientrdth;
1337 struct timeval now, lastsend;
1338 struct timespec timeout;
1340 memset(&lastsend, 0, sizeof(struct timeval));
1341 memset(&timeout, 0, sizeof(struct timespec));
1343 if (server->peer.type == 'U') {
1344 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1345 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1347 tlsconnect(server, NULL, "new client");
1349 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1350 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1353 pthread_mutex_lock(&server->newrq_mutex);
1354 if (!server->newrq) {
1355 gettimeofday(&now, NULL);
1356 if (timeout.tv_sec) {
1357 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1358 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1360 } else if (options.statusserver) {
1361 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD;
1362 /* add random 0-7 seconds to timeout */
1363 RAND_bytes(&rnd, 1);
1364 timeout.tv_sec += rnd / 32;
1365 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1368 debug(DBG_DBG, "clientwr: waiting for new request");
1369 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1372 if (server->newrq) {
1373 debug(DBG_DBG, "clientwr: got new request");
1376 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1377 pthread_mutex_unlock(&server->newrq_mutex);
1379 for (i = 0; i < MAX_REQUESTS; i++) {
1380 pthread_mutex_lock(&server->newrq_mutex);
1381 while (!server->requests[i].buf && i < MAX_REQUESTS)
1383 if (i == MAX_REQUESTS) {
1384 pthread_mutex_unlock(&server->newrq_mutex);
1387 rq = server->requests + i;
1390 debug(DBG_DBG, "clientwr: removing received packet from queue");
1392 /* setting this to NULL means that it can be reused */
1394 pthread_mutex_unlock(&server->newrq_mutex);
1398 gettimeofday(&now, NULL);
1399 if (now.tv_sec <= rq->expiry.tv_sec) {
1400 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1401 timeout.tv_sec = rq->expiry.tv_sec;
1402 pthread_mutex_unlock(&server->newrq_mutex);
1406 if (rq->tries == (server->peer.type == 'T' ? 1 : REQUEST_RETRIES)) {
1407 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1409 /* setting this to NULL means that it can be reused */
1411 pthread_mutex_unlock(&server->newrq_mutex);
1414 pthread_mutex_unlock(&server->newrq_mutex);
1416 rq->expiry.tv_sec = now.tv_sec +
1417 (server->peer.type == 'T' ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1418 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1419 timeout.tv_sec = rq->expiry.tv_sec;
1421 clientradput(server, server->requests[i].buf);
1422 gettimeofday(&lastsend, NULL);
1425 if (options.statusserver) {
1426 gettimeofday(&now, NULL);
1427 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1428 lastsend.tv_sec = now.tv_sec;
1429 debug(DBG_DBG, "clientwr: should send status to %s here", server->peer.host);
1435 void *udpserverwr(void *arg) {
1436 struct replyq *replyq = &udp_server_replyq;
1437 struct reply *reply = replyq->replies;
1439 pthread_mutex_lock(&replyq->count_mutex);
1441 while (!replyq->count) {
1442 debug(DBG_DBG, "udp server writer, waiting for signal");
1443 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1444 debug(DBG_DBG, "udp server writer, got signal");
1446 pthread_mutex_unlock(&replyq->count_mutex);
1448 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1449 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1450 debug(DBG_WARN, "sendudp: send failed");
1453 pthread_mutex_lock(&replyq->count_mutex);
1455 memmove(replyq->replies, replyq->replies + 1,
1456 replyq->count * sizeof(struct reply));
1460 void *udpserverrd(void *arg) {
1465 pthread_t udpserverwrth;
1467 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1468 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1470 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1471 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1473 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1474 debugx(1, DBG_ERR, "pthread_create failed");
1478 memset(&rq, 0, sizeof(struct request));
1479 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1480 to = radsrv(&rq, buf, fr);
1482 debug(DBG_INFO, "udpserverrd: ignoring request, no place to send it");
1485 sendrq(to, fr, &rq);
1489 void *tlsserverwr(void *arg) {
1491 unsigned long error;
1492 struct client *client = (struct client *)arg;
1493 struct replyq *replyq;
1495 debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1496 replyq = client->replyq;
1497 pthread_mutex_lock(&replyq->count_mutex);
1499 while (!replyq->count) {
1500 if (client->peer.ssl) {
1501 debug(DBG_DBG, "tls server writer, waiting for signal");
1502 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1503 debug(DBG_DBG, "tls server writer, got signal");
1505 if (!client->peer.ssl) {
1506 /* ssl might have changed while waiting */
1507 pthread_mutex_unlock(&replyq->count_mutex);
1508 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1512 pthread_mutex_unlock(&replyq->count_mutex);
1513 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1515 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1516 cnt, RADLEN(replyq->replies->buf));
1518 while ((error = ERR_get_error()))
1519 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1520 free(replyq->replies->buf);
1522 pthread_mutex_lock(&replyq->count_mutex);
1524 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1528 void *tlsserverrd(void *arg) {
1531 unsigned long error;
1534 struct client *client = (struct client *)arg;
1535 pthread_t tlsserverwrth;
1538 debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1539 ssl = client->peer.ssl;
1541 if (SSL_accept(ssl) <= 0) {
1542 while ((error = ERR_get_error()))
1543 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1544 debug(DBG_ERR, "SSL_accept failed");
1547 if (tlsverifycert(&client->peer)) {
1548 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1549 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1553 buf = radtlsget(client->peer.ssl);
1556 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1557 memset(&rq, 0, sizeof(struct request));
1558 to = radsrv(&rq, buf, client);
1560 debug(DBG_INFO, "tlsserverrd: ignoring request, no place to send it");
1563 sendrq(to, client, &rq);
1565 debug(DBG_ERR, "tlsserverrd: connection lost");
1566 /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1567 client->peer.ssl = NULL;
1568 pthread_mutex_lock(&client->replyq->count_mutex);
1569 pthread_cond_signal(&client->replyq->count_cond);
1570 pthread_mutex_unlock(&client->replyq->count_mutex);
1571 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1572 pthread_join(tlsserverwrth, NULL);
1576 s = SSL_get_fd(ssl);
1578 shutdown(s, SHUT_RDWR);
1580 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1581 client->peer.ssl = NULL;
1586 pthread_t tlsserverth;
1588 struct sockaddr_storage from;
1589 size_t fromlen = sizeof(from);
1590 struct client *client;
1592 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1593 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1596 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1597 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1600 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1602 debug(DBG_WARN, "accept failed");
1605 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1607 client = find_client('T', (struct sockaddr *)&from, NULL);
1609 debug(DBG_WARN, "ignoring request, not a known TLS client");
1610 shutdown(snew, SHUT_RDWR);
1615 if (client->peer.ssl) {
1616 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1617 shutdown(snew, SHUT_RDWR);
1621 client->peer.ssl = SSL_new(ssl_ctx);
1622 SSL_set_fd(client->peer.ssl, snew);
1623 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1624 debug(DBG_ERR, "tlslistener: pthread_create failed");
1625 SSL_free(client->peer.ssl);
1626 shutdown(snew, SHUT_RDWR);
1628 client->peer.ssl = NULL;
1631 pthread_detach(tlsserverth);
1636 char *parsehostport(char *s, struct peer *peer) {
1641 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1645 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1647 debugx(1, DBG_ERR, "no ] matching initial [");
1651 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1654 debugx(1, DBG_ERR, "missing host/address");
1656 peer->host = stringcopy(field, p - field);
1659 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1660 debugx(1, DBG_ERR, "unexpected character after ]");
1663 /* port number or service name is specified */;
1665 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1667 debugx(1, DBG_ERR, "syntax error, : but no following port");
1668 peer->port = stringcopy(field, p - field);
1670 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1674 /* * is default, else longest match ... ";" used for separator */
1675 char *parserealmlist(char *s, struct server *server) {
1679 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1684 debugx(1, DBG_ERR, "realm list must be specified");
1686 server->realmdata = stringcopy(s, l);
1687 server->realms = malloc((1+n) * sizeof(char *));
1688 if (!server->realms)
1689 debugx(1, DBG_ERR, "malloc failed");
1690 server->realms[0] = server->realmdata;
1691 for (n = 1, i = 0; i < l; i++)
1692 if (server->realmdata[i] == ';') {
1693 server->realmdata[i] = '\0';
1694 server->realms[n++] = server->realmdata + i + 1;
1696 server->realms[n] = NULL;
1700 FILE *openconfigfile(const char *filename) {
1702 char pathname[100], *base;
1704 f = fopen(filename, "r");
1706 debug(DBG_DBG, "reading config file %s", filename);
1710 if (strlen(filename) + 1 <= sizeof(pathname)) {
1711 /* basename() might modify the string */
1712 strcpy(pathname, filename);
1713 base = basename(pathname);
1714 f = fopen(base, "r");
1718 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1720 debug(DBG_DBG, "reading config file %s", base);
1724 /* exactly one argument must be non-NULL */
1725 void getconfig(const char *serverfile, const char *clientfile) {
1728 char *p, *field, **r;
1729 struct client *client;
1730 struct server *server;
1732 int i, count, *ucount, *tcount;
1734 f = openconfigfile(serverfile ? serverfile : clientfile);
1736 ucount = &server_udp_count;
1737 tcount = &server_tls_count;
1739 ucount = &client_udp_count;
1740 tcount = &client_tls_count;
1742 while (fgets(line, 1024, f)) {
1743 for (p = line; *p == ' ' || *p == '\t'; p++);
1755 debugx(1, DBG_ERR, "type must be U or T, got %c", *p);
1760 count = server_count = server_udp_count + server_tls_count;
1761 servers = calloc(count, sizeof(struct server));
1763 debugx(1, DBG_ERR, "malloc failed");
1765 count = client_count = client_udp_count + client_tls_count;
1766 clients = calloc(count, sizeof(struct client));
1768 debugx(1, DBG_ERR, "malloc failed");
1771 if (client_udp_count) {
1772 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
1773 if (!udp_server_replyq.replies)
1774 debugx(1, DBG_ERR, "malloc failed");
1775 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
1776 udp_server_replyq.count = 0;
1777 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1778 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1782 for (i = 0; i < count && fgets(line, 1024, f);) {
1784 server = &servers[i];
1785 peer = &server->peer;
1787 client = &clients[i];
1788 peer = &client->peer;
1790 for (p = line; *p == ' ' || *p == '\t'; p++);
1791 if (*p == '#' || *p == '\n')
1793 peer->type = *p; /* we already know it must be U or T */
1794 for (p++; *p == ' ' || *p == '\t'; p++);
1795 p = parsehostport(p, peer);
1796 for (; *p == ' ' || *p == '\t'; p++);
1798 p = parserealmlist(p, server);
1799 for (; *p == ' ' || *p == '\t'; p++);
1802 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1804 /* no secret set and end of line, line is complete if TLS */
1805 if (peer->type == 'U')
1806 debugx(1, DBG_ERR, "secret must be specified for UDP");
1807 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1809 peer->secret = stringcopy(field, p - field);
1810 /* check that rest of line only white space */
1811 for (; *p == ' ' || *p == '\t'; p++);
1812 if (*p && *p != '\n')
1813 debugx(1, DBG_ERR, "max 4 fields per line, found a 5th");
1816 if ((serverfile && !resolvepeer(&server->peer, 0)) ||
1817 (clientfile && !resolvepeer(&client->peer, 0)))
1818 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
1821 pthread_mutex_init(&server->lock, NULL);
1823 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1824 if (!server->requests)
1825 debugx(1, DBG_ERR, "malloc failed");
1827 pthread_mutex_init(&server->newrq_mutex, NULL);
1828 pthread_cond_init(&server->newrq_cond, NULL);
1830 if (peer->type == 'U')
1831 client->replyq = &udp_server_replyq;
1833 client->replyq = malloc(sizeof(struct replyq));
1834 if (!client->replyq)
1835 debugx(1, DBG_ERR, "malloc failed");
1836 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1837 if (!client->replyq->replies)
1838 debugx(1, DBG_ERR, "malloc failed");
1839 client->replyq->size = MAX_REQUESTS;
1840 client->replyq->count = 0;
1841 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1842 pthread_cond_init(&client->replyq->count_cond, NULL);
1845 debug(DBG_DBG, "got type %c, host %s, port %s, secret %s", peer->type, peer->host, peer->port, peer->secret);
1847 debug(DBG_DBG, " with realms:");
1848 for (r = server->realms; *r; r++)
1849 debug(DBG_DBG, "\t%s", *r);
1856 struct peer *server_create(char type) {
1857 struct peer *server;
1860 server = malloc(sizeof(struct peer));
1862 debugx(1, DBG_ERR, "malloc failed");
1863 memset(server, 0, sizeof(struct peer));
1864 server->type = type;
1865 conf = (type == 'T' ? options.listentcp : options.listenudp);
1867 parsehostport(conf, server);
1868 if (!strcmp(server->host, "*")) {
1870 server->host = NULL;
1873 server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1874 if (!resolvepeer(server, AI_PASSIVE))
1875 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1879 void getmainconfig(const char *configfile) {
1882 char *p, *opt, *endopt, *val, *endval;
1884 f = openconfigfile(configfile);
1885 memset(&options, 0, sizeof(options));
1887 while (fgets(line, 1024, f)) {
1888 for (p = line; *p == ' ' || *p == '\t'; p++);
1889 if (!*p || *p == '#' || *p == '\n')
1892 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1894 for (; *p == ' ' || *p == '\t'; p++);
1895 if (!*p || *p == '\n') {
1897 debugx(1, DBG_ERR, "error in %s, option %s has no value", configfile, opt);
1900 for (; *p && *p != '\n'; p++)
1901 if (*p != ' ' && *p != '\t')
1905 debug(DBG_DBG, "getmainconfig: %s = %s", opt, val);
1907 if (!strcasecmp(opt, "TLSCACertificateFile")) {
1908 options.tlscacertificatefile = stringcopy(val, 0);
1911 if (!strcasecmp(opt, "TLSCACertificatePath")) {
1912 options.tlscacertificatepath = stringcopy(val, 0);
1915 if (!strcasecmp(opt, "TLSCertificateFile")) {
1916 options.tlscertificatefile = stringcopy(val, 0);
1919 if (!strcasecmp(opt, "TLSCertificateKeyFile")) {
1920 options.tlscertificatekeyfile = stringcopy(val, 0);
1923 if (!strcasecmp(opt, "TLSCertificateKeyPassword")) {
1924 options.tlscertificatekeypassword = stringcopy(val, 0);
1927 if (!strcasecmp(opt, "ListenUDP")) {
1928 options.listenudp = stringcopy(val, 0);
1931 if (!strcasecmp(opt, "ListenTCP")) {
1932 options.listentcp = stringcopy(val, 0);
1935 if (!strcasecmp(opt, "StatusServer")) {
1936 if (!strcasecmp(val, "on"))
1937 options.statusserver = 1;
1938 else if (strcasecmp(val, "off")) {
1939 debugx(1, DBG_ERR, "error in %s, value of option %s is %s, must be on or off", configfile, opt, val);
1943 if (!strcasecmp(opt, "LogLevel")) {
1944 if (strlen(val) != 1 || *val < '1' || *val > '4')
1945 debugx(1, DBG_ERR, "error in %s, value of option %s is %s, must be 1, 2, 3 or 4", configfile, opt, val);
1946 options.loglevel = *val - '0';
1949 if (!strcasecmp(opt, "LogDestination")) {
1950 options.logdestination = stringcopy(val, 0);
1953 debugx(1, DBG_ERR, "error in %s, unknown option %s", configfile, opt);
1958 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel) {
1961 while ((c = getopt(argc, argv, "d:f")) != -1) {
1964 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
1965 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
1966 *loglevel = *optarg - '0';
1975 if (!(argc - optind))
1979 debug(DBG_ERR, "Usage:\n%s [ -f ] [ -d debuglevel ]", argv[0]);
1983 int main(int argc, char **argv) {
1984 pthread_t udpserverth;
1986 uint8_t foreground = 0, loglevel = 0;
1988 debug_init("radsecproxy");
1989 debug_set_level(DEBUG_LEVEL);
1990 getargs(argc, argv, &foreground, &loglevel);
1992 debug_set_level(loglevel);
1993 getmainconfig(CONFIG_MAIN);
1995 options.loglevel = loglevel;
1996 else if (options.loglevel)
1997 debug_set_level(options.loglevel);
1999 options.logdestination = NULL;
2001 if (!options.logdestination)
2002 options.logdestination = "x-syslog://";
2003 debug_set_destination(options.logdestination);
2005 getconfig(CONFIG_SERVERS, NULL);
2006 getconfig(NULL, CONFIG_CLIENTS);
2008 if (!foreground && (daemon(0, 0) < 0))
2009 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2011 if (client_udp_count) {
2012 udp_server_listen = server_create('U');
2013 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2014 debugx(1, DBG_ERR, "pthread_create failed");
2017 if (client_tls_count || server_tls_count)
2018 ssl_ctx = ssl_init();
2020 for (i = 0; i < server_count; i++)
2021 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2022 debugx(1, DBG_ERR, "pthread_create failed");
2024 if (client_tls_count) {
2025 tcp_server_listen = server_create('T');
2026 return tlslistener();
2029 /* just hang around doing nothing, anything to do here? */