1 /*
2  * RADIUS client
3  * Copyright (c) 2002-2015, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 
11 #include "common.h"
12 #include "radius.h"
13 #include "radius_client.h"
14 #include "eloop.h"
15 
16 /* Defaults for RADIUS retransmit values (exponential backoff) */
17 
18 /**
19  * RADIUS_CLIENT_FIRST_WAIT - RADIUS client timeout for first retry in seconds
20  */
21 #define RADIUS_CLIENT_FIRST_WAIT 3
22 
23 /**
24  * RADIUS_CLIENT_MAX_WAIT - RADIUS client maximum retry timeout in seconds
25  */
26 #define RADIUS_CLIENT_MAX_WAIT 120
27 
28 /**
29  * RADIUS_CLIENT_MAX_FAILOVER - RADIUS client maximum retries
30  *
31  * Maximum number of server failovers before the entry is removed from
32  * retransmit list.
33  */
34 #define RADIUS_CLIENT_MAX_FAILOVER 3
35 
36 /**
37  * RADIUS_CLIENT_MAX_ENTRIES - RADIUS client maximum pending messages
38  *
39  * Maximum number of entries in retransmit list (oldest entries will be
40  * removed, if this limit is exceeded).
41  */
42 #define RADIUS_CLIENT_MAX_ENTRIES 30
43 
44 /**
45  * RADIUS_CLIENT_NUM_FAILOVER - RADIUS client failover point
46  *
47  * The number of failed retry attempts after which the RADIUS server will be
48  * changed (if one of more backup servers are configured).
49  */
50 #define RADIUS_CLIENT_NUM_FAILOVER 4
51 
52 
53 /**
54  * struct radius_rx_handler - RADIUS client RX handler
55  *
56  * This data structure is used internally inside the RADIUS client module to
57  * store registered RX handlers. These handlers are registered by calls to
58  * radius_client_register() and unregistered when the RADIUS client is
59  * deinitialized with a call to radius_client_deinit().
60  */
61 struct radius_rx_handler {
62 	/**
63 	 * handler - Received RADIUS message handler
64 	 */
65 	RadiusRxResult (*handler)(struct radius_msg *msg,
66 				  struct radius_msg *req,
67 				  const u8 *shared_secret,
68 				  size_t shared_secret_len,
69 				  void *data);
70 
71 	/**
72 	 * data - Context data for the handler
73 	 */
74 	void *data;
75 };
76 
77 
78 /**
79  * struct radius_msg_list - RADIUS client message retransmit list
80  *
81  * This data structure is used internally inside the RADIUS client module to
82  * store pending RADIUS requests that may still need to be retransmitted.
83  */
84 struct radius_msg_list {
85 	/**
86 	 * addr - STA/client address
87 	 *
88 	 * This is used to find RADIUS messages for the same STA.
89 	 */
90 	u8 addr[ETH_ALEN];
91 
92 	/**
93 	 * msg - RADIUS message
94 	 */
95 	struct radius_msg *msg;
96 
97 	/**
98 	 * msg_type - Message type
99 	 */
100 	RadiusType msg_type;
101 
102 	/**
103 	 * first_try - Time of the first transmission attempt
104 	 */
105 	os_time_t first_try;
106 
107 	/**
108 	 * next_try - Time for the next transmission attempt
109 	 */
110 	os_time_t next_try;
111 
112 	/**
113 	 * attempts - Number of transmission attempts for one server
114 	 */
115 	int attempts;
116 
117 	/**
118 	 * accu_attempts - Number of accumulated attempts
119 	 */
120 	int accu_attempts;
121 
122 	/**
123 	 * next_wait - Next retransmission wait time in seconds
124 	 */
125 	int next_wait;
126 
127 	/**
128 	 * last_attempt - Time of the last transmission attempt
129 	 */
130 	struct os_reltime last_attempt;
131 
132 	/**
133 	 * shared_secret - Shared secret with the target RADIUS server
134 	 */
135 	const u8 *shared_secret;
136 
137 	/**
138 	 * shared_secret_len - shared_secret length in octets
139 	 */
140 	size_t shared_secret_len;
141 
142 	/* TODO: server config with failover to backup server(s) */
143 
144 	/**
145 	 * next - Next message in the list
146 	 */
147 	struct radius_msg_list *next;
148 };
149 
150 
151 /**
152  * struct radius_client_data - Internal RADIUS client data
153  *
154  * This data structure is used internally inside the RADIUS client module.
155  * External users allocate this by calling radius_client_init() and free it by
156  * calling radius_client_deinit(). The pointer to this opaque data is used in
157  * calls to other functions as an identifier for the RADIUS client instance.
158  */
159 struct radius_client_data {
160 	/**
161 	 * ctx - Context pointer for hostapd_logger() callbacks
162 	 */
163 	void *ctx;
164 
165 	/**
166 	 * conf - RADIUS client configuration (list of RADIUS servers to use)
167 	 */
168 	struct hostapd_radius_servers *conf;
169 
170 	/**
171 	 * auth_serv_sock - IPv4 socket for RADIUS authentication messages
172 	 */
173 	int auth_serv_sock;
174 
175 	/**
176 	 * acct_serv_sock - IPv4 socket for RADIUS accounting messages
177 	 */
178 	int acct_serv_sock;
179 
180 	/**
181 	 * auth_serv_sock6 - IPv6 socket for RADIUS authentication messages
182 	 */
183 	int auth_serv_sock6;
184 
185 	/**
186 	 * acct_serv_sock6 - IPv6 socket for RADIUS accounting messages
187 	 */
188 	int acct_serv_sock6;
189 
190 	/**
191 	 * auth_sock - Currently used socket for RADIUS authentication server
192 	 */
193 	int auth_sock;
194 
195 	/**
196 	 * acct_sock - Currently used socket for RADIUS accounting server
197 	 */
198 	int acct_sock;
199 
200 	/**
201 	 * auth_handlers - Authentication message handlers
202 	 */
203 	struct radius_rx_handler *auth_handlers;
204 
205 	/**
206 	 * num_auth_handlers - Number of handlers in auth_handlers
207 	 */
208 	size_t num_auth_handlers;
209 
210 	/**
211 	 * acct_handlers - Accounting message handlers
212 	 */
213 	struct radius_rx_handler *acct_handlers;
214 
215 	/**
216 	 * num_acct_handlers - Number of handlers in acct_handlers
217 	 */
218 	size_t num_acct_handlers;
219 
220 	/**
221 	 * msgs - Pending outgoing RADIUS messages
222 	 */
223 	struct radius_msg_list *msgs;
224 
225 	/**
226 	 * num_msgs - Number of pending messages in the msgs list
227 	 */
228 	size_t num_msgs;
229 
230 	/**
231 	 * next_radius_identifier - Next RADIUS message identifier to use
232 	 */
233 	u8 next_radius_identifier;
234 
235 	/**
236 	 * interim_error_cb - Interim accounting error callback
237 	 */
238 	void (*interim_error_cb)(const u8 *addr, void *ctx);
239 
240 	/**
241 	 * interim_error_cb_ctx - interim_error_cb() context data
242 	 */
243 	void *interim_error_cb_ctx;
244 };
245 
246 
247 static int
248 radius_change_server(struct radius_client_data *radius,
249 		     struct hostapd_radius_server *nserv,
250 		     struct hostapd_radius_server *oserv,
251 		     int sock, int sock6, int auth);
252 static int radius_client_init_acct(struct radius_client_data *radius);
253 static int radius_client_init_auth(struct radius_client_data *radius);
254 static void radius_client_auth_failover(struct radius_client_data *radius);
255 static void radius_client_acct_failover(struct radius_client_data *radius);
256 
257 
radius_client_msg_free(struct radius_msg_list * req)258 static void radius_client_msg_free(struct radius_msg_list *req)
259 {
260 	radius_msg_free(req->msg);
261 	os_free(req);
262 }
263 
264 
265 /**
266  * radius_client_register - Register a RADIUS client RX handler
267  * @radius: RADIUS client context from radius_client_init()
268  * @msg_type: RADIUS client type (RADIUS_AUTH or RADIUS_ACCT)
269  * @handler: Handler for received RADIUS messages
270  * @data: Context pointer for handler callbacks
271  * Returns: 0 on success, -1 on failure
272  *
273  * This function is used to register a handler for processing received RADIUS
274  * authentication and accounting messages. The handler() callback function will
275  * be called whenever a RADIUS message is received from the active server.
276  *
277  * There can be multiple registered RADIUS message handlers. The handlers will
278  * be called in order until one of them indicates that it has processed or
279  * queued the message.
280  */
radius_client_register(struct radius_client_data * radius,RadiusType msg_type,RadiusRxResult (* handler)(struct radius_msg * msg,struct radius_msg * req,const u8 * shared_secret,size_t shared_secret_len,void * data),void * data)281 int radius_client_register(struct radius_client_data *radius,
282 			   RadiusType msg_type,
283 			   RadiusRxResult (*handler)(struct radius_msg *msg,
284 						     struct radius_msg *req,
285 						     const u8 *shared_secret,
286 						     size_t shared_secret_len,
287 						     void *data),
288 			   void *data)
289 {
290 	struct radius_rx_handler **handlers, *newh;
291 	size_t *num;
292 
293 	if (msg_type == RADIUS_ACCT) {
294 		handlers = &radius->acct_handlers;
295 		num = &radius->num_acct_handlers;
296 	} else {
297 		handlers = &radius->auth_handlers;
298 		num = &radius->num_auth_handlers;
299 	}
300 
301 	newh = os_realloc_array(*handlers, *num + 1,
302 				sizeof(struct radius_rx_handler));
303 	if (newh == NULL)
304 		return -1;
305 
306 	newh[*num].handler = handler;
307 	newh[*num].data = data;
308 	(*num)++;
309 	*handlers = newh;
310 
311 	return 0;
312 }
313 
314 
315 /**
316  * radius_client_set_interim_erro_cb - Register an interim acct error callback
317  * @radius: RADIUS client context from radius_client_init()
318  * @addr: Station address from the failed message
319  * @cb: Handler for interim accounting errors
320  * @ctx: Context pointer for handler callbacks
321  *
322  * This function is used to register a handler for processing failed
323  * transmission attempts of interim accounting update messages.
324  */
radius_client_set_interim_error_cb(struct radius_client_data * radius,void (* cb)(const u8 * addr,void * ctx),void * ctx)325 void radius_client_set_interim_error_cb(struct radius_client_data *radius,
326 					void (*cb)(const u8 *addr, void *ctx),
327 					void *ctx)
328 {
329 	radius->interim_error_cb = cb;
330 	radius->interim_error_cb_ctx = ctx;
331 }
332 
333 
334 /*
335  * Returns >0 if message queue was flushed (i.e., the message that triggered
336  * the error is not available anymore)
337  */
radius_client_handle_send_error(struct radius_client_data * radius,int s,RadiusType msg_type)338 static int radius_client_handle_send_error(struct radius_client_data *radius,
339 					   int s, RadiusType msg_type)
340 {
341 #ifndef CONFIG_NATIVE_WINDOWS
342 	int _errno = errno;
343 	wpa_printf(MSG_INFO, "send[RADIUS,s=%d]: %s", s, strerror(errno));
344 	if (_errno == ENOTCONN || _errno == EDESTADDRREQ || _errno == EINVAL ||
345 	    _errno == EBADF || _errno == ENETUNREACH || _errno == EACCES) {
346 		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
347 			       HOSTAPD_LEVEL_INFO,
348 			       "Send failed - maybe interface status changed -"
349 			       " try to connect again");
350 		if (msg_type == RADIUS_ACCT ||
351 		    msg_type == RADIUS_ACCT_INTERIM) {
352 			radius_client_init_acct(radius);
353 			return 0;
354 		} else {
355 			radius_client_init_auth(radius);
356 			return 1;
357 		}
358 	}
359 #endif /* CONFIG_NATIVE_WINDOWS */
360 
361 	return 0;
362 }
363 
364 
radius_client_retransmit(struct radius_client_data * radius,struct radius_msg_list * entry,os_time_t now)365 static int radius_client_retransmit(struct radius_client_data *radius,
366 				    struct radius_msg_list *entry,
367 				    os_time_t now)
368 {
369 	struct hostapd_radius_servers *conf = radius->conf;
370 	int s;
371 	struct wpabuf *buf;
372 	size_t prev_num_msgs;
373 	u8 *acct_delay_time;
374 	size_t acct_delay_time_len;
375 	int num_servers;
376 
377 	if (entry->msg_type == RADIUS_ACCT ||
378 	    entry->msg_type == RADIUS_ACCT_INTERIM) {
379 		num_servers = conf->num_acct_servers;
380 		if (radius->acct_sock < 0)
381 			radius_client_init_acct(radius);
382 		if (radius->acct_sock < 0 && conf->num_acct_servers > 1) {
383 			prev_num_msgs = radius->num_msgs;
384 			radius_client_acct_failover(radius);
385 			if (prev_num_msgs != radius->num_msgs)
386 				return 0;
387 		}
388 		s = radius->acct_sock;
389 		if (entry->attempts == 0)
390 			conf->acct_server->requests++;
391 		else {
392 			conf->acct_server->timeouts++;
393 			conf->acct_server->retransmissions++;
394 		}
395 	} else {
396 		num_servers = conf->num_auth_servers;
397 		if (radius->auth_sock < 0)
398 			radius_client_init_auth(radius);
399 		if (radius->auth_sock < 0 && conf->num_auth_servers > 1) {
400 			prev_num_msgs = radius->num_msgs;
401 			radius_client_auth_failover(radius);
402 			if (prev_num_msgs != radius->num_msgs)
403 				return 0;
404 		}
405 		s = radius->auth_sock;
406 		if (entry->attempts == 0)
407 			conf->auth_server->requests++;
408 		else {
409 			conf->auth_server->timeouts++;
410 			conf->auth_server->retransmissions++;
411 		}
412 	}
413 
414 	if (entry->msg_type == RADIUS_ACCT_INTERIM) {
415 		wpa_printf(MSG_DEBUG,
416 			   "RADIUS: Failed to transmit interim accounting update to "
417 			   MACSTR " - drop message and request a new update",
418 			   MAC2STR(entry->addr));
419 		if (radius->interim_error_cb)
420 			radius->interim_error_cb(entry->addr,
421 						 radius->interim_error_cb_ctx);
422 		return 1;
423 	}
424 
425 	if (s < 0) {
426 		wpa_printf(MSG_INFO,
427 			   "RADIUS: No valid socket for retransmission");
428 		return 1;
429 	}
430 
431 	if (entry->msg_type == RADIUS_ACCT &&
432 	    radius_msg_get_attr_ptr(entry->msg, RADIUS_ATTR_ACCT_DELAY_TIME,
433 				    &acct_delay_time, &acct_delay_time_len,
434 				    NULL) == 0 &&
435 	    acct_delay_time_len == 4) {
436 		struct radius_hdr *hdr;
437 		u32 delay_time;
438 
439 		/*
440 		 * Need to assign a new identifier since attribute contents
441 		 * changes.
442 		 */
443 		hdr = radius_msg_get_hdr(entry->msg);
444 		hdr->identifier = radius_client_get_id(radius);
445 
446 		/* Update Acct-Delay-Time to show wait time in queue */
447 		delay_time = now - entry->first_try;
448 		WPA_PUT_BE32(acct_delay_time, delay_time);
449 
450 		wpa_printf(MSG_DEBUG,
451 			   "RADIUS: Updated Acct-Delay-Time to %u for retransmission",
452 			   delay_time);
453 		radius_msg_finish_acct(entry->msg, entry->shared_secret,
454 				       entry->shared_secret_len);
455 		if (radius->conf->msg_dumps)
456 			radius_msg_dump(entry->msg);
457 	}
458 
459 	/* retransmit; remove entry if too many attempts */
460 	if (entry->accu_attempts > RADIUS_CLIENT_MAX_FAILOVER *
461 	    RADIUS_CLIENT_NUM_FAILOVER * num_servers) {
462 		wpa_printf(MSG_INFO,
463 			   "RADIUS: Removing un-ACKed message due to too many failed retransmit attempts");
464 		return 1;
465 	}
466 
467 	entry->attempts++;
468 	entry->accu_attempts++;
469 	hostapd_logger(radius->ctx, entry->addr, HOSTAPD_MODULE_RADIUS,
470 		       HOSTAPD_LEVEL_DEBUG, "Resending RADIUS message (id=%d)",
471 		       radius_msg_get_hdr(entry->msg)->identifier);
472 
473 	os_get_reltime(&entry->last_attempt);
474 	buf = radius_msg_get_buf(entry->msg);
475 	if (send(s, wpabuf_head(buf), wpabuf_len(buf), 0) < 0) {
476 		if (radius_client_handle_send_error(radius, s, entry->msg_type)
477 		    > 0)
478 			return 0;
479 	}
480 
481 	entry->next_try = now + entry->next_wait;
482 	entry->next_wait *= 2;
483 	if (entry->next_wait > RADIUS_CLIENT_MAX_WAIT)
484 		entry->next_wait = RADIUS_CLIENT_MAX_WAIT;
485 
486 	return 0;
487 }
488 
489 
radius_client_timer(void * eloop_ctx,void * timeout_ctx)490 static void radius_client_timer(void *eloop_ctx, void *timeout_ctx)
491 {
492 	struct radius_client_data *radius = eloop_ctx;
493 	struct os_reltime now;
494 	os_time_t first;
495 	struct radius_msg_list *entry, *prev, *tmp;
496 	int auth_failover = 0, acct_failover = 0;
497 	size_t prev_num_msgs;
498 	int s;
499 
500 	entry = radius->msgs;
501 	if (!entry)
502 		return;
503 
504 	os_get_reltime(&now);
505 
506 	while (entry) {
507 		if (now.sec >= entry->next_try) {
508 			s = entry->msg_type == RADIUS_AUTH ? radius->auth_sock :
509 				radius->acct_sock;
510 			if (entry->attempts > RADIUS_CLIENT_NUM_FAILOVER ||
511 			    (s < 0 && entry->attempts > 0)) {
512 				if (entry->msg_type == RADIUS_ACCT ||
513 				    entry->msg_type == RADIUS_ACCT_INTERIM)
514 					acct_failover++;
515 				else
516 					auth_failover++;
517 			}
518 		}
519 		entry = entry->next;
520 	}
521 
522 	if (auth_failover)
523 		radius_client_auth_failover(radius);
524 
525 	if (acct_failover)
526 		radius_client_acct_failover(radius);
527 
528 	entry = radius->msgs;
529 	first = 0;
530 
531 	prev = NULL;
532 	while (entry) {
533 		prev_num_msgs = radius->num_msgs;
534 		if (now.sec >= entry->next_try &&
535 		    radius_client_retransmit(radius, entry, now.sec)) {
536 			if (prev)
537 				prev->next = entry->next;
538 			else
539 				radius->msgs = entry->next;
540 
541 			tmp = entry;
542 			entry = entry->next;
543 			radius_client_msg_free(tmp);
544 			radius->num_msgs--;
545 			continue;
546 		}
547 
548 		if (prev_num_msgs != radius->num_msgs) {
549 			wpa_printf(MSG_DEBUG,
550 				   "RADIUS: Message removed from queue - restart from beginning");
551 			entry = radius->msgs;
552 			prev = NULL;
553 			continue;
554 		}
555 
556 		if (first == 0 || entry->next_try < first)
557 			first = entry->next_try;
558 
559 		prev = entry;
560 		entry = entry->next;
561 	}
562 
563 	if (radius->msgs) {
564 		if (first < now.sec)
565 			first = now.sec;
566 		eloop_cancel_timeout(radius_client_timer, radius, NULL);
567 		eloop_register_timeout(first - now.sec, 0,
568 				       radius_client_timer, radius, NULL);
569 		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
570 			       HOSTAPD_LEVEL_DEBUG, "Next RADIUS client "
571 			       "retransmit in %ld seconds",
572 			       (long int) (first - now.sec));
573 	}
574 }
575 
576 
radius_client_auth_failover(struct radius_client_data * radius)577 static void radius_client_auth_failover(struct radius_client_data *radius)
578 {
579 	struct hostapd_radius_servers *conf = radius->conf;
580 	struct hostapd_radius_server *next, *old;
581 	struct radius_msg_list *entry;
582 	char abuf[50];
583 
584 	old = conf->auth_server;
585 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
586 		       HOSTAPD_LEVEL_NOTICE,
587 		       "No response from Authentication server %s:%d - failover",
588 		       hostapd_ip_txt(&old->addr, abuf, sizeof(abuf)),
589 		       old->port);
590 
591 	for (entry = radius->msgs; entry; entry = entry->next) {
592 		if (entry->msg_type == RADIUS_AUTH)
593 			old->timeouts++;
594 	}
595 
596 	next = old + 1;
597 	if (next > &(conf->auth_servers[conf->num_auth_servers - 1]))
598 		next = conf->auth_servers;
599 	conf->auth_server = next;
600 	radius_change_server(radius, next, old,
601 			     radius->auth_serv_sock,
602 			     radius->auth_serv_sock6, 1);
603 }
604 
605 
radius_client_acct_failover(struct radius_client_data * radius)606 static void radius_client_acct_failover(struct radius_client_data *radius)
607 {
608 	struct hostapd_radius_servers *conf = radius->conf;
609 	struct hostapd_radius_server *next, *old;
610 	struct radius_msg_list *entry;
611 	char abuf[50];
612 
613 	old = conf->acct_server;
614 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
615 		       HOSTAPD_LEVEL_NOTICE,
616 		       "No response from Accounting server %s:%d - failover",
617 		       hostapd_ip_txt(&old->addr, abuf, sizeof(abuf)),
618 		       old->port);
619 
620 	for (entry = radius->msgs; entry; entry = entry->next) {
621 		if (entry->msg_type == RADIUS_ACCT ||
622 		    entry->msg_type == RADIUS_ACCT_INTERIM)
623 			old->timeouts++;
624 	}
625 
626 	next = old + 1;
627 	if (next > &conf->acct_servers[conf->num_acct_servers - 1])
628 		next = conf->acct_servers;
629 	conf->acct_server = next;
630 	radius_change_server(radius, next, old,
631 			     radius->acct_serv_sock,
632 			     radius->acct_serv_sock6, 0);
633 }
634 
635 
radius_client_update_timeout(struct radius_client_data * radius)636 static void radius_client_update_timeout(struct radius_client_data *radius)
637 {
638 	struct os_reltime now;
639 	os_time_t first;
640 	struct radius_msg_list *entry;
641 
642 	eloop_cancel_timeout(radius_client_timer, radius, NULL);
643 
644 	if (radius->msgs == NULL) {
645 		return;
646 	}
647 
648 	first = 0;
649 	for (entry = radius->msgs; entry; entry = entry->next) {
650 		if (first == 0 || entry->next_try < first)
651 			first = entry->next_try;
652 	}
653 
654 	os_get_reltime(&now);
655 	if (first < now.sec)
656 		first = now.sec;
657 	eloop_register_timeout(first - now.sec, 0, radius_client_timer, radius,
658 			       NULL);
659 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
660 		       HOSTAPD_LEVEL_DEBUG, "Next RADIUS client retransmit in"
661 		       " %ld seconds", (long int) (first - now.sec));
662 }
663 
664 
radius_client_list_add(struct radius_client_data * radius,struct radius_msg * msg,RadiusType msg_type,const u8 * shared_secret,size_t shared_secret_len,const u8 * addr)665 static void radius_client_list_add(struct radius_client_data *radius,
666 				   struct radius_msg *msg,
667 				   RadiusType msg_type,
668 				   const u8 *shared_secret,
669 				   size_t shared_secret_len, const u8 *addr)
670 {
671 	struct radius_msg_list *entry, *prev;
672 
673 	if (eloop_terminated()) {
674 		/* No point in adding entries to retransmit queue since event
675 		 * loop has already been terminated. */
676 		radius_msg_free(msg);
677 		return;
678 	}
679 
680 	entry = os_zalloc(sizeof(*entry));
681 	if (entry == NULL) {
682 		wpa_printf(MSG_INFO, "RADIUS: Failed to add packet into retransmit list");
683 		radius_msg_free(msg);
684 		return;
685 	}
686 
687 	if (addr)
688 		os_memcpy(entry->addr, addr, ETH_ALEN);
689 	entry->msg = msg;
690 	entry->msg_type = msg_type;
691 	entry->shared_secret = shared_secret;
692 	entry->shared_secret_len = shared_secret_len;
693 	os_get_reltime(&entry->last_attempt);
694 	entry->first_try = entry->last_attempt.sec;
695 	entry->next_try = entry->first_try + RADIUS_CLIENT_FIRST_WAIT;
696 	entry->attempts = 1;
697 	entry->accu_attempts = 1;
698 	entry->next_wait = RADIUS_CLIENT_FIRST_WAIT * 2;
699 	if (entry->next_wait > RADIUS_CLIENT_MAX_WAIT)
700 		entry->next_wait = RADIUS_CLIENT_MAX_WAIT;
701 	entry->next = radius->msgs;
702 	radius->msgs = entry;
703 	radius_client_update_timeout(radius);
704 
705 	if (radius->num_msgs >= RADIUS_CLIENT_MAX_ENTRIES) {
706 		wpa_printf(MSG_INFO, "RADIUS: Removing the oldest un-ACKed packet due to retransmit list limits");
707 		prev = NULL;
708 		while (entry->next) {
709 			prev = entry;
710 			entry = entry->next;
711 		}
712 		if (prev) {
713 			prev->next = NULL;
714 			radius_client_msg_free(entry);
715 		}
716 	} else
717 		radius->num_msgs++;
718 }
719 
720 
721 /**
722  * radius_client_send - Send a RADIUS request
723  * @radius: RADIUS client context from radius_client_init()
724  * @msg: RADIUS message to be sent
725  * @msg_type: Message type (RADIUS_AUTH, RADIUS_ACCT, RADIUS_ACCT_INTERIM)
726  * @addr: MAC address of the device related to this message or %NULL
727  * Returns: 0 on success, -1 on failure
728  *
729  * This function is used to transmit a RADIUS authentication (RADIUS_AUTH) or
730  * accounting request (RADIUS_ACCT or RADIUS_ACCT_INTERIM). The only difference
731  * between accounting and interim accounting messages is that the interim
732  * message will not be retransmitted. Instead, a callback is used to indicate
733  * that the transmission failed for the specific station @addr so that a new
734  * interim accounting update message can be generated with up-to-date session
735  * data instead of trying to resend old information.
736  *
737  * The message is added on the retransmission queue and will be retransmitted
738  * automatically until a response is received or maximum number of retries
739  * (RADIUS_CLIENT_MAX_FAILOVER * RADIUS_CLIENT_NUM_FAILOVER) is reached. No
740  * such retries are used with RADIUS_ACCT_INTERIM, i.e., such a pending message
741  * is removed from the queue automatically on transmission failure.
742  *
743  * The related device MAC address can be used to identify pending messages that
744  * can be removed with radius_client_flush_auth().
745  */
radius_client_send(struct radius_client_data * radius,struct radius_msg * msg,RadiusType msg_type,const u8 * addr)746 int radius_client_send(struct radius_client_data *radius,
747 		       struct radius_msg *msg, RadiusType msg_type,
748 		       const u8 *addr)
749 {
750 	struct hostapd_radius_servers *conf = radius->conf;
751 	const u8 *shared_secret;
752 	size_t shared_secret_len;
753 	char *name;
754 	int s, res;
755 	struct wpabuf *buf;
756 
757 	if (msg_type == RADIUS_ACCT || msg_type == RADIUS_ACCT_INTERIM) {
758 		if (conf->acct_server && radius->acct_sock < 0)
759 			radius_client_init_acct(radius);
760 
761 		if (conf->acct_server == NULL || radius->acct_sock < 0 ||
762 		    conf->acct_server->shared_secret == NULL) {
763 			hostapd_logger(radius->ctx, NULL,
764 				       HOSTAPD_MODULE_RADIUS,
765 				       HOSTAPD_LEVEL_INFO,
766 				       "No accounting server configured");
767 			return -1;
768 		}
769 		shared_secret = conf->acct_server->shared_secret;
770 		shared_secret_len = conf->acct_server->shared_secret_len;
771 		radius_msg_finish_acct(msg, shared_secret, shared_secret_len);
772 		name = "accounting";
773 		s = radius->acct_sock;
774 		conf->acct_server->requests++;
775 	} else {
776 		if (conf->auth_server && radius->auth_sock < 0)
777 			radius_client_init_auth(radius);
778 
779 		if (conf->auth_server == NULL || radius->auth_sock < 0 ||
780 		    conf->auth_server->shared_secret == NULL) {
781 			hostapd_logger(radius->ctx, NULL,
782 				       HOSTAPD_MODULE_RADIUS,
783 				       HOSTAPD_LEVEL_INFO,
784 				       "No authentication server configured");
785 			return -1;
786 		}
787 		shared_secret = conf->auth_server->shared_secret;
788 		shared_secret_len = conf->auth_server->shared_secret_len;
789 		radius_msg_finish(msg, shared_secret, shared_secret_len);
790 		name = "authentication";
791 		s = radius->auth_sock;
792 		conf->auth_server->requests++;
793 	}
794 
795 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
796 		       HOSTAPD_LEVEL_DEBUG, "Sending RADIUS message to %s "
797 		       "server", name);
798 	if (conf->msg_dumps)
799 		radius_msg_dump(msg);
800 
801 	buf = radius_msg_get_buf(msg);
802 	res = send(s, wpabuf_head(buf), wpabuf_len(buf), 0);
803 	if (res < 0)
804 		radius_client_handle_send_error(radius, s, msg_type);
805 
806 	radius_client_list_add(radius, msg, msg_type, shared_secret,
807 			       shared_secret_len, addr);
808 
809 	return 0;
810 }
811 
812 
radius_client_receive(int sock,void * eloop_ctx,void * sock_ctx)813 static void radius_client_receive(int sock, void *eloop_ctx, void *sock_ctx)
814 {
815 	struct radius_client_data *radius = eloop_ctx;
816 	struct hostapd_radius_servers *conf = radius->conf;
817 #if defined(__clang_major__) && __clang_major__ >= 11
818 #pragma GCC diagnostic ignored "-Wvoid-pointer-to-enum-cast"
819 #endif
820 	RadiusType msg_type = (RadiusType) sock_ctx;
821 	int len, roundtrip;
822 	unsigned char buf[3000];
823 	struct radius_msg *msg;
824 	struct radius_hdr *hdr;
825 	struct radius_rx_handler *handlers;
826 	size_t num_handlers, i;
827 	struct radius_msg_list *req, *prev_req;
828 	struct os_reltime now;
829 	struct hostapd_radius_server *rconf;
830 	int invalid_authenticator = 0;
831 
832 	if (msg_type == RADIUS_ACCT) {
833 		handlers = radius->acct_handlers;
834 		num_handlers = radius->num_acct_handlers;
835 		rconf = conf->acct_server;
836 	} else {
837 		handlers = radius->auth_handlers;
838 		num_handlers = radius->num_auth_handlers;
839 		rconf = conf->auth_server;
840 	}
841 
842 	len = recv(sock, buf, sizeof(buf), MSG_DONTWAIT);
843 	if (len < 0) {
844 		wpa_printf(MSG_INFO, "recv[RADIUS]: %s", strerror(errno));
845 		return;
846 	}
847 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
848 		       HOSTAPD_LEVEL_DEBUG, "Received %d bytes from RADIUS "
849 		       "server", len);
850 	if (len == sizeof(buf)) {
851 		wpa_printf(MSG_INFO, "RADIUS: Possibly too long UDP frame for our buffer - dropping it");
852 		return;
853 	}
854 
855 	msg = radius_msg_parse(buf, len);
856 	if (msg == NULL) {
857 		wpa_printf(MSG_INFO, "RADIUS: Parsing incoming frame failed");
858 		rconf->malformed_responses++;
859 		return;
860 	}
861 	hdr = radius_msg_get_hdr(msg);
862 
863 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
864 		       HOSTAPD_LEVEL_DEBUG, "Received RADIUS message");
865 	if (conf->msg_dumps)
866 		radius_msg_dump(msg);
867 
868 	switch (hdr->code) {
869 	case RADIUS_CODE_ACCESS_ACCEPT:
870 		rconf->access_accepts++;
871 		break;
872 	case RADIUS_CODE_ACCESS_REJECT:
873 		rconf->access_rejects++;
874 		break;
875 	case RADIUS_CODE_ACCESS_CHALLENGE:
876 		rconf->access_challenges++;
877 		break;
878 	case RADIUS_CODE_ACCOUNTING_RESPONSE:
879 		rconf->responses++;
880 		break;
881 	}
882 
883 	prev_req = NULL;
884 	req = radius->msgs;
885 	while (req) {
886 		/* TODO: also match by src addr:port of the packet when using
887 		 * alternative RADIUS servers (?) */
888 		if ((req->msg_type == msg_type ||
889 		     (req->msg_type == RADIUS_ACCT_INTERIM &&
890 		      msg_type == RADIUS_ACCT)) &&
891 		    radius_msg_get_hdr(req->msg)->identifier ==
892 		    hdr->identifier)
893 			break;
894 
895 		prev_req = req;
896 		req = req->next;
897 	}
898 
899 	if (req == NULL) {
900 		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
901 			       HOSTAPD_LEVEL_DEBUG,
902 			       "No matching RADIUS request found (type=%d "
903 			       "id=%d) - dropping packet",
904 			       msg_type, hdr->identifier);
905 		goto fail;
906 	}
907 
908 	os_get_reltime(&now);
909 	roundtrip = (now.sec - req->last_attempt.sec) * 100 +
910 		(now.usec - req->last_attempt.usec) / 10000;
911 	hostapd_logger(radius->ctx, req->addr, HOSTAPD_MODULE_RADIUS,
912 		       HOSTAPD_LEVEL_DEBUG,
913 		       "Received RADIUS packet matched with a pending "
914 		       "request, round trip time %d.%02d sec",
915 		       roundtrip / 100, roundtrip % 100);
916 	rconf->round_trip_time = roundtrip;
917 
918 	/* Remove ACKed RADIUS packet from retransmit list */
919 	if (prev_req)
920 		prev_req->next = req->next;
921 	else
922 		radius->msgs = req->next;
923 	radius->num_msgs--;
924 
925 	for (i = 0; i < num_handlers; i++) {
926 		RadiusRxResult res;
927 		res = handlers[i].handler(msg, req->msg, req->shared_secret,
928 					  req->shared_secret_len,
929 					  handlers[i].data);
930 		switch (res) {
931 		case RADIUS_RX_PROCESSED:
932 			radius_msg_free(msg);
933 			/* fall through */
934 		case RADIUS_RX_QUEUED:
935 			radius_client_msg_free(req);
936 			return;
937 		case RADIUS_RX_INVALID_AUTHENTICATOR:
938 			invalid_authenticator++;
939 			/* fall through */
940 		case RADIUS_RX_UNKNOWN:
941 			/* continue with next handler */
942 			break;
943 		}
944 	}
945 
946 	if (invalid_authenticator)
947 		rconf->bad_authenticators++;
948 	else
949 		rconf->unknown_types++;
950 	hostapd_logger(radius->ctx, req->addr, HOSTAPD_MODULE_RADIUS,
951 		       HOSTAPD_LEVEL_DEBUG, "No RADIUS RX handler found "
952 		       "(type=%d code=%d id=%d)%s - dropping packet",
953 		       msg_type, hdr->code, hdr->identifier,
954 		       invalid_authenticator ? " [INVALID AUTHENTICATOR]" :
955 		       "");
956 	radius_client_msg_free(req);
957 
958  fail:
959 	radius_msg_free(msg);
960 }
961 
962 
963 /**
964  * radius_client_get_id - Get an identifier for a new RADIUS message
965  * @radius: RADIUS client context from radius_client_init()
966  * Returns: Allocated identifier
967  *
968  * This function is used to fetch a unique (among pending requests) identifier
969  * for a new RADIUS message.
970  */
radius_client_get_id(struct radius_client_data * radius)971 u8 radius_client_get_id(struct radius_client_data *radius)
972 {
973 	struct radius_msg_list *entry, *prev, *_remove;
974 	u8 id = radius->next_radius_identifier++;
975 
976 	/* remove entries with matching id from retransmit list to avoid
977 	 * using new reply from the RADIUS server with an old request */
978 	entry = radius->msgs;
979 	prev = NULL;
980 	while (entry) {
981 		if (radius_msg_get_hdr(entry->msg)->identifier == id) {
982 			hostapd_logger(radius->ctx, entry->addr,
983 				       HOSTAPD_MODULE_RADIUS,
984 				       HOSTAPD_LEVEL_DEBUG,
985 				       "Removing pending RADIUS message, "
986 				       "since its id (%d) is reused", id);
987 			if (prev)
988 				prev->next = entry->next;
989 			else
990 				radius->msgs = entry->next;
991 			_remove = entry;
992 		} else {
993 			_remove = NULL;
994 			prev = entry;
995 		}
996 		entry = entry->next;
997 
998 		if (_remove)
999 			radius_client_msg_free(_remove);
1000 	}
1001 
1002 	return id;
1003 }
1004 
1005 
1006 /**
1007  * radius_client_flush - Flush all pending RADIUS client messages
1008  * @radius: RADIUS client context from radius_client_init()
1009  * @only_auth: Whether only authentication messages are removed
1010  */
radius_client_flush(struct radius_client_data * radius,int only_auth)1011 void radius_client_flush(struct radius_client_data *radius, int only_auth)
1012 {
1013 	struct radius_msg_list *entry, *prev, *tmp;
1014 
1015 	if (!radius)
1016 		return;
1017 
1018 	prev = NULL;
1019 	entry = radius->msgs;
1020 
1021 	while (entry) {
1022 		if (!only_auth || entry->msg_type == RADIUS_AUTH) {
1023 			if (prev)
1024 				prev->next = entry->next;
1025 			else
1026 				radius->msgs = entry->next;
1027 
1028 			tmp = entry;
1029 			entry = entry->next;
1030 			radius_client_msg_free(tmp);
1031 			radius->num_msgs--;
1032 		} else {
1033 			prev = entry;
1034 			entry = entry->next;
1035 		}
1036 	}
1037 
1038 	if (radius->msgs == NULL)
1039 		eloop_cancel_timeout(radius_client_timer, radius, NULL);
1040 }
1041 
1042 
radius_client_update_acct_msgs(struct radius_client_data * radius,const u8 * shared_secret,size_t shared_secret_len)1043 static void radius_client_update_acct_msgs(struct radius_client_data *radius,
1044 					   const u8 *shared_secret,
1045 					   size_t shared_secret_len)
1046 {
1047 	struct radius_msg_list *entry;
1048 
1049 	if (!radius)
1050 		return;
1051 
1052 	for (entry = radius->msgs; entry; entry = entry->next) {
1053 		if (entry->msg_type == RADIUS_ACCT) {
1054 			entry->shared_secret = shared_secret;
1055 			entry->shared_secret_len = shared_secret_len;
1056 			radius_msg_finish_acct(entry->msg, shared_secret,
1057 					       shared_secret_len);
1058 		}
1059 	}
1060 }
1061 
1062 
1063 static int
radius_change_server(struct radius_client_data * radius,struct hostapd_radius_server * nserv,struct hostapd_radius_server * oserv,int sock,int sock6,int auth)1064 radius_change_server(struct radius_client_data *radius,
1065 		     struct hostapd_radius_server *nserv,
1066 		     struct hostapd_radius_server *oserv,
1067 		     int sock, int sock6, int auth)
1068 {
1069 	struct sockaddr_in serv, claddr;
1070 #ifdef CONFIG_IPV6
1071 	struct sockaddr_in6 serv6, claddr6;
1072 #endif /* CONFIG_IPV6 */
1073 	struct sockaddr *addr, *cl_addr;
1074 	socklen_t addrlen, claddrlen;
1075 	char abuf[50];
1076 	int sel_sock;
1077 	struct radius_msg_list *entry;
1078 	struct hostapd_radius_servers *conf = radius->conf;
1079 	struct sockaddr_in disconnect_addr = {
1080 		.sin_family = AF_UNSPEC,
1081 	};
1082 
1083 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
1084 		       HOSTAPD_LEVEL_INFO,
1085 		       "%s server %s:%d",
1086 		       auth ? "Authentication" : "Accounting",
1087 		       hostapd_ip_txt(&nserv->addr, abuf, sizeof(abuf)),
1088 		       nserv->port);
1089 
1090 	if (oserv && oserv == nserv) {
1091 		/* Reconnect to same server, flush */
1092 		if (auth)
1093 			radius_client_flush(radius, 1);
1094 	}
1095 
1096 	if (oserv && oserv != nserv &&
1097 	    (nserv->shared_secret_len != oserv->shared_secret_len ||
1098 	     os_memcmp(nserv->shared_secret, oserv->shared_secret,
1099 		       nserv->shared_secret_len) != 0)) {
1100 		/* Pending RADIUS packets used different shared secret, so
1101 		 * they need to be modified. Update accounting message
1102 		 * authenticators here. Authentication messages are removed
1103 		 * since they would require more changes and the new RADIUS
1104 		 * server may not be prepared to receive them anyway due to
1105 		 * missing state information. Client will likely retry
1106 		 * authentication, so this should not be an issue. */
1107 		if (auth)
1108 			radius_client_flush(radius, 1);
1109 		else {
1110 			radius_client_update_acct_msgs(
1111 				radius, nserv->shared_secret,
1112 				nserv->shared_secret_len);
1113 		}
1114 	}
1115 
1116 	/* Reset retry counters */
1117 	for (entry = radius->msgs; oserv && entry; entry = entry->next) {
1118 		if ((auth && entry->msg_type != RADIUS_AUTH) ||
1119 		    (!auth && entry->msg_type != RADIUS_ACCT))
1120 			continue;
1121 		entry->next_try = entry->first_try + RADIUS_CLIENT_FIRST_WAIT;
1122 		entry->attempts = 1;
1123 		entry->next_wait = RADIUS_CLIENT_FIRST_WAIT * 2;
1124 	}
1125 
1126 	if (radius->msgs) {
1127 		eloop_cancel_timeout(radius_client_timer, radius, NULL);
1128 		eloop_register_timeout(RADIUS_CLIENT_FIRST_WAIT, 0,
1129 				       radius_client_timer, radius, NULL);
1130 	}
1131 
1132 	switch (nserv->addr.af) {
1133 	case AF_INET:
1134 		os_memset(&serv, 0, sizeof(serv));
1135 		serv.sin_family = AF_INET;
1136 		serv.sin_addr.s_addr = nserv->addr.u.v4.s_addr;
1137 		serv.sin_port = htons(nserv->port);
1138 		addr = (struct sockaddr *) &serv;
1139 		addrlen = sizeof(serv);
1140 		sel_sock = sock;
1141 		break;
1142 #ifdef CONFIG_IPV6
1143 	case AF_INET6:
1144 		os_memset(&serv6, 0, sizeof(serv6));
1145 		serv6.sin6_family = AF_INET6;
1146 		os_memcpy(&serv6.sin6_addr, &nserv->addr.u.v6,
1147 			  sizeof(struct in6_addr));
1148 		serv6.sin6_port = htons(nserv->port);
1149 		addr = (struct sockaddr *) &serv6;
1150 		addrlen = sizeof(serv6);
1151 		sel_sock = sock6;
1152 		break;
1153 #endif /* CONFIG_IPV6 */
1154 	default:
1155 		return -1;
1156 	}
1157 
1158 	if (sel_sock < 0) {
1159 		wpa_printf(MSG_INFO,
1160 			   "RADIUS: No server socket available (af=%d sock=%d sock6=%d auth=%d",
1161 			   nserv->addr.af, sock, sock6, auth);
1162 		return -1;
1163 	}
1164 
1165 	if (conf->force_client_addr) {
1166 		switch (conf->client_addr.af) {
1167 		case AF_INET:
1168 			os_memset(&claddr, 0, sizeof(claddr));
1169 			claddr.sin_family = AF_INET;
1170 			claddr.sin_addr.s_addr = conf->client_addr.u.v4.s_addr;
1171 			claddr.sin_port = htons(0);
1172 			cl_addr = (struct sockaddr *) &claddr;
1173 			claddrlen = sizeof(claddr);
1174 			break;
1175 #ifdef CONFIG_IPV6
1176 		case AF_INET6:
1177 			os_memset(&claddr6, 0, sizeof(claddr6));
1178 			claddr6.sin6_family = AF_INET6;
1179 			os_memcpy(&claddr6.sin6_addr, &conf->client_addr.u.v6,
1180 				  sizeof(struct in6_addr));
1181 			claddr6.sin6_port = htons(0);
1182 			cl_addr = (struct sockaddr *) &claddr6;
1183 			claddrlen = sizeof(claddr6);
1184 			break;
1185 #endif /* CONFIG_IPV6 */
1186 		default:
1187 			return -1;
1188 		}
1189 
1190 		if (bind(sel_sock, cl_addr, claddrlen) < 0) {
1191 			wpa_printf(MSG_INFO, "bind[radius]: %s",
1192 				   strerror(errno));
1193 			return -1;
1194 		}
1195 	}
1196 
1197 	/* Force a reconnect by disconnecting the socket first */
1198 	if (connect(sel_sock, (struct sockaddr *) &disconnect_addr,
1199 		    sizeof(disconnect_addr)) < 0)
1200 		wpa_printf(MSG_INFO, "disconnect[radius]: %s", strerror(errno));
1201 
1202 	if (connect(sel_sock, addr, addrlen) < 0) {
1203 		wpa_printf(MSG_INFO, "connect[radius]: %s", strerror(errno));
1204 		return -1;
1205 	}
1206 
1207 #ifndef CONFIG_NATIVE_WINDOWS
1208 	switch (nserv->addr.af) {
1209 	case AF_INET:
1210 		claddrlen = sizeof(claddr);
1211 		if (getsockname(sel_sock, (struct sockaddr *) &claddr,
1212 				&claddrlen) == 0) {
1213 			wpa_printf(MSG_DEBUG, "RADIUS local address: %s:%u",
1214 				   inet_ntoa(claddr.sin_addr),
1215 				   ntohs(claddr.sin_port));
1216 		}
1217 		break;
1218 #ifdef CONFIG_IPV6
1219 	case AF_INET6: {
1220 		claddrlen = sizeof(claddr6);
1221 		if (getsockname(sel_sock, (struct sockaddr *) &claddr6,
1222 				&claddrlen) == 0) {
1223 			wpa_printf(MSG_DEBUG, "RADIUS local address: %s:%u",
1224 				   inet_ntop(AF_INET6, &claddr6.sin6_addr,
1225 					     abuf, sizeof(abuf)),
1226 				   ntohs(claddr6.sin6_port));
1227 		}
1228 		break;
1229 	}
1230 #endif /* CONFIG_IPV6 */
1231 	}
1232 #endif /* CONFIG_NATIVE_WINDOWS */
1233 
1234 	if (auth)
1235 		radius->auth_sock = sel_sock;
1236 	else
1237 		radius->acct_sock = sel_sock;
1238 
1239 	return 0;
1240 }
1241 
1242 
radius_retry_primary_timer(void * eloop_ctx,void * timeout_ctx)1243 static void radius_retry_primary_timer(void *eloop_ctx, void *timeout_ctx)
1244 {
1245 	struct radius_client_data *radius = eloop_ctx;
1246 	struct hostapd_radius_servers *conf = radius->conf;
1247 	struct hostapd_radius_server *oserv;
1248 
1249 	if (radius->auth_sock >= 0 && conf->auth_servers &&
1250 	    conf->auth_server != conf->auth_servers) {
1251 		oserv = conf->auth_server;
1252 		conf->auth_server = conf->auth_servers;
1253 		if (radius_change_server(radius, conf->auth_server, oserv,
1254 					 radius->auth_serv_sock,
1255 					 radius->auth_serv_sock6, 1) < 0) {
1256 			conf->auth_server = oserv;
1257 			radius_change_server(radius, oserv, conf->auth_server,
1258 					     radius->auth_serv_sock,
1259 					     radius->auth_serv_sock6, 1);
1260 		}
1261 	}
1262 
1263 	if (radius->acct_sock >= 0 && conf->acct_servers &&
1264 	    conf->acct_server != conf->acct_servers) {
1265 		oserv = conf->acct_server;
1266 		conf->acct_server = conf->acct_servers;
1267 		if (radius_change_server(radius, conf->acct_server, oserv,
1268 					 radius->acct_serv_sock,
1269 					 radius->acct_serv_sock6, 0) < 0) {
1270 			conf->acct_server = oserv;
1271 			radius_change_server(radius, oserv, conf->acct_server,
1272 					     radius->acct_serv_sock,
1273 					     radius->acct_serv_sock6, 0);
1274 		}
1275 	}
1276 
1277 	if (conf->retry_primary_interval)
1278 		eloop_register_timeout(conf->retry_primary_interval, 0,
1279 				       radius_retry_primary_timer, radius,
1280 				       NULL);
1281 }
1282 
1283 
radius_client_disable_pmtu_discovery(int s)1284 static int radius_client_disable_pmtu_discovery(int s)
1285 {
1286 	int r = -1;
1287 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1288 	/* Turn off Path MTU discovery on IPv4/UDP sockets. */
1289 	int action = IP_PMTUDISC_DONT;
1290 	r = setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &action,
1291 		       sizeof(action));
1292 	if (r == -1)
1293 		wpa_printf(MSG_ERROR, "RADIUS: Failed to set IP_MTU_DISCOVER: %s",
1294 			   strerror(errno));
1295 #endif
1296 	return r;
1297 }
1298 
1299 
radius_close_auth_sockets(struct radius_client_data * radius)1300 static void radius_close_auth_sockets(struct radius_client_data *radius)
1301 {
1302 	radius->auth_sock = -1;
1303 
1304 	if (radius->auth_serv_sock >= 0) {
1305 		eloop_unregister_read_sock(radius->auth_serv_sock);
1306 		close(radius->auth_serv_sock);
1307 		radius->auth_serv_sock = -1;
1308 	}
1309 #ifdef CONFIG_IPV6
1310 	if (radius->auth_serv_sock6 >= 0) {
1311 		eloop_unregister_read_sock(radius->auth_serv_sock6);
1312 		close(radius->auth_serv_sock6);
1313 		radius->auth_serv_sock6 = -1;
1314 	}
1315 #endif /* CONFIG_IPV6 */
1316 }
1317 
1318 
radius_close_acct_sockets(struct radius_client_data * radius)1319 static void radius_close_acct_sockets(struct radius_client_data *radius)
1320 {
1321 	radius->acct_sock = -1;
1322 
1323 	if (radius->acct_serv_sock >= 0) {
1324 		eloop_unregister_read_sock(radius->acct_serv_sock);
1325 		close(radius->acct_serv_sock);
1326 		radius->acct_serv_sock = -1;
1327 	}
1328 #ifdef CONFIG_IPV6
1329 	if (radius->acct_serv_sock6 >= 0) {
1330 		eloop_unregister_read_sock(radius->acct_serv_sock6);
1331 		close(radius->acct_serv_sock6);
1332 		radius->acct_serv_sock6 = -1;
1333 	}
1334 #endif /* CONFIG_IPV6 */
1335 }
1336 
1337 
radius_client_init_auth(struct radius_client_data * radius)1338 static int radius_client_init_auth(struct radius_client_data *radius)
1339 {
1340 	struct hostapd_radius_servers *conf = radius->conf;
1341 	int ok = 0;
1342 
1343 	radius_close_auth_sockets(radius);
1344 
1345 	radius->auth_serv_sock = socket(PF_INET, SOCK_DGRAM, 0);
1346 	if (radius->auth_serv_sock < 0)
1347 		wpa_printf(MSG_INFO, "RADIUS: socket[PF_INET,SOCK_DGRAM]: %s",
1348 			   strerror(errno));
1349 	else {
1350 		radius_client_disable_pmtu_discovery(radius->auth_serv_sock);
1351 		ok++;
1352 	}
1353 
1354 #ifdef CONFIG_IPV6
1355 	radius->auth_serv_sock6 = socket(PF_INET6, SOCK_DGRAM, 0);
1356 	if (radius->auth_serv_sock6 < 0)
1357 		wpa_printf(MSG_INFO, "RADIUS: socket[PF_INET6,SOCK_DGRAM]: %s",
1358 			   strerror(errno));
1359 	else
1360 		ok++;
1361 #endif /* CONFIG_IPV6 */
1362 
1363 	if (ok == 0)
1364 		return -1;
1365 
1366 	radius_change_server(radius, conf->auth_server, NULL,
1367 			     radius->auth_serv_sock, radius->auth_serv_sock6,
1368 			     1);
1369 
1370 	if (radius->auth_serv_sock >= 0 &&
1371 	    eloop_register_read_sock(radius->auth_serv_sock,
1372 				     radius_client_receive, radius,
1373 				     (void *) RADIUS_AUTH)) {
1374 		wpa_printf(MSG_INFO, "RADIUS: Could not register read socket for authentication server");
1375 		radius_close_auth_sockets(radius);
1376 		return -1;
1377 	}
1378 
1379 #ifdef CONFIG_IPV6
1380 	if (radius->auth_serv_sock6 >= 0 &&
1381 	    eloop_register_read_sock(radius->auth_serv_sock6,
1382 				     radius_client_receive, radius,
1383 				     (void *) RADIUS_AUTH)) {
1384 		wpa_printf(MSG_INFO, "RADIUS: Could not register read socket for authentication server");
1385 		radius_close_auth_sockets(radius);
1386 		return -1;
1387 	}
1388 #endif /* CONFIG_IPV6 */
1389 
1390 	return 0;
1391 }
1392 
1393 
radius_client_init_acct(struct radius_client_data * radius)1394 static int radius_client_init_acct(struct radius_client_data *radius)
1395 {
1396 	struct hostapd_radius_servers *conf = radius->conf;
1397 	int ok = 0;
1398 
1399 	radius_close_acct_sockets(radius);
1400 
1401 	radius->acct_serv_sock = socket(PF_INET, SOCK_DGRAM, 0);
1402 	if (radius->acct_serv_sock < 0)
1403 		wpa_printf(MSG_INFO, "RADIUS: socket[PF_INET,SOCK_DGRAM]: %s",
1404 			   strerror(errno));
1405 	else {
1406 		radius_client_disable_pmtu_discovery(radius->acct_serv_sock);
1407 		ok++;
1408 	}
1409 
1410 #ifdef CONFIG_IPV6
1411 	radius->acct_serv_sock6 = socket(PF_INET6, SOCK_DGRAM, 0);
1412 	if (radius->acct_serv_sock6 < 0)
1413 		wpa_printf(MSG_INFO, "RADIUS: socket[PF_INET6,SOCK_DGRAM]: %s",
1414 			   strerror(errno));
1415 	else
1416 		ok++;
1417 #endif /* CONFIG_IPV6 */
1418 
1419 	if (ok == 0)
1420 		return -1;
1421 
1422 	radius_change_server(radius, conf->acct_server, NULL,
1423 			     radius->acct_serv_sock, radius->acct_serv_sock6,
1424 			     0);
1425 
1426 	if (radius->acct_serv_sock >= 0 &&
1427 	    eloop_register_read_sock(radius->acct_serv_sock,
1428 				     radius_client_receive, radius,
1429 				     (void *) RADIUS_ACCT)) {
1430 		wpa_printf(MSG_INFO, "RADIUS: Could not register read socket for accounting server");
1431 		radius_close_acct_sockets(radius);
1432 		return -1;
1433 	}
1434 
1435 #ifdef CONFIG_IPV6
1436 	if (radius->acct_serv_sock6 >= 0 &&
1437 	    eloop_register_read_sock(radius->acct_serv_sock6,
1438 				     radius_client_receive, radius,
1439 				     (void *) RADIUS_ACCT)) {
1440 		wpa_printf(MSG_INFO, "RADIUS: Could not register read socket for accounting server");
1441 		radius_close_acct_sockets(radius);
1442 		return -1;
1443 	}
1444 #endif /* CONFIG_IPV6 */
1445 
1446 	return 0;
1447 }
1448 
1449 
1450 /**
1451  * radius_client_init - Initialize RADIUS client
1452  * @ctx: Callback context to be used in hostapd_logger() calls
1453  * @conf: RADIUS client configuration (RADIUS servers)
1454  * Returns: Pointer to private RADIUS client context or %NULL on failure
1455  *
1456  * The caller is responsible for keeping the configuration data available for
1457  * the lifetime of the RADIUS client, i.e., until radius_client_deinit() is
1458  * called for the returned context pointer.
1459  */
1460 struct radius_client_data *
radius_client_init(void * ctx,struct hostapd_radius_servers * conf)1461 radius_client_init(void *ctx, struct hostapd_radius_servers *conf)
1462 {
1463 	struct radius_client_data *radius;
1464 
1465 	radius = os_zalloc(sizeof(struct radius_client_data));
1466 	if (radius == NULL)
1467 		return NULL;
1468 
1469 	radius->ctx = ctx;
1470 	radius->conf = conf;
1471 	radius->auth_serv_sock = radius->acct_serv_sock =
1472 		radius->auth_serv_sock6 = radius->acct_serv_sock6 =
1473 		radius->auth_sock = radius->acct_sock = -1;
1474 
1475 	if (conf->auth_server && radius_client_init_auth(radius)) {
1476 		radius_client_deinit(radius);
1477 		return NULL;
1478 	}
1479 
1480 	if (conf->acct_server && radius_client_init_acct(radius)) {
1481 		radius_client_deinit(radius);
1482 		return NULL;
1483 	}
1484 
1485 	if (conf->retry_primary_interval)
1486 		eloop_register_timeout(conf->retry_primary_interval, 0,
1487 				       radius_retry_primary_timer, radius,
1488 				       NULL);
1489 
1490 	return radius;
1491 }
1492 
1493 
1494 /**
1495  * radius_client_deinit - Deinitialize RADIUS client
1496  * @radius: RADIUS client context from radius_client_init()
1497  */
radius_client_deinit(struct radius_client_data * radius)1498 void radius_client_deinit(struct radius_client_data *radius)
1499 {
1500 	if (!radius)
1501 		return;
1502 
1503 	radius_close_auth_sockets(radius);
1504 	radius_close_acct_sockets(radius);
1505 
1506 	eloop_cancel_timeout(radius_retry_primary_timer, radius, NULL);
1507 
1508 	radius_client_flush(radius, 0);
1509 	os_free(radius->auth_handlers);
1510 	os_free(radius->acct_handlers);
1511 	os_free(radius);
1512 }
1513 
1514 
1515 /**
1516  * radius_client_flush_auth - Flush pending RADIUS messages for an address
1517  * @radius: RADIUS client context from radius_client_init()
1518  * @addr: MAC address of the related device
1519  *
1520  * This function can be used to remove pending RADIUS authentication messages
1521  * that are related to a specific device. The addr parameter is matched with
1522  * the one used in radius_client_send() call that was used to transmit the
1523  * authentication request.
1524  */
radius_client_flush_auth(struct radius_client_data * radius,const u8 * addr)1525 void radius_client_flush_auth(struct radius_client_data *radius,
1526 			      const u8 *addr)
1527 {
1528 	struct radius_msg_list *entry, *prev, *tmp;
1529 
1530 	prev = NULL;
1531 	entry = radius->msgs;
1532 	while (entry) {
1533 		if (entry->msg_type == RADIUS_AUTH &&
1534 		    os_memcmp(entry->addr, addr, ETH_ALEN) == 0) {
1535 			hostapd_logger(radius->ctx, addr,
1536 				       HOSTAPD_MODULE_RADIUS,
1537 				       HOSTAPD_LEVEL_DEBUG,
1538 				       "Removing pending RADIUS authentication"
1539 				       " message for removed client");
1540 
1541 			if (prev)
1542 				prev->next = entry->next;
1543 			else
1544 				radius->msgs = entry->next;
1545 
1546 			tmp = entry;
1547 			entry = entry->next;
1548 			radius_client_msg_free(tmp);
1549 			radius->num_msgs--;
1550 			continue;
1551 		}
1552 
1553 		prev = entry;
1554 		entry = entry->next;
1555 	}
1556 }
1557 
1558 
radius_client_dump_auth_server(char * buf,size_t buflen,struct hostapd_radius_server * serv,struct radius_client_data * cli)1559 static int radius_client_dump_auth_server(char *buf, size_t buflen,
1560 					  struct hostapd_radius_server *serv,
1561 					  struct radius_client_data *cli)
1562 {
1563 	int pending = 0;
1564 	struct radius_msg_list *msg;
1565 	char abuf[50];
1566 
1567 	if (cli) {
1568 		for (msg = cli->msgs; msg; msg = msg->next) {
1569 			if (msg->msg_type == RADIUS_AUTH)
1570 				pending++;
1571 		}
1572 	}
1573 
1574 	return os_snprintf(buf, buflen,
1575 			   "radiusAuthServerIndex=%d\n"
1576 			   "radiusAuthServerAddress=%s\n"
1577 			   "radiusAuthClientServerPortNumber=%d\n"
1578 			   "radiusAuthClientRoundTripTime=%d\n"
1579 			   "radiusAuthClientAccessRequests=%u\n"
1580 			   "radiusAuthClientAccessRetransmissions=%u\n"
1581 			   "radiusAuthClientAccessAccepts=%u\n"
1582 			   "radiusAuthClientAccessRejects=%u\n"
1583 			   "radiusAuthClientAccessChallenges=%u\n"
1584 			   "radiusAuthClientMalformedAccessResponses=%u\n"
1585 			   "radiusAuthClientBadAuthenticators=%u\n"
1586 			   "radiusAuthClientPendingRequests=%u\n"
1587 			   "radiusAuthClientTimeouts=%u\n"
1588 			   "radiusAuthClientUnknownTypes=%u\n"
1589 			   "radiusAuthClientPacketsDropped=%u\n",
1590 			   serv->index,
1591 			   hostapd_ip_txt(&serv->addr, abuf, sizeof(abuf)),
1592 			   serv->port,
1593 			   serv->round_trip_time,
1594 			   serv->requests,
1595 			   serv->retransmissions,
1596 			   serv->access_accepts,
1597 			   serv->access_rejects,
1598 			   serv->access_challenges,
1599 			   serv->malformed_responses,
1600 			   serv->bad_authenticators,
1601 			   pending,
1602 			   serv->timeouts,
1603 			   serv->unknown_types,
1604 			   serv->packets_dropped);
1605 }
1606 
1607 
radius_client_dump_acct_server(char * buf,size_t buflen,struct hostapd_radius_server * serv,struct radius_client_data * cli)1608 static int radius_client_dump_acct_server(char *buf, size_t buflen,
1609 					  struct hostapd_radius_server *serv,
1610 					  struct radius_client_data *cli)
1611 {
1612 	int pending = 0;
1613 	struct radius_msg_list *msg;
1614 	char abuf[50];
1615 
1616 	if (cli) {
1617 		for (msg = cli->msgs; msg; msg = msg->next) {
1618 			if (msg->msg_type == RADIUS_ACCT ||
1619 			    msg->msg_type == RADIUS_ACCT_INTERIM)
1620 				pending++;
1621 		}
1622 	}
1623 
1624 	return os_snprintf(buf, buflen,
1625 			   "radiusAccServerIndex=%d\n"
1626 			   "radiusAccServerAddress=%s\n"
1627 			   "radiusAccClientServerPortNumber=%d\n"
1628 			   "radiusAccClientRoundTripTime=%d\n"
1629 			   "radiusAccClientRequests=%u\n"
1630 			   "radiusAccClientRetransmissions=%u\n"
1631 			   "radiusAccClientResponses=%u\n"
1632 			   "radiusAccClientMalformedResponses=%u\n"
1633 			   "radiusAccClientBadAuthenticators=%u\n"
1634 			   "radiusAccClientPendingRequests=%u\n"
1635 			   "radiusAccClientTimeouts=%u\n"
1636 			   "radiusAccClientUnknownTypes=%u\n"
1637 			   "radiusAccClientPacketsDropped=%u\n",
1638 			   serv->index,
1639 			   hostapd_ip_txt(&serv->addr, abuf, sizeof(abuf)),
1640 			   serv->port,
1641 			   serv->round_trip_time,
1642 			   serv->requests,
1643 			   serv->retransmissions,
1644 			   serv->responses,
1645 			   serv->malformed_responses,
1646 			   serv->bad_authenticators,
1647 			   pending,
1648 			   serv->timeouts,
1649 			   serv->unknown_types,
1650 			   serv->packets_dropped);
1651 }
1652 
1653 
1654 /**
1655  * radius_client_get_mib - Get RADIUS client MIB information
1656  * @radius: RADIUS client context from radius_client_init()
1657  * @buf: Buffer for returning MIB data in text format
1658  * @buflen: Maximum buf length in octets
1659  * Returns: Number of octets written into the buffer
1660  */
radius_client_get_mib(struct radius_client_data * radius,char * buf,size_t buflen)1661 int radius_client_get_mib(struct radius_client_data *radius, char *buf,
1662 			  size_t buflen)
1663 {
1664 	struct hostapd_radius_servers *conf;
1665 	int i;
1666 	struct hostapd_radius_server *serv;
1667 	int count = 0;
1668 
1669 	if (!radius)
1670 		return 0;
1671 
1672 	conf = radius->conf;
1673 
1674 	if (conf->auth_servers) {
1675 		for (i = 0; i < conf->num_auth_servers; i++) {
1676 			serv = &conf->auth_servers[i];
1677 			count += radius_client_dump_auth_server(
1678 				buf + count, buflen - count, serv,
1679 				serv == conf->auth_server ?
1680 				radius : NULL);
1681 		}
1682 	}
1683 
1684 	if (conf->acct_servers) {
1685 		for (i = 0; i < conf->num_acct_servers; i++) {
1686 			serv = &conf->acct_servers[i];
1687 			count += radius_client_dump_acct_server(
1688 				buf + count, buflen - count, serv,
1689 				serv == conf->acct_server ?
1690 				radius : NULL);
1691 		}
1692 	}
1693 
1694 	return count;
1695 }
1696 
1697 
radius_client_reconfig(struct radius_client_data * radius,struct hostapd_radius_servers * conf)1698 void radius_client_reconfig(struct radius_client_data *radius,
1699 			    struct hostapd_radius_servers *conf)
1700 {
1701 	if (radius)
1702 		radius->conf = conf;
1703 }
1704