2 * Copyright (C) 2006, 2007 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
32 #include <sys/socket.h>
33 #include <netinet/in.h>
41 #include <openssl/ssl.h>
42 #include <openssl/rand.h>
43 #include <openssl/err.h>
44 #include <openssl/md5.h>
45 #include <openssl/hmac.h>
47 #include "radsecproxy.h"
49 static struct options options;
50 static struct client *clients = NULL;
51 static struct server *servers = NULL;
52 static struct realm *realms = NULL;
54 static int client_udp_count = 0;
55 static int client_tls_count = 0;
56 static int client_count = 0;
57 static int server_udp_count = 0;
58 static int server_tls_count = 0;
59 static int server_count = 0;
60 static int realm_count = 0;
62 static struct peer *tcp_server_listen;
63 static struct peer *udp_server_listen;
64 static struct replyq udp_server_replyq;
65 static int udp_server_sock = -1;
66 static pthread_mutex_t *ssl_locks;
67 static long *ssl_lock_count;
68 static SSL_CTX *ssl_ctx = NULL;
72 /* callbacks for making OpenSSL thread safe */
73 unsigned long ssl_thread_id() {
74 return (unsigned long)pthread_self();
77 void ssl_locking_callback(int mode, int type, const char *file, int line) {
78 if (mode & CRYPTO_LOCK) {
79 pthread_mutex_lock(&ssl_locks[type]);
80 ssl_lock_count[type]++;
82 pthread_mutex_unlock(&ssl_locks[type]);
85 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
86 int pwdlen = strlen(userdata);
87 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
89 memcpy(buf, userdata, pwdlen);
93 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
98 err_cert = X509_STORE_CTX_get_current_cert(ctx);
99 err = X509_STORE_CTX_get_error(ctx);
100 depth = X509_STORE_CTX_get_error_depth(ctx);
102 if (depth > MAX_CERT_DEPTH) {
104 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
105 X509_STORE_CTX_set_error(ctx, err);
109 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
110 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
113 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
114 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
115 debug(DBG_WARN, "\tIssuer=%s", buf);
117 case X509_V_ERR_CERT_NOT_YET_VALID:
118 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
119 debug(DBG_WARN, "\tCertificate not yet valid");
121 case X509_V_ERR_CERT_HAS_EXPIRED:
122 debug(DBG_WARN, "Certificate has expired");
124 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
125 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
130 printf("certificate verify returns %d\n", ok);
135 SSL_CTX *ssl_init() {
140 if (!options.tlscertificatefile || !options.tlscertificatekeyfile)
141 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS");
143 if (!options.tlscacertificatefile && !options.tlscacertificatepath)
144 debugx(1, DBG_ERR, "CA Certificate file/path need to be configured");
146 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
147 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
148 for (i = 0; i < CRYPTO_num_locks(); i++) {
149 ssl_lock_count[i] = 0;
150 pthread_mutex_init(&ssl_locks[i], NULL);
152 CRYPTO_set_id_callback(ssl_thread_id);
153 CRYPTO_set_locking_callback(ssl_locking_callback);
155 SSL_load_error_strings();
158 while (!RAND_status()) {
159 time_t t = time(NULL);
160 pid_t pid = getpid();
161 RAND_seed((unsigned char *)&t, sizeof(time_t));
162 RAND_seed((unsigned char *)&pid, sizeof(pid));
165 ctx = SSL_CTX_new(TLSv1_method());
166 if (options.tlscertificatekeypassword) {
167 SSL_CTX_set_default_passwd_cb_userdata(ctx, options.tlscertificatekeypassword);
168 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
170 if (SSL_CTX_use_certificate_chain_file(ctx, options.tlscertificatefile) &&
171 SSL_CTX_use_PrivateKey_file(ctx, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) &&
172 SSL_CTX_check_private_key(ctx) &&
173 SSL_CTX_load_verify_locations(ctx, options.tlscacertificatefile, options.tlscacertificatepath)) {
174 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
175 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
179 while ((error = ERR_get_error()))
180 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
181 debug(DBG_ERR, "Error initialising SSL/TLS");
186 void printauth(char *s, unsigned char *t) {
189 for (i = 0; i < 16; i++)
190 printf("%02x ", t[i]);
195 int resolvepeer(struct peer *peer, int ai_flags) {
196 struct addrinfo hints, *addrinfo;
198 memset(&hints, 0, sizeof(hints));
199 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
200 hints.ai_family = AF_UNSPEC;
201 hints.ai_flags = ai_flags;
202 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
203 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", peer->host, peer->port);
208 freeaddrinfo(peer->addrinfo);
209 peer->addrinfo = addrinfo;
213 int connecttoserver(struct addrinfo *addrinfo) {
215 struct addrinfo *res;
218 for (res = addrinfo; res; res = res->ai_next) {
219 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
221 debug(DBG_WARN, "connecttoserver: socket failed");
224 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
226 debug(DBG_WARN, "connecttoserver: connect failed");
233 int bindtoaddr(struct addrinfo *addrinfo) {
235 struct addrinfo *res;
237 for (res = addrinfo; res; res = res->ai_next) {
238 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
240 debug(DBG_WARN, "bindtoaddr: socket failed");
243 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
244 if (!bind(s, res->ai_addr, res->ai_addrlen))
246 debug(DBG_WARN, "bindtoaddr: bind failed");
252 /* returns the client with matching address, or NULL */
253 /* if client argument is not NULL, we only check that one client */
254 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
255 struct sockaddr_in6 *sa6 = NULL;
256 struct in_addr *a4 = NULL;
259 struct addrinfo *res;
261 if (addr->sa_family == AF_INET6) {
262 sa6 = (struct sockaddr_in6 *)addr;
263 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
264 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
266 a4 = &((struct sockaddr_in *)addr)->sin_addr;
268 c = (client ? client : clients);
269 for (i = 0; i < client_count; i++) {
270 if (c->peer.type == type)
271 for (res = c->peer.addrinfo; res; res = res->ai_next)
272 if ((a4 && res->ai_family == AF_INET &&
273 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
274 (res->ai_family == AF_INET6 &&
275 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
284 /* returns the server with matching address, or NULL */
285 /* if server argument is not NULL, we only check that one server */
286 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
287 struct sockaddr_in6 *sa6 = NULL;
288 struct in_addr *a4 = NULL;
291 struct addrinfo *res;
293 if (addr->sa_family == AF_INET6) {
294 sa6 = (struct sockaddr_in6 *)addr;
295 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
296 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
298 a4 = &((struct sockaddr_in *)addr)->sin_addr;
300 s = (server ? server : servers);
301 for (i = 0; i < server_count; i++) {
302 if (s->peer.type == type)
303 for (res = s->peer.addrinfo; res; res = res->ai_next)
304 if ((a4 && res->ai_family == AF_INET &&
305 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
306 (res->ai_family == AF_INET6 &&
307 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
316 /* exactly one of client and server must be non-NULL */
317 /* if *peer == NULL we return who we received from, else require it to be from peer */
318 /* return from in sa if not NULL */
319 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
322 unsigned char buf[65536], *rad;
323 struct sockaddr_storage from;
324 socklen_t fromlen = sizeof(from);
327 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
329 debug(DBG_WARN, "radudpget: recv failed");
332 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
335 debug(DBG_WARN, "radudpget: packet too small");
341 debug(DBG_WARN, "radudpget: length too small");
346 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
350 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
353 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
354 : (void *)find_server('U', (struct sockaddr *)&from, *server));
356 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
363 debug(DBG_ERR, "radudpget: malloc failed");
365 memcpy(rad, buf, len);
367 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
369 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
375 int tlsverifycert(struct peer *peer) {
383 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
384 debug(DBG_ERR, "tlsverifycert: basic validation failed");
385 while ((error = ERR_get_error()))
386 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
390 cert = SSL_get_peer_certificate(peer->ssl);
392 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
395 nm = X509_get_subject_name(cert);
398 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
401 e = X509_NAME_get_entry(nm, loc);
402 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
409 for (i = 0; i < l; i++)
414 if (l == strlen(peer->host) && !strncasecmp(peer->host, (char *)v, l)) {
415 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s, All OK", peer->host);
418 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", peer->host);
424 void tlsconnect(struct server *server, struct timeval *when, char *text) {
428 debug(DBG_DBG, "tlsconnect called from %s", text);
429 pthread_mutex_lock(&server->lock);
430 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
431 /* already reconnected, nothing to do */
432 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
433 pthread_mutex_unlock(&server->lock);
437 debug(DBG_DBG, "tlsconnect %s", text);
440 gettimeofday(&now, NULL);
441 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
442 if (server->connectionok) {
443 server->connectionok = 0;
445 } else if (elapsed < 5)
447 else if (elapsed < 300) {
448 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
450 } else if (elapsed < 100000) {
451 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
454 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
455 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->peer.host, server->peer.port);
456 if (server->sock >= 0)
458 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
459 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
463 SSL_free(server->peer.ssl);
464 server->peer.ssl = SSL_new(ssl_ctx);
465 SSL_set_fd(server->peer.ssl, server->sock);
466 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
469 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->peer.host, server->peer.port);
470 gettimeofday(&server->lastconnecttry, NULL);
471 pthread_mutex_unlock(&server->lock);
474 unsigned char *radtlsget(SSL *ssl) {
476 unsigned char buf[4], *rad;
479 for (total = 0; total < 4; total += cnt) {
480 cnt = SSL_read(ssl, buf + total, 4 - total);
482 debug(DBG_ERR, "radtlsget: connection lost");
483 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
484 /* remote end sent close_notify, send one back */
494 debug(DBG_ERR, "radtlsget: malloc failed");
499 for (; total < len; total += cnt) {
500 cnt = SSL_read(ssl, rad + total, len - total);
502 debug(DBG_ERR, "radtlsget: connection lost");
503 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
504 /* remote end sent close_notify, send one back */
516 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
519 debug(DBG_DBG, "radtlsget: got %d bytes", total);
523 int clientradput(struct server *server, unsigned char *rad) {
527 struct timeval lastconnecttry;
530 if (server->peer.type == 'U') {
531 if (send(server->sock, rad, len, 0) >= 0) {
532 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->peer.host, server->peer.port);
535 debug(DBG_WARN, "clientradput: send failed");
539 lastconnecttry = server->lastconnecttry;
540 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
541 while ((error = ERR_get_error()))
542 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
543 tlsconnect(server, &lastconnecttry, "clientradput");
544 lastconnecttry = server->lastconnecttry;
547 server->connectionok = 1;
548 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
549 cnt, len, server->peer.host);
553 int radsign(unsigned char *rad, unsigned char *sec) {
554 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
555 static unsigned char first = 1;
556 static EVP_MD_CTX mdctx;
560 pthread_mutex_lock(&lock);
562 EVP_MD_CTX_init(&mdctx);
566 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
567 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
568 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
569 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
571 pthread_mutex_unlock(&lock);
575 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
576 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
577 static unsigned char first = 1;
578 static EVP_MD_CTX mdctx;
579 unsigned char hash[EVP_MAX_MD_SIZE];
583 pthread_mutex_lock(&lock);
585 EVP_MD_CTX_init(&mdctx);
591 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
592 EVP_DigestUpdate(&mdctx, rad, 4) &&
593 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
594 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
595 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
596 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
598 !memcmp(hash, rad + 4, 16));
599 pthread_mutex_unlock(&lock);
603 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
604 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
605 static unsigned char first = 1;
606 static HMAC_CTX hmacctx;
608 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
610 pthread_mutex_lock(&lock);
612 HMAC_CTX_init(&hmacctx);
616 memcpy(auth, authattr, 16);
617 memset(authattr, 0, 16);
619 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
620 HMAC_Update(&hmacctx, rad, RADLEN(rad));
621 HMAC_Final(&hmacctx, hash, &md_len);
622 memcpy(authattr, auth, 16);
624 debug(DBG_WARN, "message auth computation failed");
625 pthread_mutex_unlock(&lock);
629 if (memcmp(auth, hash, 16)) {
630 debug(DBG_WARN, "message authenticator, wrong value");
631 pthread_mutex_unlock(&lock);
635 pthread_mutex_unlock(&lock);
639 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
640 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
641 static unsigned char first = 1;
642 static HMAC_CTX hmacctx;
648 pthread_mutex_lock(&lock);
650 HMAC_CTX_init(&hmacctx);
654 memset(authattrval, 0, 16);
656 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
657 HMAC_Update(&hmacctx, rad, RADLEN(rad));
658 HMAC_Final(&hmacctx, authattrval, &md_len);
660 debug(DBG_WARN, "message auth computation failed");
661 pthread_mutex_unlock(&lock);
665 pthread_mutex_unlock(&lock);
669 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
671 if (ATTRTYPE(attrs) == type)
673 length -= ATTRLEN(attrs);
674 attrs += ATTRLEN(attrs);
679 void sendrq(struct server *to, struct request *rq) {
683 pthread_mutex_lock(&to->newrq_mutex);
684 /* might simplify if only try nextid, might be ok */
685 for (i = to->nextid; i < MAX_REQUESTS; i++)
686 if (!to->requests[i].buf)
688 if (i == MAX_REQUESTS) {
689 for (i = 0; i < to->nextid; i++)
690 if (!to->requests[i].buf)
692 if (i == to->nextid) {
693 debug(DBG_WARN, "No room in queue, dropping request");
695 pthread_mutex_unlock(&to->newrq_mutex);
700 rq->buf[1] = (char)i;
702 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
703 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->peer.secret)) {
705 pthread_mutex_unlock(&to->newrq_mutex);
709 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
710 to->requests[i] = *rq;
715 debug(DBG_DBG, "signalling client writer");
716 pthread_cond_signal(&to->newrq_cond);
718 pthread_mutex_unlock(&to->newrq_mutex);
721 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
722 struct replyq *replyq = to->replyq;
724 if (!radsign(buf, (unsigned char *)to->peer.secret)) {
726 debug(DBG_WARN, "sendreply: failed to sign message");
730 pthread_mutex_lock(&replyq->count_mutex);
731 if (replyq->count == replyq->size) {
732 debug(DBG_WARN, "No room in queue, dropping request");
733 pthread_mutex_unlock(&replyq->count_mutex);
738 replyq->replies[replyq->count].buf = buf;
740 replyq->replies[replyq->count].tosa = *tosa;
743 if (replyq->count == 1) {
744 debug(DBG_DBG, "signalling server writer");
745 pthread_cond_signal(&replyq->count_cond);
747 pthread_mutex_unlock(&replyq->count_mutex);
750 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
751 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
752 static unsigned char first = 1;
753 static EVP_MD_CTX mdctx;
754 unsigned char hash[EVP_MAX_MD_SIZE], *input;
756 uint8_t i, offset = 0, out[128];
758 pthread_mutex_lock(&lock);
760 EVP_MD_CTX_init(&mdctx);
766 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
767 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
768 !EVP_DigestUpdate(&mdctx, input, 16) ||
769 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
771 pthread_mutex_unlock(&lock);
774 for (i = 0; i < 16; i++)
775 out[offset + i] = hash[i] ^ in[offset + i];
776 input = out + offset - 16;
781 memcpy(in, out, len);
782 pthread_mutex_unlock(&lock);
786 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
787 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
788 static unsigned char first = 1;
789 static EVP_MD_CTX mdctx;
790 unsigned char hash[EVP_MAX_MD_SIZE], *input;
792 uint8_t i, offset = 0, out[128];
794 pthread_mutex_lock(&lock);
796 EVP_MD_CTX_init(&mdctx);
802 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
803 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
804 !EVP_DigestUpdate(&mdctx, input, 16) ||
805 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
807 pthread_mutex_unlock(&lock);
810 for (i = 0; i < 16; i++)
811 out[offset + i] = hash[i] ^ in[offset + i];
817 memcpy(in, out, len);
818 pthread_mutex_unlock(&lock);
822 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
823 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
824 static unsigned char first = 1;
825 static EVP_MD_CTX mdctx;
826 unsigned char hash[EVP_MAX_MD_SIZE];
830 pthread_mutex_lock(&lock);
832 EVP_MD_CTX_init(&mdctx);
837 printf("msppencrypt auth in: ");
838 for (i = 0; i < 16; i++)
839 printf("%02x ", auth[i]);
842 printf("msppencrypt salt in: ");
843 for (i = 0; i < 2; i++)
844 printf("%02x ", salt[i]);
847 printf("msppencrypt in: ");
848 for (i = 0; i < len; i++)
849 printf("%02x ", text[i]);
853 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
854 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
855 !EVP_DigestUpdate(&mdctx, auth, 16) ||
856 !EVP_DigestUpdate(&mdctx, salt, 2) ||
857 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
858 pthread_mutex_unlock(&lock);
863 printf("msppencrypt hash: ");
864 for (i = 0; i < 16; i++)
865 printf("%02x ", hash[i]);
869 for (i = 0; i < 16; i++)
872 for (offset = 16; offset < len; offset += 16) {
874 printf("text + offset - 16 c(%d): ", offset / 16);
875 for (i = 0; i < 16; i++)
876 printf("%02x ", (text + offset - 16)[i]);
879 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
880 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
881 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
882 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
884 pthread_mutex_unlock(&lock);
888 printf("msppencrypt hash: ");
889 for (i = 0; i < 16; i++)
890 printf("%02x ", hash[i]);
894 for (i = 0; i < 16; i++)
895 text[offset + i] ^= hash[i];
899 printf("msppencrypt out: ");
900 for (i = 0; i < len; i++)
901 printf("%02x ", text[i]);
905 pthread_mutex_unlock(&lock);
909 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
910 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
911 static unsigned char first = 1;
912 static EVP_MD_CTX mdctx;
913 unsigned char hash[EVP_MAX_MD_SIZE];
918 pthread_mutex_lock(&lock);
920 EVP_MD_CTX_init(&mdctx);
925 printf("msppdecrypt auth in: ");
926 for (i = 0; i < 16; i++)
927 printf("%02x ", auth[i]);
930 printf("msppedecrypt salt in: ");
931 for (i = 0; i < 2; i++)
932 printf("%02x ", salt[i]);
935 printf("msppedecrypt in: ");
936 for (i = 0; i < len; i++)
937 printf("%02x ", text[i]);
941 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
942 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
943 !EVP_DigestUpdate(&mdctx, auth, 16) ||
944 !EVP_DigestUpdate(&mdctx, salt, 2) ||
945 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
946 pthread_mutex_unlock(&lock);
951 printf("msppedecrypt hash: ");
952 for (i = 0; i < 16; i++)
953 printf("%02x ", hash[i]);
957 for (i = 0; i < 16; i++)
958 plain[i] = text[i] ^ hash[i];
960 for (offset = 16; offset < len; offset += 16) {
962 printf("text + offset - 16 c(%d): ", offset / 16);
963 for (i = 0; i < 16; i++)
964 printf("%02x ", (text + offset - 16)[i]);
967 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
968 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
969 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
970 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
972 pthread_mutex_unlock(&lock);
976 printf("msppedecrypt hash: ");
977 for (i = 0; i < 16; i++)
978 printf("%02x ", hash[i]);
982 for (i = 0; i < 16; i++)
983 plain[offset + i] = text[offset + i] ^ hash[i];
986 memcpy(text, plain, len);
988 printf("msppedecrypt out: ");
989 for (i = 0; i < len; i++)
990 printf("%02x ", text[i]);
994 pthread_mutex_unlock(&lock);
998 struct realm *id2realm(char *id, uint8_t len) {
1000 for (i = 0; i < realm_count; i++)
1001 if (!regexec(&realms[i].regex, id, 0, NULL, 0)) {
1002 debug(DBG_DBG, "found matching realm: %s", realms[i].name);
1008 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1011 pthread_mutex_lock(&to->newrq_mutex);
1012 for (i = 0; i < MAX_REQUESTS; i++)
1013 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1015 pthread_mutex_unlock(&to->newrq_mutex);
1017 return i < MAX_REQUESTS;
1020 int attrvalidate(unsigned char *attrs, int length) {
1021 while (length > 1) {
1022 if (ATTRLEN(attrs) < 2) {
1023 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1026 length -= ATTRLEN(attrs);
1028 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1031 attrs += ATTRLEN(attrs);
1034 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1038 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1042 if (len < 16 || len > 128 || len % 16) {
1043 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1047 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1048 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1052 printf("pwdrecrypt: password: ");
1053 for (i = 0; i < len; i++)
1054 printf("%02x ", pwd[i]);
1057 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1058 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1064 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1067 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1068 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1071 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1072 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1078 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1079 char *oldsecret, char *newsecret) {
1080 unsigned char *attr;
1082 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1083 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1084 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1090 void respondstatusserver(struct request *rq) {
1091 unsigned char *resp;
1095 debug(DBG_ERR, "respondstatusserver: malloc failed");
1098 memcpy(resp, rq->buf, 20);
1099 resp[0] = RAD_Access_Accept;
1102 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->peer.host);
1103 sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1106 void respondreject(struct request *rq, char *message) {
1107 unsigned char *resp;
1111 len += 2 + strlen(message);
1115 debug(DBG_ERR, "respondreject: malloc failed");
1118 memcpy(resp, rq->buf, 20);
1119 resp[0] = RAD_Access_Reject;
1120 *(uint16_t *)(resp + 2) = htons(len);
1122 resp[20] = RAD_Attr_Reply_Message;
1123 resp[21] = len - 20;
1124 memcpy(resp + 22, message, len - 22);
1126 sendreply(rq->from, resp, rq->from->peer.type == 'U' ? &rq->fromsa : NULL);
1129 void radsrv(struct request *rq) {
1130 uint8_t code, id, *auth, *attrs, *attr;
1132 struct server *to = NULL;
1134 unsigned char *buf, newauth[16];
1135 struct realm *realm = NULL;
1138 code = *(uint8_t *)buf;
1139 id = *(uint8_t *)(buf + 1);
1141 auth = (uint8_t *)(buf + 4);
1143 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1145 if (code != RAD_Access_Request && code != RAD_Status_Server) {
1146 debug(DBG_INFO, "radsrv: server currently accepts only access-requests and status-server, ignoring");
1154 if (!attrvalidate(attrs, len)) {
1155 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1160 if (code == RAD_Access_Request) {
1161 attr = attrget(attrs, len, RAD_Attr_User_Name);
1163 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1167 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1168 username[ATTRVALLEN(attr)] = '\0';
1169 debug(DBG_DBG, "Access Request with username: %s", username);
1171 realm = id2realm(username, strlen(username));
1173 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1179 if (to && rqinqueue(to, rq->from, id)) {
1180 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->peer.host, id);
1186 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1187 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->peer.secret))) {
1188 debug(DBG_WARN, "radsrv: message authentication failed");
1193 if (code == RAD_Status_Server) {
1194 respondstatusserver(rq);
1199 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->peer.host, username);
1200 respondreject(rq, realm->message);
1204 if (!RAND_bytes(newauth, 16)) {
1205 debug(DBG_WARN, "radsrv: failed to generate random auth");
1211 printauth("auth", auth);
1214 attr = attrget(attrs, len, RAD_Attr_User_Password);
1216 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1217 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1223 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1225 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1226 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->peer.secret, to->peer.secret, auth, newauth)) {
1233 memcpy(rq->origauth, auth, 16);
1234 memcpy(auth, newauth, 16);
1238 void *clientrd(void *arg) {
1239 struct server *server = (struct server *)arg;
1240 struct client *from;
1242 unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1243 struct sockaddr_storage fromsa;
1244 struct timeval lastconnecttry;
1248 lastconnecttry = server->lastconnecttry;
1249 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1250 if (!buf && server->peer.type == 'T') {
1251 tlsconnect(server, &lastconnecttry, "clientrd");
1255 server->connectionok = 1;
1257 i = buf[1]; /* i is the id */
1260 case RAD_Access_Accept:
1261 debug(DBG_DBG, "got Access Accept with id %d", i);
1263 case RAD_Access_Reject:
1264 debug(DBG_DBG, "got Access Reject with id %d", i);
1266 case RAD_Access_Challenge:
1267 debug(DBG_DBG, "got Access Challenge with id %d", i);
1271 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1275 pthread_mutex_lock(&server->newrq_mutex);
1276 if (!server->requests[i].buf || !server->requests[i].tries) {
1277 pthread_mutex_unlock(&server->newrq_mutex);
1279 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1283 if (server->requests[i].received) {
1284 pthread_mutex_unlock(&server->newrq_mutex);
1286 debug(DBG_INFO, "clientrd: already received, ignoring");
1290 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1291 pthread_mutex_unlock(&server->newrq_mutex);
1293 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1297 from = server->requests[i].from;
1298 len = RADLEN(buf) - 20;
1301 if (!attrvalidate(attrs, len)) {
1302 pthread_mutex_unlock(&server->newrq_mutex);
1304 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1308 /* Message Authenticator */
1309 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1311 if (ATTRVALLEN(messageauth) != 16) {
1312 pthread_mutex_unlock(&server->newrq_mutex);
1314 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1317 memcpy(tmp, buf + 4, 16);
1318 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1319 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->peer.secret)) {
1320 pthread_mutex_unlock(&server->newrq_mutex);
1322 debug(DBG_WARN, "clientrd: message authentication failed");
1325 memcpy(buf + 4, tmp, 16);
1326 debug(DBG_DBG, "clientrd: message auth ok");
1329 if (*server->requests[i].buf == RAD_Status_Server) {
1330 server->requests[i].received = 1;
1331 pthread_mutex_unlock(&server->newrq_mutex);
1333 debug(DBG_INFO, "clientrd: got status server response from %s", server->peer.host);
1338 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1339 if (ATTRVALLEN(attr) <= 4)
1342 if (((uint16_t *)attr)[1] != 0 || ntohs(((uint16_t *)attr)[2]) != 311) /* 311 == MS */
1345 sublen = ATTRVALLEN(attr) - 4;
1346 subattrs = ATTRVAL(attr) + 4;
1347 if (!attrvalidate(subattrs, sublen) ||
1348 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1349 server->requests + i, server->peer.secret, from->peer.secret) ||
1350 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1351 server->requests + i, server->peer.secret, from->peer.secret))
1355 pthread_mutex_unlock(&server->newrq_mutex);
1357 debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1361 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1362 attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1363 /* we know the attribute exists */
1364 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1365 tmp[ATTRVALLEN(attr)] = '\0';
1367 case RAD_Access_Accept:
1368 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->peer.host);
1370 case RAD_Access_Reject:
1371 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->peer.host);
1376 /* once we set received = 1, requests[i] may be reused */
1377 buf[1] = (char)server->requests[i].origid;
1378 memcpy(buf + 4, server->requests[i].origauth, 16);
1380 printauth("origauth/buf+4", buf + 4);
1384 if (!createmessageauth(buf, ATTRVAL(messageauth), from->peer.secret)) {
1385 pthread_mutex_unlock(&server->newrq_mutex);
1389 debug(DBG_DBG, "clientrd: computed messageauthattr");
1392 if (from->peer.type == 'U')
1393 fromsa = server->requests[i].fromsa;
1394 server->requests[i].received = 1;
1395 pthread_mutex_unlock(&server->newrq_mutex);
1397 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1398 sendreply(from, buf, from->peer.type == 'U' ? &fromsa : NULL);
1402 void *clientwr(void *arg) {
1403 struct server *server = (struct server *)arg;
1405 pthread_t clientrdth;
1408 struct timeval now, lastsend;
1409 struct timespec timeout;
1410 struct request statsrvrq;
1411 unsigned char statsrvbuf[38];
1413 memset(&timeout, 0, sizeof(struct timespec));
1415 if (server->statusserver) {
1416 memset(&statsrvrq, 0, sizeof(struct request));
1417 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1418 statsrvbuf[0] = RAD_Status_Server;
1420 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1421 statsrvbuf[21] = 18;
1422 gettimeofday(&lastsend, NULL);
1425 if (server->peer.type == 'U') {
1426 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1427 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1429 tlsconnect(server, NULL, "new client");
1431 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1432 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1435 pthread_mutex_lock(&server->newrq_mutex);
1436 if (!server->newrq) {
1437 gettimeofday(&now, NULL);
1438 if (server->statusserver) {
1439 /* random 0-7 seconds */
1440 RAND_bytes(&rnd, 1);
1442 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1443 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1445 if (timeout.tv_sec) {
1446 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1447 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1450 debug(DBG_DBG, "clientwr: waiting for new request");
1451 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1454 if (server->newrq) {
1455 debug(DBG_DBG, "clientwr: got new request");
1458 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1459 pthread_mutex_unlock(&server->newrq_mutex);
1461 for (i = 0; i < MAX_REQUESTS; i++) {
1462 pthread_mutex_lock(&server->newrq_mutex);
1463 while (!server->requests[i].buf && i < MAX_REQUESTS)
1465 if (i == MAX_REQUESTS) {
1466 pthread_mutex_unlock(&server->newrq_mutex);
1469 rq = server->requests + i;
1472 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1474 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1476 /* setting this to NULL means that it can be reused */
1479 pthread_mutex_unlock(&server->newrq_mutex);
1483 gettimeofday(&now, NULL);
1484 if (now.tv_sec < rq->expiry.tv_sec) {
1485 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1486 timeout.tv_sec = rq->expiry.tv_sec;
1487 pthread_mutex_unlock(&server->newrq_mutex);
1491 if (rq->tries == (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1492 ? 1 : REQUEST_RETRIES)) {
1493 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1494 if (*rq->buf == RAD_Status_Server)
1495 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->peer.host);
1497 /* setting this to NULL means that it can be reused */
1499 pthread_mutex_unlock(&server->newrq_mutex);
1502 pthread_mutex_unlock(&server->newrq_mutex);
1504 rq->expiry.tv_sec = now.tv_sec +
1505 (*rq->buf == RAD_Status_Server || server->peer.type == 'T'
1506 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1507 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1508 timeout.tv_sec = rq->expiry.tv_sec;
1510 clientradput(server, server->requests[i].buf);
1511 gettimeofday(&lastsend, NULL);
1513 if (server->statusserver) {
1514 gettimeofday(&now, NULL);
1515 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1516 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1517 debug(DBG_WARN, "clientwr: failed to generate random auth");
1520 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1521 if (!statsrvrq.buf) {
1522 debug(DBG_ERR, "clientwr: malloc failed");
1525 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1526 debug(DBG_DBG, "clientwr: sending status server to %s", server->peer.host);
1527 lastsend.tv_sec = now.tv_sec;
1528 sendrq(server, &statsrvrq);
1534 void *udpserverwr(void *arg) {
1535 struct replyq *replyq = &udp_server_replyq;
1536 struct reply *reply = replyq->replies;
1538 pthread_mutex_lock(&replyq->count_mutex);
1540 while (!replyq->count) {
1541 debug(DBG_DBG, "udp server writer, waiting for signal");
1542 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1543 debug(DBG_DBG, "udp server writer, got signal");
1545 pthread_mutex_unlock(&replyq->count_mutex);
1547 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1548 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1549 debug(DBG_WARN, "sendudp: send failed");
1552 pthread_mutex_lock(&replyq->count_mutex);
1554 memmove(replyq->replies, replyq->replies + 1,
1555 replyq->count * sizeof(struct reply));
1559 void *udpserverrd(void *arg) {
1561 pthread_t udpserverwrth;
1563 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1564 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1566 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1567 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1569 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1570 debugx(1, DBG_ERR, "pthread_create failed");
1573 memset(&rq, 0, sizeof(struct request));
1574 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1579 void *tlsserverwr(void *arg) {
1581 unsigned long error;
1582 struct client *client = (struct client *)arg;
1583 struct replyq *replyq;
1585 debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1586 replyq = client->replyq;
1587 pthread_mutex_lock(&replyq->count_mutex);
1589 while (!replyq->count) {
1590 if (client->peer.ssl) {
1591 debug(DBG_DBG, "tls server writer, waiting for signal");
1592 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1593 debug(DBG_DBG, "tls server writer, got signal");
1595 if (!client->peer.ssl) {
1596 /* ssl might have changed while waiting */
1597 pthread_mutex_unlock(&replyq->count_mutex);
1598 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1602 pthread_mutex_unlock(&replyq->count_mutex);
1603 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1605 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1606 cnt, RADLEN(replyq->replies->buf));
1608 while ((error = ERR_get_error()))
1609 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1610 free(replyq->replies->buf);
1612 pthread_mutex_lock(&replyq->count_mutex);
1614 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1618 void *tlsserverrd(void *arg) {
1620 unsigned long error;
1622 struct client *client = (struct client *)arg;
1623 pthread_t tlsserverwrth;
1626 debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1627 ssl = client->peer.ssl;
1629 if (SSL_accept(ssl) <= 0) {
1630 while ((error = ERR_get_error()))
1631 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1632 debug(DBG_ERR, "SSL_accept failed");
1635 if (tlsverifycert(&client->peer)) {
1636 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1637 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1641 memset(&rq, 0, sizeof(struct request));
1642 rq.buf = radtlsget(client->peer.ssl);
1645 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1649 debug(DBG_ERR, "tlsserverrd: connection lost");
1650 /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1651 client->peer.ssl = NULL;
1652 pthread_mutex_lock(&client->replyq->count_mutex);
1653 pthread_cond_signal(&client->replyq->count_cond);
1654 pthread_mutex_unlock(&client->replyq->count_mutex);
1655 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1656 pthread_join(tlsserverwrth, NULL);
1660 s = SSL_get_fd(ssl);
1662 shutdown(s, SHUT_RDWR);
1664 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1665 client->peer.ssl = NULL;
1670 pthread_t tlsserverth;
1672 struct sockaddr_storage from;
1673 size_t fromlen = sizeof(from);
1674 struct client *client;
1676 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1677 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1680 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1681 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1684 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1686 debug(DBG_WARN, "accept failed");
1689 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1691 client = find_client('T', (struct sockaddr *)&from, NULL);
1693 debug(DBG_WARN, "ignoring request, not a known TLS client");
1694 shutdown(snew, SHUT_RDWR);
1699 if (client->peer.ssl) {
1700 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1701 shutdown(snew, SHUT_RDWR);
1705 client->peer.ssl = SSL_new(ssl_ctx);
1706 SSL_set_fd(client->peer.ssl, snew);
1707 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1708 debug(DBG_ERR, "tlslistener: pthread_create failed");
1709 SSL_free(client->peer.ssl);
1710 shutdown(snew, SHUT_RDWR);
1712 client->peer.ssl = NULL;
1715 pthread_detach(tlsserverth);
1720 void addrealm(char *value, char *server, char *message) {
1722 struct realm *realm;
1723 char *s, *regex = NULL;
1726 for (i = 0; i < server_count; i++)
1727 if (!strcasecmp(server, servers[i].peer.host))
1729 if (i == server_count)
1730 debugx(1, DBG_ERR, "addrealm failed, no server %s", server);
1733 if (*value != '/') {
1734 /* not a regexp, let us make it one */
1735 if (*value == '*' && !value[1])
1736 regex = stringcopy(".*", 0);
1738 for (n = 0, s = value; *s;)
1741 regex = malloc(strlen(value) + n + 3);
1744 for (n = 1, s = value; *s; s++) {
1754 debugx(1, DBG_ERR, "malloc failed");
1755 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
1759 realms = realloc(realms, realm_count * sizeof(struct realm));
1761 debugx(1, DBG_ERR, "malloc failed");
1762 realm = realms + realm_count - 1;
1763 memset(realm, 0, sizeof(struct realm));
1764 realm->name = stringcopy(value, 0);
1766 debugx(1, DBG_ERR, "malloc failed");
1767 if (message && strlen(message) > 253)
1768 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
1769 realm->message = message;
1771 realm->server = servers + i;
1772 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
1773 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
1776 debug(DBG_DBG, "addrealm: added realm %s for server %s", value, server);
1779 char *parsehostport(char *s, struct peer *peer) {
1784 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1788 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1790 debugx(1, DBG_ERR, "no ] matching initial [");
1794 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1797 debugx(1, DBG_ERR, "missing host/address");
1799 peer->host = stringcopy(field, p - field);
1802 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1803 debugx(1, DBG_ERR, "unexpected character after ]");
1806 /* port number or service name is specified */;
1808 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1810 debugx(1, DBG_ERR, "syntax error, : but no following port");
1811 peer->port = stringcopy(field, p - field);
1813 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1817 FILE *openconfigfile(const char *filename) {
1819 char pathname[100], *base = NULL;
1821 f = fopen(filename, "r");
1823 debug(DBG_DBG, "reading config file %s", filename);
1827 if (strlen(filename) + 1 <= sizeof(pathname)) {
1828 /* basename() might modify the string */
1829 strcpy(pathname, filename);
1830 base = basename(pathname);
1831 f = fopen(base, "r");
1835 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1837 debug(DBG_DBG, "reading config file %s", base);
1841 struct peer *server_create(char type) {
1842 struct peer *server;
1845 server = malloc(sizeof(struct peer));
1847 debugx(1, DBG_ERR, "malloc failed");
1848 memset(server, 0, sizeof(struct peer));
1849 server->type = type;
1850 conf = (type == 'T' ? options.listentcp : options.listenudp);
1852 parsehostport(conf, server);
1853 if (!strcmp(server->host, "*")) {
1855 server->host = NULL;
1858 server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1859 if (!resolvepeer(server, AI_PASSIVE))
1860 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1864 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
1865 char *strtokenquote(char *s, char **token, char *del, char *quote) {
1866 char *t = s, *q, *r;
1868 if (!t || !token || !del)
1870 while (*t && strchr(del, *t))
1874 return t + 1; /* needs to be non-NULL, but value doesn't matter */
1876 if (quote && (q = strchr(quote, *t))) {
1879 while (*t && *t != *q)
1881 if (!*t || (t[1] && !strchr(del, t[1])))
1889 while (*t && !strchr(del, *t))
1895 /* Parses config with following syntax:
1898 * option-name = value
1900 * option-name value {
1901 * option-name [=] value
1905 void getgeneralconfig(FILE *f, char *block, ...) {
1908 /* initialise lots of stuff to avoid stupid compiler warnings */
1909 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, **str = NULL;
1910 int type = 0, tcount, conftype = 0;
1911 void (*cbk)(FILE *, char *, char *) = NULL;
1913 while (fgets(line, 1024, f)) {
1915 for (tcount = 0; tcount < 3; tcount++) {
1916 s = strtokenquote(s, &tokens[tcount], " \t\n", "\"'");
1918 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
1919 if (!tokens[tcount])
1922 if (!tcount || **tokens == '#')
1925 if (**tokens == '}') {
1928 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
1935 conftype = CONF_STR;
1938 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
1941 conftype = CONF_STR;
1944 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
1947 conftype = CONF_CBK;
1953 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
1954 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
1958 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
1960 va_start(ap, block);
1961 while ((word = va_arg(ap, char *))) {
1962 type = va_arg(ap, int);
1965 str = va_arg(ap, char **);
1967 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
1970 cbk = va_arg(ap, void (*)(FILE *, char *, char *));
1973 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
1975 if (!strcasecmp(opt, word))
1982 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
1983 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
1986 if (type != conftype) {
1988 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
1989 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
1995 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
1997 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
1998 *str = stringcopy(val, 0);
2004 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2009 void confclsrv_cb(FILE *f, char *opt, char *val) {
2010 char *type = NULL, *secret = NULL, *port = NULL, *statusserver = NULL;
2012 struct client *client = NULL;
2013 struct server *server = NULL;
2016 block = malloc(strlen(opt) + strlen(val) + 2);
2018 debugx(1, DBG_ERR, "malloc failed");
2019 sprintf(block, "%s %s", opt, val);
2020 debug(DBG_DBG, "confclsrv_cb called for %s", block);
2022 if (!strcasecmp(opt, "client")) {
2023 getgeneralconfig(f, block,
2024 "type", CONF_STR, &type,
2025 "secret", CONF_STR, &secret,
2029 clients = realloc(clients, client_count * sizeof(struct client));
2031 debugx(1, DBG_ERR, "malloc failed");
2032 client = clients + client_count - 1;
2033 memset(client, 0, sizeof(struct client));
2034 peer = &client->peer;
2036 getgeneralconfig(f, block,
2037 "type", CONF_STR, &type,
2038 "secret", CONF_STR, &secret,
2039 "port", CONF_STR, &port,
2040 "StatusServer", CONF_STR, &statusserver,
2044 servers = realloc(servers, server_count * sizeof(struct server));
2046 debugx(1, DBG_ERR, "malloc failed");
2047 server = servers + server_count - 1;
2048 memset(server, 0, sizeof(struct server));
2049 peer = &server->peer;
2052 if (!strcasecmp(statusserver, "on"))
2053 server->statusserver = 1;
2054 else if (strcasecmp(statusserver, "off"))
2055 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2060 peer->host = stringcopy(val, 0);
2062 if (type && !strcasecmp(type, "udp")) {
2069 peer->port = stringcopy(DEFAULT_UDP_PORT, 0);
2071 } else if (type && !strcasecmp(type, "tls")) {
2078 peer->port = stringcopy(DEFAULT_TLS_PORT, 0);
2081 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2084 if (!resolvepeer(peer, 0))
2085 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
2088 if (peer->type == 'U')
2089 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2090 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2092 peer->secret = secret;
2096 if (peer->type == 'U')
2097 client->replyq = &udp_server_replyq;
2099 client->replyq = malloc(sizeof(struct replyq));
2100 if (!client->replyq)
2101 debugx(1, DBG_ERR, "malloc failed");
2102 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
2103 if (!client->replyq->replies)
2104 debugx(1, DBG_ERR, "malloc failed");
2105 client->replyq->size = MAX_REQUESTS;
2106 client->replyq->count = 0;
2107 pthread_mutex_init(&client->replyq->count_mutex, NULL);
2108 pthread_cond_init(&client->replyq->count_cond, NULL);
2111 pthread_mutex_init(&server->lock, NULL);
2113 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
2114 if (!server->requests)
2115 debugx(1, DBG_ERR, "malloc failed");
2117 pthread_mutex_init(&server->newrq_mutex, NULL);
2118 pthread_cond_init(&server->newrq_cond, NULL);
2124 void confrealm_cb(FILE *f, char *opt, char *val) {
2125 char *server = NULL, *msg = NULL;
2128 block = malloc(strlen(opt) + strlen(val) + 2);
2130 debugx(1, DBG_ERR, "malloc failed");
2131 sprintf(block, "%s %s", opt, val);
2132 debug(DBG_DBG, "confrealm_cb called for %s", block);
2134 getgeneralconfig(f, block,
2135 "server", CONF_STR, &server,
2136 "ReplyMessage", CONF_STR, &msg,
2140 addrealm(val, server, msg);
2145 void getmainconfig(const char *configfile) {
2147 char *loglevel = NULL;
2149 f = openconfigfile(configfile);
2150 memset(&options, 0, sizeof(options));
2152 getgeneralconfig(f, NULL,
2153 "TLSCACertificateFile", CONF_STR, &options.tlscacertificatefile,
2154 "TLSCACertificatePath", CONF_STR, &options.tlscacertificatepath,
2155 "TLSCertificateFile", CONF_STR, &options.tlscertificatefile,
2156 "TLSCertificateKeyFile", CONF_STR, &options.tlscertificatekeyfile,
2157 "TLSCertificateKeyPassword", CONF_STR, &options.tlscertificatekeypassword,
2158 "ListenUDP", CONF_STR, &options.listenudp,
2159 "ListenTCP", CONF_STR, &options.listentcp,
2160 "LogLevel", CONF_STR, &loglevel,
2161 "LogDestination", CONF_STR, &options.logdestination,
2162 "Client", CONF_CBK, confclsrv_cb,
2163 "Server", CONF_CBK, confclsrv_cb,
2164 "Realm", CONF_CBK, confrealm_cb,
2170 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2171 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2172 options.loglevel = *loglevel - '0';
2176 if (client_udp_count) {
2177 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
2178 if (!udp_server_replyq.replies)
2179 debugx(1, DBG_ERR, "malloc failed");
2180 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
2181 udp_server_replyq.count = 0;
2182 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
2183 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
2187 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2190 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2193 *configfile = optarg;
2196 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2197 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2198 *loglevel = *optarg - '0';
2204 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2209 if (!(argc - optind))
2213 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2217 int main(int argc, char **argv) {
2218 pthread_t udpserverth;
2220 uint8_t foreground = 0, loglevel = 0;
2221 char *configfile = NULL;
2223 debug_init("radsecproxy");
2224 debug_set_level(DEBUG_LEVEL);
2225 getargs(argc, argv, &foreground, &loglevel, &configfile);
2227 debug_set_level(loglevel);
2228 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2230 options.loglevel = loglevel;
2231 else if (options.loglevel)
2232 debug_set_level(options.loglevel);
2234 options.logdestination = NULL;
2236 if (!options.logdestination)
2237 options.logdestination = "x-syslog://";
2238 debug_set_destination(options.logdestination);
2242 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2244 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2246 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2248 if (!foreground && (daemon(0, 0) < 0))
2249 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2251 if (client_udp_count) {
2252 udp_server_listen = server_create('U');
2253 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2254 debugx(1, DBG_ERR, "pthread_create failed");
2257 if (client_tls_count || server_tls_count)
2258 ssl_ctx = ssl_init();
2260 for (i = 0; i < server_count; i++)
2261 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2262 debugx(1, DBG_ERR, "pthread_create failed");
2264 if (client_tls_count) {
2265 tcp_server_listen = server_create('T');
2266 return tlslistener();
2269 /* just hang around doing nothing, anything to do here? */