radius_server.c revision 351611
1/*
2 * RADIUS authentication server
3 * Copyright (c) 2005-2009, 2011-2019, 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#include <net/if.h>
11#ifdef CONFIG_SQLITE
12#include <sqlite3.h>
13#endif /* CONFIG_SQLITE */
14
15#include "common.h"
16#include "radius.h"
17#include "eloop.h"
18#include "eap_server/eap.h"
19#include "ap/ap_config.h"
20#include "crypto/tls.h"
21#include "radius_server.h"
22
23/**
24 * RADIUS_SESSION_TIMEOUT - Session timeout in seconds
25 */
26#define RADIUS_SESSION_TIMEOUT 60
27
28/**
29 * RADIUS_SESSION_MAINTAIN - Completed session expiration timeout in seconds
30 */
31#define RADIUS_SESSION_MAINTAIN 5
32
33/**
34 * RADIUS_MAX_SESSION - Maximum number of active sessions
35 */
36#define RADIUS_MAX_SESSION 1000
37
38/**
39 * RADIUS_MAX_MSG_LEN - Maximum message length for incoming RADIUS messages
40 */
41#define RADIUS_MAX_MSG_LEN 3000
42
43static const struct eapol_callbacks radius_server_eapol_cb;
44
45struct radius_client;
46struct radius_server_data;
47
48/**
49 * struct radius_server_counters - RADIUS server statistics counters
50 */
51struct radius_server_counters {
52	u32 access_requests;
53	u32 invalid_requests;
54	u32 dup_access_requests;
55	u32 access_accepts;
56	u32 access_rejects;
57	u32 access_challenges;
58	u32 malformed_access_requests;
59	u32 bad_authenticators;
60	u32 packets_dropped;
61	u32 unknown_types;
62
63	u32 acct_requests;
64	u32 invalid_acct_requests;
65	u32 acct_responses;
66	u32 malformed_acct_requests;
67	u32 acct_bad_authenticators;
68	u32 unknown_acct_types;
69};
70
71/**
72 * struct radius_session - Internal RADIUS server data for a session
73 */
74struct radius_session {
75	struct radius_session *next;
76	struct radius_client *client;
77	struct radius_server_data *server;
78	unsigned int sess_id;
79	struct eap_sm *eap;
80	struct eap_eapol_interface *eap_if;
81	char *username; /* from User-Name attribute */
82	char *nas_ip;
83	u8 mac_addr[ETH_ALEN]; /* from Calling-Station-Id attribute */
84
85	struct radius_msg *last_msg;
86	char *last_from_addr;
87	int last_from_port;
88	struct sockaddr_storage last_from;
89	socklen_t last_fromlen;
90	u8 last_identifier;
91	struct radius_msg *last_reply;
92	u8 last_authenticator[16];
93
94	unsigned int remediation:1;
95	unsigned int macacl:1;
96	unsigned int t_c_filtering:1;
97
98	struct hostapd_radius_attr *accept_attr;
99
100	u32 t_c_timestamp; /* Last read T&C timestamp from user DB */
101};
102
103/**
104 * struct radius_client - Internal RADIUS server data for a client
105 */
106struct radius_client {
107	struct radius_client *next;
108	struct in_addr addr;
109	struct in_addr mask;
110#ifdef CONFIG_IPV6
111	struct in6_addr addr6;
112	struct in6_addr mask6;
113#endif /* CONFIG_IPV6 */
114	char *shared_secret;
115	int shared_secret_len;
116	struct radius_session *sessions;
117	struct radius_server_counters counters;
118
119	u8 next_dac_identifier;
120	struct radius_msg *pending_dac_coa_req;
121	u8 pending_dac_coa_id;
122	u8 pending_dac_coa_addr[ETH_ALEN];
123	struct radius_msg *pending_dac_disconnect_req;
124	u8 pending_dac_disconnect_id;
125	u8 pending_dac_disconnect_addr[ETH_ALEN];
126};
127
128/**
129 * struct radius_server_data - Internal RADIUS server data
130 */
131struct radius_server_data {
132	/**
133	 * auth_sock - Socket for RADIUS authentication messages
134	 */
135	int auth_sock;
136
137	/**
138	 * acct_sock - Socket for RADIUS accounting messages
139	 */
140	int acct_sock;
141
142	/**
143	 * clients - List of authorized RADIUS clients
144	 */
145	struct radius_client *clients;
146
147	/**
148	 * next_sess_id - Next session identifier
149	 */
150	unsigned int next_sess_id;
151
152	/**
153	 * conf_ctx - Context pointer for callbacks
154	 *
155	 * This is used as the ctx argument in get_eap_user() calls.
156	 */
157	void *conf_ctx;
158
159	/**
160	 * num_sess - Number of active sessions
161	 */
162	int num_sess;
163
164	/**
165	 * eap_sim_db_priv - EAP-SIM/AKA database context
166	 *
167	 * This is passed to the EAP-SIM/AKA server implementation as a
168	 * callback context.
169	 */
170	void *eap_sim_db_priv;
171
172	/**
173	 * ssl_ctx - TLS context
174	 *
175	 * This is passed to the EAP server implementation as a callback
176	 * context for TLS operations.
177	 */
178	void *ssl_ctx;
179
180	/**
181	 * pac_opaque_encr_key - PAC-Opaque encryption key for EAP-FAST
182	 *
183	 * This parameter is used to set a key for EAP-FAST to encrypt the
184	 * PAC-Opaque data. It can be set to %NULL if EAP-FAST is not used. If
185	 * set, must point to a 16-octet key.
186	 */
187	u8 *pac_opaque_encr_key;
188
189	/**
190	 * eap_fast_a_id - EAP-FAST authority identity (A-ID)
191	 *
192	 * If EAP-FAST is not used, this can be set to %NULL. In theory, this
193	 * is a variable length field, but due to some existing implementations
194	 * requiring A-ID to be 16 octets in length, it is recommended to use
195	 * that length for the field to provide interoperability with deployed
196	 * peer implementations.
197	 */
198	u8 *eap_fast_a_id;
199
200	/**
201	 * eap_fast_a_id_len - Length of eap_fast_a_id buffer in octets
202	 */
203	size_t eap_fast_a_id_len;
204
205	/**
206	 * eap_fast_a_id_info - EAP-FAST authority identifier information
207	 *
208	 * This A-ID-Info contains a user-friendly name for the A-ID. For
209	 * example, this could be the enterprise and server names in
210	 * human-readable format. This field is encoded as UTF-8. If EAP-FAST
211	 * is not used, this can be set to %NULL.
212	 */
213	char *eap_fast_a_id_info;
214
215	/**
216	 * eap_fast_prov - EAP-FAST provisioning modes
217	 *
218	 * 0 = provisioning disabled, 1 = only anonymous provisioning allowed,
219	 * 2 = only authenticated provisioning allowed, 3 = both provisioning
220	 * modes allowed.
221	 */
222	int eap_fast_prov;
223
224	/**
225	 * pac_key_lifetime - EAP-FAST PAC-Key lifetime in seconds
226	 *
227	 * This is the hard limit on how long a provisioned PAC-Key can be
228	 * used.
229	 */
230	int pac_key_lifetime;
231
232	/**
233	 * pac_key_refresh_time - EAP-FAST PAC-Key refresh time in seconds
234	 *
235	 * This is a soft limit on the PAC-Key. The server will automatically
236	 * generate a new PAC-Key when this number of seconds (or fewer) of the
237	 * lifetime remains.
238	 */
239	int pac_key_refresh_time;
240
241	int eap_teap_auth;
242	int eap_teap_pac_no_inner;
243
244	/**
245	 * eap_sim_aka_result_ind - EAP-SIM/AKA protected success indication
246	 *
247	 * This controls whether the protected success/failure indication
248	 * (AT_RESULT_IND) is used with EAP-SIM and EAP-AKA.
249	 */
250	int eap_sim_aka_result_ind;
251
252	int eap_sim_id;
253
254	/**
255	 * tnc - Trusted Network Connect (TNC)
256	 *
257	 * This controls whether TNC is enabled and will be required before the
258	 * peer is allowed to connect. Note: This is only used with EAP-TTLS
259	 * and EAP-FAST. If any other EAP method is enabled, the peer will be
260	 * allowed to connect without TNC.
261	 */
262	int tnc;
263
264	/**
265	 * pwd_group - The D-H group assigned for EAP-pwd
266	 *
267	 * If EAP-pwd is not used it can be set to zero.
268	 */
269	u16 pwd_group;
270
271	/**
272	 * server_id - Server identity
273	 */
274	const char *server_id;
275
276	/**
277	 * erp - Whether EAP Re-authentication Protocol (ERP) is enabled
278	 *
279	 * This controls whether the authentication server derives ERP key
280	 * hierarchy (rRK and rIK) from full EAP authentication and allows
281	 * these keys to be used to perform ERP to derive rMSK instead of full
282	 * EAP authentication to derive MSK.
283	 */
284	int erp;
285
286	const char *erp_domain;
287
288	struct dl_list erp_keys; /* struct eap_server_erp_key */
289
290	unsigned int tls_session_lifetime;
291
292	unsigned int tls_flags;
293
294	/**
295	 * wps - Wi-Fi Protected Setup context
296	 *
297	 * If WPS is used with an external RADIUS server (which is quite
298	 * unlikely configuration), this is used to provide a pointer to WPS
299	 * context data. Normally, this can be set to %NULL.
300	 */
301	struct wps_context *wps;
302
303	/**
304	 * ipv6 - Whether to enable IPv6 support in the RADIUS server
305	 */
306	int ipv6;
307
308	/**
309	 * start_time - Timestamp of server start
310	 */
311	struct os_reltime start_time;
312
313	/**
314	 * counters - Statistics counters for server operations
315	 *
316	 * These counters are the sum over all clients.
317	 */
318	struct radius_server_counters counters;
319
320	/**
321	 * get_eap_user - Callback for fetching EAP user information
322	 * @ctx: Context data from conf_ctx
323	 * @identity: User identity
324	 * @identity_len: identity buffer length in octets
325	 * @phase2: Whether this is for Phase 2 identity
326	 * @user: Data structure for filling in the user information
327	 * Returns: 0 on success, -1 on failure
328	 *
329	 * This is used to fetch information from user database. The callback
330	 * will fill in information about allowed EAP methods and the user
331	 * password. The password field will be an allocated copy of the
332	 * password data and RADIUS server will free it after use.
333	 */
334	int (*get_eap_user)(void *ctx, const u8 *identity, size_t identity_len,
335			    int phase2, struct eap_user *user);
336
337	/**
338	 * eap_req_id_text - Optional data for EAP-Request/Identity
339	 *
340	 * This can be used to configure an optional, displayable message that
341	 * will be sent in EAP-Request/Identity. This string can contain an
342	 * ASCII-0 character (nul) to separate network infromation per RFC
343	 * 4284. The actual string length is explicit provided in
344	 * eap_req_id_text_len since nul character will not be used as a string
345	 * terminator.
346	 */
347	char *eap_req_id_text;
348
349	/**
350	 * eap_req_id_text_len - Length of eap_req_id_text buffer in octets
351	 */
352	size_t eap_req_id_text_len;
353
354	/*
355	 * msg_ctx - Context data for wpa_msg() calls
356	 */
357	void *msg_ctx;
358
359#ifdef CONFIG_RADIUS_TEST
360	char *dump_msk_file;
361#endif /* CONFIG_RADIUS_TEST */
362
363	char *subscr_remediation_url;
364	u8 subscr_remediation_method;
365	char *hs20_sim_provisioning_url;
366
367	char *t_c_server_url;
368
369#ifdef CONFIG_SQLITE
370	sqlite3 *db;
371#endif /* CONFIG_SQLITE */
372};
373
374
375#define RADIUS_DEBUG(args...) \
376wpa_printf(MSG_DEBUG, "RADIUS SRV: " args)
377#define RADIUS_ERROR(args...) \
378wpa_printf(MSG_ERROR, "RADIUS SRV: " args)
379#define RADIUS_DUMP(args...) \
380wpa_hexdump(MSG_MSGDUMP, "RADIUS SRV: " args)
381#define RADIUS_DUMP_ASCII(args...) \
382wpa_hexdump_ascii(MSG_MSGDUMP, "RADIUS SRV: " args)
383
384
385static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx);
386static void radius_server_session_remove_timeout(void *eloop_ctx,
387						 void *timeout_ctx);
388
389#ifdef CONFIG_SQLITE
390#ifdef CONFIG_HS20
391
392static int db_table_exists(sqlite3 *db, const char *name)
393{
394	char cmd[128];
395
396	os_snprintf(cmd, sizeof(cmd), "SELECT 1 FROM %s;", name);
397	return sqlite3_exec(db, cmd, NULL, NULL, NULL) == SQLITE_OK;
398}
399
400
401static int db_table_create_sim_provisioning(sqlite3 *db)
402{
403	char *err = NULL;
404	const char *sql =
405		"CREATE TABLE sim_provisioning("
406		" mobile_identifier_hash TEXT PRIMARY KEY,"
407		" imsi TEXT,"
408		" mac_addr TEXT,"
409		" eap_method TEXT,"
410		" timestamp TEXT"
411		");";
412
413	RADIUS_DEBUG("Adding database table for SIM provisioning information");
414	if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
415		RADIUS_ERROR("SQLite error: %s", err);
416		sqlite3_free(err);
417		return -1;
418	}
419
420	return 0;
421}
422
423#endif /* CONFIG_HS20 */
424#endif /* CONFIG_SQLITE */
425
426
427void srv_log(struct radius_session *sess, const char *fmt, ...)
428PRINTF_FORMAT(2, 3);
429
430void srv_log(struct radius_session *sess, const char *fmt, ...)
431{
432	va_list ap;
433	char *buf;
434	int buflen;
435
436	va_start(ap, fmt);
437	buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
438	va_end(ap);
439
440	buf = os_malloc(buflen);
441	if (buf == NULL)
442		return;
443	va_start(ap, fmt);
444	vsnprintf(buf, buflen, fmt, ap);
445	va_end(ap);
446
447	RADIUS_DEBUG("[0x%x %s] %s", sess->sess_id, sess->nas_ip, buf);
448
449#ifdef CONFIG_SQLITE
450	if (sess->server->db) {
451		char *sql;
452		sql = sqlite3_mprintf("INSERT INTO authlog"
453				      "(timestamp,session,nas_ip,username,note)"
454				      " VALUES ("
455				      "strftime('%%Y-%%m-%%d %%H:%%M:%%f',"
456				      "'now'),%u,%Q,%Q,%Q)",
457				      sess->sess_id, sess->nas_ip,
458				      sess->username, buf);
459		if (sql) {
460			if (sqlite3_exec(sess->server->db, sql, NULL, NULL,
461					 NULL) != SQLITE_OK) {
462				RADIUS_ERROR("Failed to add authlog entry into sqlite database: %s",
463					     sqlite3_errmsg(sess->server->db));
464			}
465			sqlite3_free(sql);
466		}
467	}
468#endif /* CONFIG_SQLITE */
469
470	os_free(buf);
471}
472
473
474static struct radius_client *
475radius_server_get_client(struct radius_server_data *data, struct in_addr *addr,
476			 int ipv6)
477{
478	struct radius_client *client = data->clients;
479
480	while (client) {
481#ifdef CONFIG_IPV6
482		if (ipv6) {
483			struct in6_addr *addr6;
484			int i;
485
486			addr6 = (struct in6_addr *) addr;
487			for (i = 0; i < 16; i++) {
488				if ((addr6->s6_addr[i] &
489				     client->mask6.s6_addr[i]) !=
490				    (client->addr6.s6_addr[i] &
491				     client->mask6.s6_addr[i])) {
492					i = 17;
493					break;
494				}
495			}
496			if (i == 16) {
497				break;
498			}
499		}
500#endif /* CONFIG_IPV6 */
501		if (!ipv6 && (client->addr.s_addr & client->mask.s_addr) ==
502		    (addr->s_addr & client->mask.s_addr)) {
503			break;
504		}
505
506		client = client->next;
507	}
508
509	return client;
510}
511
512
513static struct radius_session *
514radius_server_get_session(struct radius_client *client, unsigned int sess_id)
515{
516	struct radius_session *sess = client->sessions;
517
518	while (sess) {
519		if (sess->sess_id == sess_id) {
520			break;
521		}
522		sess = sess->next;
523	}
524
525	return sess;
526}
527
528
529static void radius_server_session_free(struct radius_server_data *data,
530				       struct radius_session *sess)
531{
532	eloop_cancel_timeout(radius_server_session_timeout, data, sess);
533	eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);
534	eap_server_sm_deinit(sess->eap);
535	radius_msg_free(sess->last_msg);
536	os_free(sess->last_from_addr);
537	radius_msg_free(sess->last_reply);
538	os_free(sess->username);
539	os_free(sess->nas_ip);
540	os_free(sess);
541	data->num_sess--;
542}
543
544
545static void radius_server_session_remove(struct radius_server_data *data,
546					 struct radius_session *sess)
547{
548	struct radius_client *client = sess->client;
549	struct radius_session *session, *prev;
550
551	eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);
552
553	prev = NULL;
554	session = client->sessions;
555	while (session) {
556		if (session == sess) {
557			if (prev == NULL) {
558				client->sessions = sess->next;
559			} else {
560				prev->next = sess->next;
561			}
562			radius_server_session_free(data, sess);
563			break;
564		}
565		prev = session;
566		session = session->next;
567	}
568}
569
570
571static void radius_server_session_remove_timeout(void *eloop_ctx,
572						 void *timeout_ctx)
573{
574	struct radius_server_data *data = eloop_ctx;
575	struct radius_session *sess = timeout_ctx;
576	RADIUS_DEBUG("Removing completed session 0x%x", sess->sess_id);
577	radius_server_session_remove(data, sess);
578}
579
580
581static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx)
582{
583	struct radius_server_data *data = eloop_ctx;
584	struct radius_session *sess = timeout_ctx;
585
586	RADIUS_DEBUG("Timing out authentication session 0x%x", sess->sess_id);
587	radius_server_session_remove(data, sess);
588}
589
590
591static struct radius_session *
592radius_server_new_session(struct radius_server_data *data,
593			  struct radius_client *client)
594{
595	struct radius_session *sess;
596
597	if (data->num_sess >= RADIUS_MAX_SESSION) {
598		RADIUS_DEBUG("Maximum number of existing session - no room "
599			     "for a new session");
600		return NULL;
601	}
602
603	sess = os_zalloc(sizeof(*sess));
604	if (sess == NULL)
605		return NULL;
606
607	sess->server = data;
608	sess->client = client;
609	sess->sess_id = data->next_sess_id++;
610	sess->next = client->sessions;
611	client->sessions = sess;
612	eloop_register_timeout(RADIUS_SESSION_TIMEOUT, 0,
613			       radius_server_session_timeout, data, sess);
614	data->num_sess++;
615	return sess;
616}
617
618
619#ifdef CONFIG_TESTING_OPTIONS
620static void radius_server_testing_options_tls(struct radius_session *sess,
621					      const char *tls,
622					      struct eap_config *eap_conf)
623{
624	int test = atoi(tls);
625
626	switch (test) {
627	case 1:
628		srv_log(sess, "TLS test - break VerifyData");
629		eap_conf->tls_test_flags = TLS_BREAK_VERIFY_DATA;
630		break;
631	case 2:
632		srv_log(sess, "TLS test - break ServerKeyExchange ServerParams hash");
633		eap_conf->tls_test_flags = TLS_BREAK_SRV_KEY_X_HASH;
634		break;
635	case 3:
636		srv_log(sess, "TLS test - break ServerKeyExchange ServerParams Signature");
637		eap_conf->tls_test_flags = TLS_BREAK_SRV_KEY_X_SIGNATURE;
638		break;
639	case 4:
640		srv_log(sess, "TLS test - RSA-DHE using a short 511-bit prime");
641		eap_conf->tls_test_flags = TLS_DHE_PRIME_511B;
642		break;
643	case 5:
644		srv_log(sess, "TLS test - RSA-DHE using a short 767-bit prime");
645		eap_conf->tls_test_flags = TLS_DHE_PRIME_767B;
646		break;
647	case 6:
648		srv_log(sess, "TLS test - RSA-DHE using a bogus 15 \"prime\"");
649		eap_conf->tls_test_flags = TLS_DHE_PRIME_15;
650		break;
651	case 7:
652		srv_log(sess, "TLS test - RSA-DHE using a short 58-bit prime in long container");
653		eap_conf->tls_test_flags = TLS_DHE_PRIME_58B;
654		break;
655	case 8:
656		srv_log(sess, "TLS test - RSA-DHE using a non-prime");
657		eap_conf->tls_test_flags = TLS_DHE_NON_PRIME;
658		break;
659	default:
660		srv_log(sess, "Unrecognized TLS test");
661		break;
662	}
663}
664#endif /* CONFIG_TESTING_OPTIONS */
665
666static void radius_server_testing_options(struct radius_session *sess,
667					  struct eap_config *eap_conf)
668{
669#ifdef CONFIG_TESTING_OPTIONS
670	const char *pos;
671
672	pos = os_strstr(sess->username, "@test-");
673	if (pos == NULL)
674		return;
675	pos += 6;
676	if (os_strncmp(pos, "tls-", 4) == 0)
677		radius_server_testing_options_tls(sess, pos + 4, eap_conf);
678	else
679		srv_log(sess, "Unrecognized test: %s", pos);
680#endif /* CONFIG_TESTING_OPTIONS */
681}
682
683
684#ifdef CONFIG_ERP
685static struct eap_server_erp_key *
686radius_server_erp_find_key(struct radius_server_data *data, const char *keyname)
687{
688	struct eap_server_erp_key *erp;
689
690	dl_list_for_each(erp, &data->erp_keys, struct eap_server_erp_key,
691			 list) {
692		if (os_strcmp(erp->keyname_nai, keyname) == 0)
693			return erp;
694	}
695
696	return NULL;
697}
698#endif /* CONFIG_ERP */
699
700
701static struct radius_session *
702radius_server_get_new_session(struct radius_server_data *data,
703			      struct radius_client *client,
704			      struct radius_msg *msg, const char *from_addr)
705{
706	u8 *user, *id;
707	size_t user_len, id_len;
708	int res;
709	struct radius_session *sess;
710	struct eap_config eap_conf;
711	struct eap_user *tmp;
712
713	RADIUS_DEBUG("Creating a new session");
714
715	if (radius_msg_get_attr_ptr(msg, RADIUS_ATTR_USER_NAME, &user,
716				    &user_len, NULL) < 0) {
717		RADIUS_DEBUG("Could not get User-Name");
718		return NULL;
719	}
720	RADIUS_DUMP_ASCII("User-Name", user, user_len);
721
722	tmp = os_zalloc(sizeof(*tmp));
723	if (!tmp)
724		return NULL;
725
726	res = data->get_eap_user(data->conf_ctx, user, user_len, 0, tmp);
727#ifdef CONFIG_ERP
728	if (res != 0 && data->erp) {
729		char *username;
730
731		username = os_zalloc(user_len + 1);
732		if (username) {
733			os_memcpy(username, user, user_len);
734			if (radius_server_erp_find_key(data, username))
735				res = 0;
736			os_free(username);
737		}
738	}
739#endif /* CONFIG_ERP */
740	if (res != 0) {
741		RADIUS_DEBUG("User-Name not found from user database");
742		eap_user_free(tmp);
743		return NULL;
744	}
745
746	RADIUS_DEBUG("Matching user entry found");
747	sess = radius_server_new_session(data, client);
748	if (sess == NULL) {
749		RADIUS_DEBUG("Failed to create a new session");
750		eap_user_free(tmp);
751		return NULL;
752	}
753	sess->accept_attr = tmp->accept_attr;
754	sess->macacl = tmp->macacl;
755	eap_user_free(tmp);
756
757	sess->username = os_malloc(user_len * 4 + 1);
758	if (sess->username == NULL) {
759		radius_server_session_remove(data, sess);
760		return NULL;
761	}
762	printf_encode(sess->username, user_len * 4 + 1, user, user_len);
763
764	sess->nas_ip = os_strdup(from_addr);
765	if (sess->nas_ip == NULL) {
766		radius_server_session_remove(data, sess);
767		return NULL;
768	}
769
770	if (radius_msg_get_attr_ptr(msg, RADIUS_ATTR_CALLING_STATION_ID, &id,
771				    &id_len, NULL) == 0) {
772		char buf[3 * ETH_ALEN];
773
774		os_memset(buf, 0, sizeof(buf));
775		if (id_len >= sizeof(buf))
776			id_len = sizeof(buf) - 1;
777		os_memcpy(buf, id, id_len);
778		if (hwaddr_aton2(buf, sess->mac_addr) < 0)
779			os_memset(sess->mac_addr, 0, ETH_ALEN);
780		else
781			RADIUS_DEBUG("Calling-Station-Id: " MACSTR,
782				     MAC2STR(sess->mac_addr));
783	}
784
785	srv_log(sess, "New session created");
786
787	os_memset(&eap_conf, 0, sizeof(eap_conf));
788	eap_conf.ssl_ctx = data->ssl_ctx;
789	eap_conf.msg_ctx = data->msg_ctx;
790	eap_conf.eap_sim_db_priv = data->eap_sim_db_priv;
791	eap_conf.backend_auth = TRUE;
792	eap_conf.eap_server = 1;
793	eap_conf.pac_opaque_encr_key = data->pac_opaque_encr_key;
794	eap_conf.eap_fast_a_id = data->eap_fast_a_id;
795	eap_conf.eap_fast_a_id_len = data->eap_fast_a_id_len;
796	eap_conf.eap_fast_a_id_info = data->eap_fast_a_id_info;
797	eap_conf.eap_fast_prov = data->eap_fast_prov;
798	eap_conf.pac_key_lifetime = data->pac_key_lifetime;
799	eap_conf.pac_key_refresh_time = data->pac_key_refresh_time;
800	eap_conf.eap_teap_auth = data->eap_teap_auth;
801	eap_conf.eap_teap_pac_no_inner = data->eap_teap_pac_no_inner;
802	eap_conf.eap_sim_aka_result_ind = data->eap_sim_aka_result_ind;
803	eap_conf.eap_sim_id = data->eap_sim_id;
804	eap_conf.tnc = data->tnc;
805	eap_conf.wps = data->wps;
806	eap_conf.pwd_group = data->pwd_group;
807	eap_conf.server_id = (const u8 *) data->server_id;
808	eap_conf.server_id_len = os_strlen(data->server_id);
809	eap_conf.erp = data->erp;
810	eap_conf.tls_session_lifetime = data->tls_session_lifetime;
811	eap_conf.tls_flags = data->tls_flags;
812	radius_server_testing_options(sess, &eap_conf);
813	sess->eap = eap_server_sm_init(sess, &radius_server_eapol_cb,
814				       &eap_conf);
815	if (sess->eap == NULL) {
816		RADIUS_DEBUG("Failed to initialize EAP state machine for the "
817			     "new session");
818		radius_server_session_remove(data, sess);
819		return NULL;
820	}
821	sess->eap_if = eap_get_interface(sess->eap);
822	sess->eap_if->eapRestart = TRUE;
823	sess->eap_if->portEnabled = TRUE;
824
825	RADIUS_DEBUG("New session 0x%x initialized", sess->sess_id);
826
827	return sess;
828}
829
830
831#ifdef CONFIG_HS20
832static void radius_srv_hs20_t_c_pending(struct radius_session *sess)
833{
834#ifdef CONFIG_SQLITE
835	char *sql;
836	char addr[3 * ETH_ALEN], *id_str;
837	const u8 *id;
838	size_t id_len;
839
840	if (!sess->server->db || !sess->eap ||
841	    is_zero_ether_addr(sess->mac_addr))
842		return;
843
844	os_snprintf(addr, sizeof(addr), MACSTR, MAC2STR(sess->mac_addr));
845
846	id = eap_get_identity(sess->eap, &id_len);
847	if (!id)
848		return;
849	id_str = os_malloc(id_len + 1);
850	if (!id_str)
851		return;
852	os_memcpy(id_str, id, id_len);
853	id_str[id_len] = '\0';
854
855	sql = sqlite3_mprintf("INSERT OR REPLACE INTO pending_tc (mac_addr,identity) VALUES (%Q,%Q)",
856			      addr, id_str);
857	os_free(id_str);
858	if (!sql)
859		return;
860
861	if (sqlite3_exec(sess->server->db, sql, NULL, NULL, NULL) !=
862	    SQLITE_OK) {
863		RADIUS_ERROR("Failed to add pending_tc entry into sqlite database: %s",
864			     sqlite3_errmsg(sess->server->db));
865	}
866	sqlite3_free(sql);
867#endif /* CONFIG_SQLITE */
868}
869#endif /* CONFIG_HS20 */
870
871
872static void radius_server_add_session(struct radius_session *sess)
873{
874#ifdef CONFIG_SQLITE
875	char *sql;
876	char addr_txt[ETH_ALEN * 3];
877	struct os_time now;
878
879	if (!sess->server->db)
880		return;
881
882
883	os_snprintf(addr_txt, sizeof(addr_txt), MACSTR,
884		    MAC2STR(sess->mac_addr));
885
886	os_get_time(&now);
887	sql = sqlite3_mprintf("INSERT OR REPLACE INTO current_sessions(mac_addr,identity,start_time,nas,hs20_t_c_filtering) VALUES (%Q,%Q,%d,%Q,%u)",
888			      addr_txt, sess->username, now.sec,
889			      sess->nas_ip, sess->t_c_filtering);
890	if (sql) {
891			if (sqlite3_exec(sess->server->db, sql, NULL, NULL,
892					 NULL) != SQLITE_OK) {
893				RADIUS_ERROR("Failed to add current_sessions entry into sqlite database: %s",
894					     sqlite3_errmsg(sess->server->db));
895			}
896			sqlite3_free(sql);
897	}
898#endif /* CONFIG_SQLITE */
899}
900
901
902static void db_update_last_msk(struct radius_session *sess, const char *msk)
903{
904#ifdef CONFIG_RADIUS_TEST
905#ifdef CONFIG_SQLITE
906	char *sql = NULL;
907	char *id_str = NULL;
908	const u8 *id;
909	size_t id_len;
910	const char *serial_num;
911
912	if (!sess->server->db)
913		return;
914
915	serial_num = eap_get_serial_num(sess->eap);
916	if (serial_num) {
917		id_len = 5 + os_strlen(serial_num) + 1;
918		id_str = os_malloc(id_len);
919		if (!id_str)
920			return;
921		os_snprintf(id_str, id_len, "cert-%s", serial_num);
922	} else {
923		id = eap_get_identity(sess->eap, &id_len);
924		if (!id)
925			return;
926		id_str = os_malloc(id_len + 1);
927		if (!id_str)
928			return;
929		os_memcpy(id_str, id, id_len);
930		id_str[id_len] = '\0';
931	}
932
933	sql = sqlite3_mprintf("UPDATE users SET last_msk=%Q WHERE identity=%Q",
934			      msk, id_str);
935	os_free(id_str);
936	if (!sql)
937		return;
938
939	if (sqlite3_exec(sess->server->db, sql, NULL, NULL, NULL) !=
940	    SQLITE_OK) {
941		RADIUS_DEBUG("Failed to update last_msk: %s",
942			     sqlite3_errmsg(sess->server->db));
943	}
944	sqlite3_free(sql);
945#endif /* CONFIG_SQLITE */
946#endif /* CONFIG_RADIUS_TEST */
947}
948
949
950#ifdef CONFIG_HS20
951
952static int radius_server_is_sim_method(struct radius_session *sess)
953{
954	const char *name;
955
956	name = eap_get_method(sess->eap);
957	return name &&
958		(os_strcmp(name, "SIM") == 0 ||
959		 os_strcmp(name, "AKA") == 0 ||
960		 os_strcmp(name, "AKA'") == 0);
961}
962
963
964static int radius_server_hs20_missing_sim_pps(struct radius_msg *request)
965{
966	u8 *buf, *pos, *end, type, sublen;
967	size_t len;
968
969	buf = NULL;
970	for (;;) {
971		if (radius_msg_get_attr_ptr(request,
972					    RADIUS_ATTR_VENDOR_SPECIFIC,
973					    &buf, &len, buf) < 0)
974			return 0;
975		if (len < 6)
976			continue;
977		pos = buf;
978		end = buf + len;
979		if (WPA_GET_BE32(pos) != RADIUS_VENDOR_ID_WFA)
980			continue;
981		pos += 4;
982
983		type = *pos++;
984		sublen = *pos++;
985		if (sublen < 2)
986			continue; /* invalid length */
987		sublen -= 2; /* skip header */
988		if (pos + sublen > end)
989			continue; /* invalid WFA VSA */
990
991		if (type != RADIUS_VENDOR_ATTR_WFA_HS20_STA_VERSION)
992			continue;
993
994		RADIUS_DUMP("HS2.0 mobile device version", pos, sublen);
995		if (sublen < 1 + 2)
996			continue;
997		if (pos[0] == 0)
998			continue; /* Release 1 STA does not support provisioning
999
1000				   */
1001		/* UpdateIdentifier 0 indicates no PPS MO */
1002		return WPA_GET_BE16(pos + 1) == 0;
1003	}
1004}
1005
1006
1007#define HS20_MOBILE_ID_HASH_LEN 16
1008
1009static int radius_server_sim_provisioning_session(struct radius_session *sess,
1010						  const u8 *hash)
1011{
1012#ifdef CONFIG_SQLITE
1013	char *sql;
1014	char addr_txt[ETH_ALEN * 3];
1015	char hash_txt[2 * HS20_MOBILE_ID_HASH_LEN + 1];
1016	struct os_time now;
1017	int res;
1018	const char *imsi, *eap_method;
1019
1020	if (!sess->server->db ||
1021	    (!db_table_exists(sess->server->db, "sim_provisioning") &&
1022	     db_table_create_sim_provisioning(sess->server->db) < 0))
1023		return -1;
1024
1025	imsi = eap_get_imsi(sess->eap);
1026	if (!imsi)
1027		return -1;
1028
1029	eap_method = eap_get_method(sess->eap);
1030	if (!eap_method)
1031		return -1;
1032
1033	os_snprintf(addr_txt, sizeof(addr_txt), MACSTR,
1034		    MAC2STR(sess->mac_addr));
1035	wpa_snprintf_hex(hash_txt, sizeof(hash_txt), hash,
1036			 HS20_MOBILE_ID_HASH_LEN);
1037
1038	os_get_time(&now);
1039	sql = sqlite3_mprintf("INSERT INTO sim_provisioning(mobile_identifier_hash,imsi,mac_addr,eap_method,timestamp) VALUES (%Q,%Q,%Q,%Q,%u)",
1040			      hash_txt, imsi, addr_txt, eap_method, now.sec);
1041	if (!sql)
1042		return -1;
1043
1044	if (sqlite3_exec(sess->server->db, sql, NULL, NULL, NULL) !=
1045	    SQLITE_OK) {
1046		RADIUS_ERROR("Failed to add SIM provisioning entry into sqlite database: %s",
1047			     sqlite3_errmsg(sess->server->db));
1048		res = -1;
1049	} else {
1050		res = 0;
1051	}
1052	sqlite3_free(sql);
1053	return res;
1054#endif /* CONFIG_SQLITE */
1055	return -1;
1056}
1057
1058#endif /* CONFIG_HS20 */
1059
1060
1061static struct radius_msg *
1062radius_server_encapsulate_eap(struct radius_server_data *data,
1063			      struct radius_client *client,
1064			      struct radius_session *sess,
1065			      struct radius_msg *request)
1066{
1067	struct radius_msg *msg;
1068	int code;
1069	unsigned int sess_id;
1070	struct radius_hdr *hdr = radius_msg_get_hdr(request);
1071	u16 reason = WLAN_REASON_IEEE_802_1X_AUTH_FAILED;
1072
1073	if (sess->eap_if->eapFail) {
1074		sess->eap_if->eapFail = FALSE;
1075		code = RADIUS_CODE_ACCESS_REJECT;
1076	} else if (sess->eap_if->eapSuccess) {
1077		sess->eap_if->eapSuccess = FALSE;
1078		code = RADIUS_CODE_ACCESS_ACCEPT;
1079	} else {
1080		sess->eap_if->eapReq = FALSE;
1081		code = RADIUS_CODE_ACCESS_CHALLENGE;
1082	}
1083
1084	msg = radius_msg_new(code, hdr->identifier);
1085	if (msg == NULL) {
1086		RADIUS_DEBUG("Failed to allocate reply message");
1087		return NULL;
1088	}
1089
1090	sess_id = htonl(sess->sess_id);
1091	if (code == RADIUS_CODE_ACCESS_CHALLENGE &&
1092	    !radius_msg_add_attr(msg, RADIUS_ATTR_STATE,
1093				 (u8 *) &sess_id, sizeof(sess_id))) {
1094		RADIUS_DEBUG("Failed to add State attribute");
1095	}
1096
1097	if (sess->eap_if->eapReqData &&
1098	    !radius_msg_add_eap(msg, wpabuf_head(sess->eap_if->eapReqData),
1099				wpabuf_len(sess->eap_if->eapReqData))) {
1100		RADIUS_DEBUG("Failed to add EAP-Message attribute");
1101	}
1102
1103	if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->eap_if->eapKeyData) {
1104		int len;
1105#ifdef CONFIG_RADIUS_TEST
1106		char buf[2 * 64 + 1];
1107
1108		len = sess->eap_if->eapKeyDataLen;
1109		if (len > 64)
1110			len = 64;
1111		len = wpa_snprintf_hex(buf, sizeof(buf),
1112				       sess->eap_if->eapKeyData, len);
1113		buf[len] = '\0';
1114
1115		if (data->dump_msk_file) {
1116			FILE *f;
1117
1118			f = fopen(data->dump_msk_file, "a");
1119			if (f) {
1120				len = sess->eap_if->eapKeyDataLen;
1121				if (len > 64)
1122					len = 64;
1123				len = wpa_snprintf_hex(
1124					buf, sizeof(buf),
1125					sess->eap_if->eapKeyData, len);
1126				buf[len] = '\0';
1127				fprintf(f, "%s\n", buf);
1128				fclose(f);
1129			}
1130		}
1131
1132		db_update_last_msk(sess, buf);
1133#endif /* CONFIG_RADIUS_TEST */
1134		if (sess->eap_if->eapKeyDataLen > 64) {
1135			len = 32;
1136		} else {
1137			len = sess->eap_if->eapKeyDataLen / 2;
1138		}
1139		if (!radius_msg_add_mppe_keys(msg, hdr->authenticator,
1140					      (u8 *) client->shared_secret,
1141					      client->shared_secret_len,
1142					      sess->eap_if->eapKeyData + len,
1143					      len, sess->eap_if->eapKeyData,
1144					      len)) {
1145			RADIUS_DEBUG("Failed to add MPPE key attributes");
1146		}
1147
1148		if (sess->eap_if->eapSessionId &&
1149		    !radius_msg_add_attr(msg, RADIUS_ATTR_EAP_KEY_NAME,
1150					 sess->eap_if->eapSessionId,
1151					 sess->eap_if->eapSessionIdLen)) {
1152			RADIUS_DEBUG("Failed to add EAP-Key-Name attribute");
1153		}
1154	}
1155
1156#ifdef CONFIG_HS20
1157	if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->remediation &&
1158	    data->subscr_remediation_url) {
1159		u8 *buf;
1160		size_t url_len = os_strlen(data->subscr_remediation_url);
1161		buf = os_malloc(1 + url_len);
1162		if (buf == NULL) {
1163			radius_msg_free(msg);
1164			return NULL;
1165		}
1166		buf[0] = data->subscr_remediation_method;
1167		os_memcpy(&buf[1], data->subscr_remediation_url, url_len);
1168		if (!radius_msg_add_wfa(
1169			    msg, RADIUS_VENDOR_ATTR_WFA_HS20_SUBSCR_REMEDIATION,
1170			    buf, 1 + url_len)) {
1171			RADIUS_DEBUG("Failed to add WFA-HS20-SubscrRem");
1172		}
1173		os_free(buf);
1174	} else if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->remediation) {
1175		u8 buf[1];
1176		if (!radius_msg_add_wfa(
1177			    msg, RADIUS_VENDOR_ATTR_WFA_HS20_SUBSCR_REMEDIATION,
1178			    buf, 0)) {
1179			RADIUS_DEBUG("Failed to add WFA-HS20-SubscrRem");
1180		}
1181	} else if (code == RADIUS_CODE_ACCESS_ACCEPT &&
1182		   data->hs20_sim_provisioning_url &&
1183		   radius_server_is_sim_method(sess) &&
1184		   radius_server_hs20_missing_sim_pps(request)) {
1185		u8 *buf, *pos, hash[HS20_MOBILE_ID_HASH_LEN];
1186		size_t prefix_len, url_len;
1187
1188		RADIUS_DEBUG("Device needs HS 2.0 SIM provisioning");
1189
1190		if (os_get_random(hash, HS20_MOBILE_ID_HASH_LEN) < 0) {
1191			radius_msg_free(msg);
1192			return NULL;
1193		}
1194		RADIUS_DUMP("hotspot2dot0-mobile-identifier-hash",
1195			    hash, HS20_MOBILE_ID_HASH_LEN);
1196
1197		if (radius_server_sim_provisioning_session(sess, hash) < 0) {
1198			radius_msg_free(msg);
1199			return NULL;
1200		}
1201
1202		prefix_len = os_strlen(data->hs20_sim_provisioning_url);
1203		url_len = prefix_len + 2 * HS20_MOBILE_ID_HASH_LEN;
1204		buf = os_malloc(1 + url_len + 1);
1205		if (!buf) {
1206			radius_msg_free(msg);
1207			return NULL;
1208		}
1209		pos = buf;
1210		*pos++ = data->subscr_remediation_method;
1211		os_memcpy(pos, data->hs20_sim_provisioning_url, prefix_len);
1212		pos += prefix_len;
1213		wpa_snprintf_hex((char *) pos, 2 * HS20_MOBILE_ID_HASH_LEN + 1,
1214				 hash, HS20_MOBILE_ID_HASH_LEN);
1215		RADIUS_DEBUG("HS 2.0 subscription remediation URL: %s",
1216			     (char *) &buf[1]);
1217		if (!radius_msg_add_wfa(
1218			    msg, RADIUS_VENDOR_ATTR_WFA_HS20_SUBSCR_REMEDIATION,
1219			    buf, 1 + url_len)) {
1220			RADIUS_DEBUG("Failed to add WFA-HS20-SubscrRem");
1221		}
1222		os_free(buf);
1223	}
1224
1225	if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->t_c_filtering) {
1226		u8 buf[4] = { 0x01, 0x00, 0x00, 0x00 }; /* E=1 */
1227		const char *url = data->t_c_server_url, *pos;
1228		char *url2, *end2, *pos2;
1229		size_t url_len;
1230
1231		if (!radius_msg_add_wfa(
1232			    msg, RADIUS_VENDOR_ATTR_WFA_HS20_T_C_FILTERING,
1233			    buf, sizeof(buf))) {
1234			RADIUS_DEBUG("Failed to add WFA-HS20-T-C-Filtering");
1235			radius_msg_free(msg);
1236			return NULL;
1237		}
1238
1239		if (!url) {
1240			RADIUS_DEBUG("No t_c_server_url configured");
1241			radius_msg_free(msg);
1242			return NULL;
1243		}
1244
1245		pos = os_strstr(url, "@1@");
1246		if (!pos) {
1247			RADIUS_DEBUG("No @1@ macro in t_c_server_url");
1248			radius_msg_free(msg);
1249			return NULL;
1250		}
1251
1252		url_len = os_strlen(url) + ETH_ALEN * 3 - 1 - 3;
1253		url2 = os_malloc(url_len + 1);
1254		if (!url2) {
1255			RADIUS_DEBUG("Failed to allocate room for T&C Server URL");
1256			os_free(url2);
1257			radius_msg_free(msg);
1258			return NULL;
1259		}
1260		pos2 = url2;
1261		end2 = url2 + url_len + 1;
1262		os_memcpy(pos2, url, pos - url);
1263		pos2 += pos - url;
1264		os_snprintf(pos2, end2 - pos2, MACSTR, MAC2STR(sess->mac_addr));
1265		pos2 += ETH_ALEN * 3 - 1;
1266		os_memcpy(pos2, pos + 3, os_strlen(pos + 3));
1267		if (!radius_msg_add_wfa(msg,
1268					RADIUS_VENDOR_ATTR_WFA_HS20_T_C_URL,
1269					(const u8 *) url2, url_len)) {
1270			RADIUS_DEBUG("Failed to add WFA-HS20-T-C-URL");
1271			os_free(url2);
1272			radius_msg_free(msg);
1273			return NULL;
1274		}
1275		os_free(url2);
1276
1277		radius_srv_hs20_t_c_pending(sess);
1278	}
1279#endif /* CONFIG_HS20 */
1280
1281	if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
1282		RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
1283		radius_msg_free(msg);
1284		return NULL;
1285	}
1286
1287	if (code == RADIUS_CODE_ACCESS_ACCEPT) {
1288		struct hostapd_radius_attr *attr;
1289		for (attr = sess->accept_attr; attr; attr = attr->next) {
1290			if (!radius_msg_add_attr(msg, attr->type,
1291						 wpabuf_head(attr->val),
1292						 wpabuf_len(attr->val))) {
1293				wpa_printf(MSG_ERROR, "Could not add RADIUS attribute");
1294				radius_msg_free(msg);
1295				return NULL;
1296			}
1297		}
1298	}
1299
1300	if (code == RADIUS_CODE_ACCESS_REJECT) {
1301		if (radius_msg_add_attr_int32(msg, RADIUS_ATTR_WLAN_REASON_CODE,
1302					      reason) < 0) {
1303			RADIUS_DEBUG("Failed to add WLAN-Reason-Code attribute");
1304			radius_msg_free(msg);
1305			return NULL;
1306		}
1307	}
1308
1309	if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
1310				  client->shared_secret_len,
1311				  hdr->authenticator) < 0) {
1312		RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
1313	}
1314
1315	if (code == RADIUS_CODE_ACCESS_ACCEPT)
1316		radius_server_add_session(sess);
1317
1318	return msg;
1319}
1320
1321
1322static struct radius_msg *
1323radius_server_macacl(struct radius_server_data *data,
1324		     struct radius_client *client,
1325		     struct radius_session *sess,
1326		     struct radius_msg *request)
1327{
1328	struct radius_msg *msg;
1329	int code;
1330	struct radius_hdr *hdr = radius_msg_get_hdr(request);
1331	u8 *pw;
1332	size_t pw_len;
1333
1334	code = RADIUS_CODE_ACCESS_ACCEPT;
1335
1336	if (radius_msg_get_attr_ptr(request, RADIUS_ATTR_USER_PASSWORD, &pw,
1337				    &pw_len, NULL) < 0) {
1338		RADIUS_DEBUG("Could not get User-Password");
1339		code = RADIUS_CODE_ACCESS_REJECT;
1340	} else {
1341		int res;
1342		struct eap_user tmp;
1343
1344		os_memset(&tmp, 0, sizeof(tmp));
1345		res = data->get_eap_user(data->conf_ctx, (u8 *) sess->username,
1346					 os_strlen(sess->username), 0, &tmp);
1347		if (res || !tmp.macacl || tmp.password == NULL) {
1348			RADIUS_DEBUG("No MAC ACL user entry");
1349			bin_clear_free(tmp.password, tmp.password_len);
1350			code = RADIUS_CODE_ACCESS_REJECT;
1351		} else {
1352			u8 buf[128];
1353			res = radius_user_password_hide(
1354				request, tmp.password, tmp.password_len,
1355				(u8 *) client->shared_secret,
1356				client->shared_secret_len,
1357				buf, sizeof(buf));
1358			bin_clear_free(tmp.password, tmp.password_len);
1359
1360			if (res < 0 || pw_len != (size_t) res ||
1361			    os_memcmp_const(pw, buf, res) != 0) {
1362				RADIUS_DEBUG("Incorrect User-Password");
1363				code = RADIUS_CODE_ACCESS_REJECT;
1364			}
1365		}
1366	}
1367
1368	msg = radius_msg_new(code, hdr->identifier);
1369	if (msg == NULL) {
1370		RADIUS_DEBUG("Failed to allocate reply message");
1371		return NULL;
1372	}
1373
1374	if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
1375		RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
1376		radius_msg_free(msg);
1377		return NULL;
1378	}
1379
1380	if (code == RADIUS_CODE_ACCESS_ACCEPT) {
1381		struct hostapd_radius_attr *attr;
1382		for (attr = sess->accept_attr; attr; attr = attr->next) {
1383			if (!radius_msg_add_attr(msg, attr->type,
1384						 wpabuf_head(attr->val),
1385						 wpabuf_len(attr->val))) {
1386				wpa_printf(MSG_ERROR, "Could not add RADIUS attribute");
1387				radius_msg_free(msg);
1388				return NULL;
1389			}
1390		}
1391	}
1392
1393	if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
1394				  client->shared_secret_len,
1395				  hdr->authenticator) < 0) {
1396		RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
1397	}
1398
1399	return msg;
1400}
1401
1402
1403static int radius_server_reject(struct radius_server_data *data,
1404				struct radius_client *client,
1405				struct radius_msg *request,
1406				struct sockaddr *from, socklen_t fromlen,
1407				const char *from_addr, int from_port)
1408{
1409	struct radius_msg *msg;
1410	int ret = 0;
1411	struct eap_hdr eapfail;
1412	struct wpabuf *buf;
1413	struct radius_hdr *hdr = radius_msg_get_hdr(request);
1414
1415	RADIUS_DEBUG("Reject invalid request from %s:%d",
1416		     from_addr, from_port);
1417
1418	msg = radius_msg_new(RADIUS_CODE_ACCESS_REJECT, hdr->identifier);
1419	if (msg == NULL) {
1420		return -1;
1421	}
1422
1423	os_memset(&eapfail, 0, sizeof(eapfail));
1424	eapfail.code = EAP_CODE_FAILURE;
1425	eapfail.identifier = 0;
1426	eapfail.length = host_to_be16(sizeof(eapfail));
1427
1428	if (!radius_msg_add_eap(msg, (u8 *) &eapfail, sizeof(eapfail))) {
1429		RADIUS_DEBUG("Failed to add EAP-Message attribute");
1430	}
1431
1432	if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
1433		RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
1434		radius_msg_free(msg);
1435		return -1;
1436	}
1437
1438	if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
1439				  client->shared_secret_len,
1440				  hdr->authenticator) <
1441	    0) {
1442		RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
1443	}
1444
1445	if (wpa_debug_level <= MSG_MSGDUMP) {
1446		radius_msg_dump(msg);
1447	}
1448
1449	data->counters.access_rejects++;
1450	client->counters.access_rejects++;
1451	buf = radius_msg_get_buf(msg);
1452	if (sendto(data->auth_sock, wpabuf_head(buf), wpabuf_len(buf), 0,
1453		   (struct sockaddr *) from, sizeof(*from)) < 0) {
1454		wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s", strerror(errno));
1455		ret = -1;
1456	}
1457
1458	radius_msg_free(msg);
1459
1460	return ret;
1461}
1462
1463
1464static void radius_server_hs20_t_c_check(struct radius_session *sess,
1465					 struct radius_msg *msg)
1466{
1467#ifdef CONFIG_HS20
1468	u8 *buf, *pos, *end, type, sublen, *timestamp = NULL;
1469	size_t len;
1470
1471	buf = NULL;
1472	for (;;) {
1473		if (radius_msg_get_attr_ptr(msg, RADIUS_ATTR_VENDOR_SPECIFIC,
1474					    &buf, &len, buf) < 0)
1475			break;
1476		if (len < 6)
1477			continue;
1478		pos = buf;
1479		end = buf + len;
1480		if (WPA_GET_BE32(pos) != RADIUS_VENDOR_ID_WFA)
1481			continue;
1482		pos += 4;
1483
1484		type = *pos++;
1485		sublen = *pos++;
1486		if (sublen < 2)
1487			continue; /* invalid length */
1488		sublen -= 2; /* skip header */
1489		if (pos + sublen > end)
1490			continue; /* invalid WFA VSA */
1491
1492		if (type == RADIUS_VENDOR_ATTR_WFA_HS20_TIMESTAMP && len >= 4) {
1493			timestamp = pos;
1494			break;
1495		}
1496	}
1497
1498	if (!timestamp)
1499		return;
1500	RADIUS_DEBUG("HS20-Timestamp: %u", WPA_GET_BE32(timestamp));
1501	if (sess->t_c_timestamp != WPA_GET_BE32(timestamp)) {
1502		RADIUS_DEBUG("Last read T&C timestamp does not match HS20-Timestamp --> require filtering");
1503		sess->t_c_filtering = 1;
1504	}
1505#endif /* CONFIG_HS20 */
1506}
1507
1508
1509static int radius_server_request(struct radius_server_data *data,
1510				 struct radius_msg *msg,
1511				 struct sockaddr *from, socklen_t fromlen,
1512				 struct radius_client *client,
1513				 const char *from_addr, int from_port,
1514				 struct radius_session *force_sess)
1515{
1516	struct wpabuf *eap = NULL;
1517	int res, state_included = 0;
1518	u8 statebuf[4];
1519	unsigned int state;
1520	struct radius_session *sess;
1521	struct radius_msg *reply;
1522	int is_complete = 0;
1523
1524	if (force_sess)
1525		sess = force_sess;
1526	else {
1527		res = radius_msg_get_attr(msg, RADIUS_ATTR_STATE, statebuf,
1528					  sizeof(statebuf));
1529		state_included = res >= 0;
1530		if (res == sizeof(statebuf)) {
1531			state = WPA_GET_BE32(statebuf);
1532			sess = radius_server_get_session(client, state);
1533		} else {
1534			sess = NULL;
1535		}
1536	}
1537
1538	if (sess) {
1539		RADIUS_DEBUG("Request for session 0x%x", sess->sess_id);
1540	} else if (state_included) {
1541		RADIUS_DEBUG("State attribute included but no session found");
1542		radius_server_reject(data, client, msg, from, fromlen,
1543				     from_addr, from_port);
1544		return -1;
1545	} else {
1546		sess = radius_server_get_new_session(data, client, msg,
1547						     from_addr);
1548		if (sess == NULL) {
1549			RADIUS_DEBUG("Could not create a new session");
1550			radius_server_reject(data, client, msg, from, fromlen,
1551					     from_addr, from_port);
1552			return -1;
1553		}
1554	}
1555
1556	if (sess->last_from_port == from_port &&
1557	    sess->last_identifier == radius_msg_get_hdr(msg)->identifier &&
1558	    os_memcmp(sess->last_authenticator,
1559		      radius_msg_get_hdr(msg)->authenticator, 16) == 0) {
1560		RADIUS_DEBUG("Duplicate message from %s", from_addr);
1561		data->counters.dup_access_requests++;
1562		client->counters.dup_access_requests++;
1563
1564		if (sess->last_reply) {
1565			struct wpabuf *buf;
1566			buf = radius_msg_get_buf(sess->last_reply);
1567			res = sendto(data->auth_sock, wpabuf_head(buf),
1568				     wpabuf_len(buf), 0,
1569				     (struct sockaddr *) from, fromlen);
1570			if (res < 0) {
1571				wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
1572					   strerror(errno));
1573			}
1574			return 0;
1575		}
1576
1577		RADIUS_DEBUG("No previous reply available for duplicate "
1578			     "message");
1579		return -1;
1580	}
1581
1582	eap = radius_msg_get_eap(msg);
1583	if (eap == NULL && sess->macacl) {
1584		reply = radius_server_macacl(data, client, sess, msg);
1585		if (reply == NULL)
1586			return -1;
1587		goto send_reply;
1588	}
1589	if (eap == NULL) {
1590		RADIUS_DEBUG("No EAP-Message in RADIUS packet from %s",
1591			     from_addr);
1592		data->counters.packets_dropped++;
1593		client->counters.packets_dropped++;
1594		return -1;
1595	}
1596
1597	RADIUS_DUMP("Received EAP data", wpabuf_head(eap), wpabuf_len(eap));
1598
1599	/* FIX: if Code is Request, Success, or Failure, send Access-Reject;
1600	 * RFC3579 Sect. 2.6.2.
1601	 * Include EAP-Response/Nak with no preferred method if
1602	 * code == request.
1603	 * If code is not 1-4, discard the packet silently.
1604	 * Or is this already done by the EAP state machine? */
1605
1606	wpabuf_free(sess->eap_if->eapRespData);
1607	sess->eap_if->eapRespData = eap;
1608	sess->eap_if->eapResp = TRUE;
1609	eap_server_sm_step(sess->eap);
1610
1611	if ((sess->eap_if->eapReq || sess->eap_if->eapSuccess ||
1612	     sess->eap_if->eapFail) && sess->eap_if->eapReqData) {
1613		RADIUS_DUMP("EAP data from the state machine",
1614			    wpabuf_head(sess->eap_if->eapReqData),
1615			    wpabuf_len(sess->eap_if->eapReqData));
1616	} else if (sess->eap_if->eapFail) {
1617		RADIUS_DEBUG("No EAP data from the state machine, but eapFail "
1618			     "set");
1619	} else if (eap_sm_method_pending(sess->eap)) {
1620		radius_msg_free(sess->last_msg);
1621		sess->last_msg = msg;
1622		sess->last_from_port = from_port;
1623		os_free(sess->last_from_addr);
1624		sess->last_from_addr = os_strdup(from_addr);
1625		sess->last_fromlen = fromlen;
1626		os_memcpy(&sess->last_from, from, fromlen);
1627		return -2;
1628	} else {
1629		RADIUS_DEBUG("No EAP data from the state machine - ignore this"
1630			     " Access-Request silently (assuming it was a "
1631			     "duplicate)");
1632		data->counters.packets_dropped++;
1633		client->counters.packets_dropped++;
1634		return -1;
1635	}
1636
1637	if (sess->eap_if->eapSuccess || sess->eap_if->eapFail)
1638		is_complete = 1;
1639	if (sess->eap_if->eapFail) {
1640		srv_log(sess, "EAP authentication failed");
1641		db_update_last_msk(sess, "FAIL");
1642	} else if (sess->eap_if->eapSuccess) {
1643		srv_log(sess, "EAP authentication succeeded");
1644	}
1645
1646	if (sess->eap_if->eapSuccess)
1647		radius_server_hs20_t_c_check(sess, msg);
1648
1649	reply = radius_server_encapsulate_eap(data, client, sess, msg);
1650
1651send_reply:
1652	if (reply) {
1653		struct wpabuf *buf;
1654		struct radius_hdr *hdr;
1655
1656		RADIUS_DEBUG("Reply to %s:%d", from_addr, from_port);
1657		if (wpa_debug_level <= MSG_MSGDUMP) {
1658			radius_msg_dump(reply);
1659		}
1660
1661		switch (radius_msg_get_hdr(reply)->code) {
1662		case RADIUS_CODE_ACCESS_ACCEPT:
1663			srv_log(sess, "Sending Access-Accept");
1664			data->counters.access_accepts++;
1665			client->counters.access_accepts++;
1666			break;
1667		case RADIUS_CODE_ACCESS_REJECT:
1668			srv_log(sess, "Sending Access-Reject");
1669			data->counters.access_rejects++;
1670			client->counters.access_rejects++;
1671			break;
1672		case RADIUS_CODE_ACCESS_CHALLENGE:
1673			data->counters.access_challenges++;
1674			client->counters.access_challenges++;
1675			break;
1676		}
1677		buf = radius_msg_get_buf(reply);
1678		res = sendto(data->auth_sock, wpabuf_head(buf),
1679			     wpabuf_len(buf), 0,
1680			     (struct sockaddr *) from, fromlen);
1681		if (res < 0) {
1682			wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
1683				   strerror(errno));
1684		}
1685		radius_msg_free(sess->last_reply);
1686		sess->last_reply = reply;
1687		sess->last_from_port = from_port;
1688		hdr = radius_msg_get_hdr(msg);
1689		sess->last_identifier = hdr->identifier;
1690		os_memcpy(sess->last_authenticator, hdr->authenticator, 16);
1691	} else {
1692		data->counters.packets_dropped++;
1693		client->counters.packets_dropped++;
1694	}
1695
1696	if (is_complete) {
1697		RADIUS_DEBUG("Removing completed session 0x%x after timeout",
1698			     sess->sess_id);
1699		eloop_cancel_timeout(radius_server_session_remove_timeout,
1700				     data, sess);
1701		eloop_register_timeout(RADIUS_SESSION_MAINTAIN, 0,
1702				       radius_server_session_remove_timeout,
1703				       data, sess);
1704	}
1705
1706	return 0;
1707}
1708
1709
1710static void
1711radius_server_receive_disconnect_resp(struct radius_server_data *data,
1712				      struct radius_client *client,
1713				      struct radius_msg *msg, int ack)
1714{
1715	struct radius_hdr *hdr;
1716
1717	if (!client->pending_dac_disconnect_req) {
1718		RADIUS_DEBUG("Ignore unexpected Disconnect response");
1719		radius_msg_free(msg);
1720		return;
1721	}
1722
1723	hdr = radius_msg_get_hdr(msg);
1724	if (hdr->identifier != client->pending_dac_disconnect_id) {
1725		RADIUS_DEBUG("Ignore unexpected Disconnect response with unexpected identifier %u (expected %u)",
1726			     hdr->identifier,
1727			     client->pending_dac_disconnect_id);
1728		radius_msg_free(msg);
1729		return;
1730	}
1731
1732	if (radius_msg_verify(msg, (const u8 *) client->shared_secret,
1733			      client->shared_secret_len,
1734			      client->pending_dac_disconnect_req, 0)) {
1735		RADIUS_DEBUG("Ignore Disconnect response with invalid authenticator");
1736		radius_msg_free(msg);
1737		return;
1738	}
1739
1740	RADIUS_DEBUG("Disconnect-%s received for " MACSTR,
1741		     ack ? "ACK" : "NAK",
1742		     MAC2STR(client->pending_dac_disconnect_addr));
1743
1744	radius_msg_free(msg);
1745	radius_msg_free(client->pending_dac_disconnect_req);
1746	client->pending_dac_disconnect_req = NULL;
1747}
1748
1749
1750static void radius_server_receive_coa_resp(struct radius_server_data *data,
1751					   struct radius_client *client,
1752					   struct radius_msg *msg, int ack)
1753{
1754	struct radius_hdr *hdr;
1755#ifdef CONFIG_SQLITE
1756	char addrtxt[3 * ETH_ALEN];
1757	char *sql;
1758	int res;
1759#endif /* CONFIG_SQLITE */
1760
1761	if (!client->pending_dac_coa_req) {
1762		RADIUS_DEBUG("Ignore unexpected CoA response");
1763		radius_msg_free(msg);
1764		return;
1765	}
1766
1767	hdr = radius_msg_get_hdr(msg);
1768	if (hdr->identifier != client->pending_dac_coa_id) {
1769		RADIUS_DEBUG("Ignore unexpected CoA response with unexpected identifier %u (expected %u)",
1770			     hdr->identifier,
1771			     client->pending_dac_coa_id);
1772		radius_msg_free(msg);
1773		return;
1774	}
1775
1776	if (radius_msg_verify(msg, (const u8 *) client->shared_secret,
1777			      client->shared_secret_len,
1778			      client->pending_dac_coa_req, 0)) {
1779		RADIUS_DEBUG("Ignore CoA response with invalid authenticator");
1780		radius_msg_free(msg);
1781		return;
1782	}
1783
1784	RADIUS_DEBUG("CoA-%s received for " MACSTR,
1785		     ack ? "ACK" : "NAK",
1786		     MAC2STR(client->pending_dac_coa_addr));
1787
1788	radius_msg_free(msg);
1789	radius_msg_free(client->pending_dac_coa_req);
1790	client->pending_dac_coa_req = NULL;
1791
1792#ifdef CONFIG_SQLITE
1793	if (!data->db)
1794		return;
1795
1796	os_snprintf(addrtxt, sizeof(addrtxt), MACSTR,
1797		    MAC2STR(client->pending_dac_coa_addr));
1798
1799	if (ack) {
1800		sql = sqlite3_mprintf("UPDATE current_sessions SET hs20_t_c_filtering=0, waiting_coa_ack=0, coa_ack_received=1 WHERE mac_addr=%Q",
1801				      addrtxt);
1802	} else {
1803		sql = sqlite3_mprintf("UPDATE current_sessions SET waiting_coa_ack=0 WHERE mac_addr=%Q",
1804				      addrtxt);
1805	}
1806	if (!sql)
1807		return;
1808
1809	res = sqlite3_exec(data->db, sql, NULL, NULL, NULL);
1810	sqlite3_free(sql);
1811	if (res != SQLITE_OK) {
1812		RADIUS_ERROR("Failed to update current_sessions entry: %s",
1813			     sqlite3_errmsg(data->db));
1814		return;
1815	}
1816#endif /* CONFIG_SQLITE */
1817}
1818
1819
1820static void radius_server_receive_auth(int sock, void *eloop_ctx,
1821				       void *sock_ctx)
1822{
1823	struct radius_server_data *data = eloop_ctx;
1824	u8 *buf = NULL;
1825	union {
1826		struct sockaddr_storage ss;
1827		struct sockaddr_in sin;
1828#ifdef CONFIG_IPV6
1829		struct sockaddr_in6 sin6;
1830#endif /* CONFIG_IPV6 */
1831	} from;
1832	socklen_t fromlen;
1833	int len;
1834	struct radius_client *client = NULL;
1835	struct radius_msg *msg = NULL;
1836	char abuf[50];
1837	int from_port = 0;
1838
1839	buf = os_malloc(RADIUS_MAX_MSG_LEN);
1840	if (buf == NULL) {
1841		goto fail;
1842	}
1843
1844	fromlen = sizeof(from);
1845	len = recvfrom(sock, buf, RADIUS_MAX_MSG_LEN, 0,
1846		       (struct sockaddr *) &from.ss, &fromlen);
1847	if (len < 0) {
1848		wpa_printf(MSG_INFO, "recvfrom[radius_server]: %s",
1849			   strerror(errno));
1850		goto fail;
1851	}
1852
1853#ifdef CONFIG_IPV6
1854	if (data->ipv6) {
1855		if (inet_ntop(AF_INET6, &from.sin6.sin6_addr, abuf,
1856			      sizeof(abuf)) == NULL)
1857			abuf[0] = '\0';
1858		from_port = ntohs(from.sin6.sin6_port);
1859		RADIUS_DEBUG("Received %d bytes from %s:%d",
1860			     len, abuf, from_port);
1861
1862		client = radius_server_get_client(data,
1863						  (struct in_addr *)
1864						  &from.sin6.sin6_addr, 1);
1865	}
1866#endif /* CONFIG_IPV6 */
1867
1868	if (!data->ipv6) {
1869		os_strlcpy(abuf, inet_ntoa(from.sin.sin_addr), sizeof(abuf));
1870		from_port = ntohs(from.sin.sin_port);
1871		RADIUS_DEBUG("Received %d bytes from %s:%d",
1872			     len, abuf, from_port);
1873
1874		client = radius_server_get_client(data, &from.sin.sin_addr, 0);
1875	}
1876
1877	RADIUS_DUMP("Received data", buf, len);
1878
1879	if (client == NULL) {
1880		RADIUS_DEBUG("Unknown client %s - packet ignored", abuf);
1881		data->counters.invalid_requests++;
1882		goto fail;
1883	}
1884
1885	msg = radius_msg_parse(buf, len);
1886	if (msg == NULL) {
1887		RADIUS_DEBUG("Parsing incoming RADIUS frame failed");
1888		data->counters.malformed_access_requests++;
1889		client->counters.malformed_access_requests++;
1890		goto fail;
1891	}
1892
1893	os_free(buf);
1894	buf = NULL;
1895
1896	if (wpa_debug_level <= MSG_MSGDUMP) {
1897		radius_msg_dump(msg);
1898	}
1899
1900	if (radius_msg_get_hdr(msg)->code == RADIUS_CODE_DISCONNECT_ACK) {
1901		radius_server_receive_disconnect_resp(data, client, msg, 1);
1902		return;
1903	}
1904
1905	if (radius_msg_get_hdr(msg)->code == RADIUS_CODE_DISCONNECT_NAK) {
1906		radius_server_receive_disconnect_resp(data, client, msg, 0);
1907		return;
1908	}
1909
1910	if (radius_msg_get_hdr(msg)->code == RADIUS_CODE_COA_ACK) {
1911		radius_server_receive_coa_resp(data, client, msg, 1);
1912		return;
1913	}
1914
1915	if (radius_msg_get_hdr(msg)->code == RADIUS_CODE_COA_NAK) {
1916		radius_server_receive_coa_resp(data, client, msg, 0);
1917		return;
1918	}
1919
1920	if (radius_msg_get_hdr(msg)->code != RADIUS_CODE_ACCESS_REQUEST) {
1921		RADIUS_DEBUG("Unexpected RADIUS code %d",
1922			     radius_msg_get_hdr(msg)->code);
1923		data->counters.unknown_types++;
1924		client->counters.unknown_types++;
1925		goto fail;
1926	}
1927
1928	data->counters.access_requests++;
1929	client->counters.access_requests++;
1930
1931	if (radius_msg_verify_msg_auth(msg, (u8 *) client->shared_secret,
1932				       client->shared_secret_len, NULL)) {
1933		RADIUS_DEBUG("Invalid Message-Authenticator from %s", abuf);
1934		data->counters.bad_authenticators++;
1935		client->counters.bad_authenticators++;
1936		goto fail;
1937	}
1938
1939	if (radius_server_request(data, msg, (struct sockaddr *) &from,
1940				  fromlen, client, abuf, from_port, NULL) ==
1941	    -2)
1942		return; /* msg was stored with the session */
1943
1944fail:
1945	radius_msg_free(msg);
1946	os_free(buf);
1947}
1948
1949
1950static void radius_server_receive_acct(int sock, void *eloop_ctx,
1951				       void *sock_ctx)
1952{
1953	struct radius_server_data *data = eloop_ctx;
1954	u8 *buf = NULL;
1955	union {
1956		struct sockaddr_storage ss;
1957		struct sockaddr_in sin;
1958#ifdef CONFIG_IPV6
1959		struct sockaddr_in6 sin6;
1960#endif /* CONFIG_IPV6 */
1961	} from;
1962	socklen_t fromlen;
1963	int len, res;
1964	struct radius_client *client = NULL;
1965	struct radius_msg *msg = NULL, *resp = NULL;
1966	char abuf[50];
1967	int from_port = 0;
1968	struct radius_hdr *hdr;
1969	struct wpabuf *rbuf;
1970
1971	buf = os_malloc(RADIUS_MAX_MSG_LEN);
1972	if (buf == NULL) {
1973		goto fail;
1974	}
1975
1976	fromlen = sizeof(from);
1977	len = recvfrom(sock, buf, RADIUS_MAX_MSG_LEN, 0,
1978		       (struct sockaddr *) &from.ss, &fromlen);
1979	if (len < 0) {
1980		wpa_printf(MSG_INFO, "recvfrom[radius_server]: %s",
1981			   strerror(errno));
1982		goto fail;
1983	}
1984
1985#ifdef CONFIG_IPV6
1986	if (data->ipv6) {
1987		if (inet_ntop(AF_INET6, &from.sin6.sin6_addr, abuf,
1988			      sizeof(abuf)) == NULL)
1989			abuf[0] = '\0';
1990		from_port = ntohs(from.sin6.sin6_port);
1991		RADIUS_DEBUG("Received %d bytes from %s:%d",
1992			     len, abuf, from_port);
1993
1994		client = radius_server_get_client(data,
1995						  (struct in_addr *)
1996						  &from.sin6.sin6_addr, 1);
1997	}
1998#endif /* CONFIG_IPV6 */
1999
2000	if (!data->ipv6) {
2001		os_strlcpy(abuf, inet_ntoa(from.sin.sin_addr), sizeof(abuf));
2002		from_port = ntohs(from.sin.sin_port);
2003		RADIUS_DEBUG("Received %d bytes from %s:%d",
2004			     len, abuf, from_port);
2005
2006		client = radius_server_get_client(data, &from.sin.sin_addr, 0);
2007	}
2008
2009	RADIUS_DUMP("Received data", buf, len);
2010
2011	if (client == NULL) {
2012		RADIUS_DEBUG("Unknown client %s - packet ignored", abuf);
2013		data->counters.invalid_acct_requests++;
2014		goto fail;
2015	}
2016
2017	msg = radius_msg_parse(buf, len);
2018	if (msg == NULL) {
2019		RADIUS_DEBUG("Parsing incoming RADIUS frame failed");
2020		data->counters.malformed_acct_requests++;
2021		client->counters.malformed_acct_requests++;
2022		goto fail;
2023	}
2024
2025	os_free(buf);
2026	buf = NULL;
2027
2028	if (wpa_debug_level <= MSG_MSGDUMP) {
2029		radius_msg_dump(msg);
2030	}
2031
2032	if (radius_msg_get_hdr(msg)->code != RADIUS_CODE_ACCOUNTING_REQUEST) {
2033		RADIUS_DEBUG("Unexpected RADIUS code %d",
2034			     radius_msg_get_hdr(msg)->code);
2035		data->counters.unknown_acct_types++;
2036		client->counters.unknown_acct_types++;
2037		goto fail;
2038	}
2039
2040	data->counters.acct_requests++;
2041	client->counters.acct_requests++;
2042
2043	if (radius_msg_verify_acct_req(msg, (u8 *) client->shared_secret,
2044				       client->shared_secret_len)) {
2045		RADIUS_DEBUG("Invalid Authenticator from %s", abuf);
2046		data->counters.acct_bad_authenticators++;
2047		client->counters.acct_bad_authenticators++;
2048		goto fail;
2049	}
2050
2051	/* TODO: Write accounting information to a file or database */
2052
2053	hdr = radius_msg_get_hdr(msg);
2054
2055	resp = radius_msg_new(RADIUS_CODE_ACCOUNTING_RESPONSE, hdr->identifier);
2056	if (resp == NULL)
2057		goto fail;
2058
2059	radius_msg_finish_acct_resp(resp, (u8 *) client->shared_secret,
2060				    client->shared_secret_len,
2061				    hdr->authenticator);
2062
2063	RADIUS_DEBUG("Reply to %s:%d", abuf, from_port);
2064	if (wpa_debug_level <= MSG_MSGDUMP) {
2065		radius_msg_dump(resp);
2066	}
2067	rbuf = radius_msg_get_buf(resp);
2068	data->counters.acct_responses++;
2069	client->counters.acct_responses++;
2070	res = sendto(data->acct_sock, wpabuf_head(rbuf), wpabuf_len(rbuf), 0,
2071		     (struct sockaddr *) &from.ss, fromlen);
2072	if (res < 0) {
2073		wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
2074			   strerror(errno));
2075	}
2076
2077fail:
2078	radius_msg_free(resp);
2079	radius_msg_free(msg);
2080	os_free(buf);
2081}
2082
2083
2084static int radius_server_disable_pmtu_discovery(int s)
2085{
2086	int r = -1;
2087#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2088	/* Turn off Path MTU discovery on IPv4/UDP sockets. */
2089	int action = IP_PMTUDISC_DONT;
2090	r = setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &action,
2091		       sizeof(action));
2092	if (r == -1)
2093		wpa_printf(MSG_ERROR, "Failed to set IP_MTU_DISCOVER: "
2094			   "%s", strerror(errno));
2095#endif
2096	return r;
2097}
2098
2099
2100static int radius_server_open_socket(int port)
2101{
2102	int s;
2103	struct sockaddr_in addr;
2104
2105	s = socket(PF_INET, SOCK_DGRAM, 0);
2106	if (s < 0) {
2107		wpa_printf(MSG_INFO, "RADIUS: socket: %s", strerror(errno));
2108		return -1;
2109	}
2110
2111	radius_server_disable_pmtu_discovery(s);
2112
2113	os_memset(&addr, 0, sizeof(addr));
2114	addr.sin_family = AF_INET;
2115	addr.sin_port = htons(port);
2116	if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
2117		wpa_printf(MSG_INFO, "RADIUS: bind: %s", strerror(errno));
2118		close(s);
2119		return -1;
2120	}
2121
2122	return s;
2123}
2124
2125
2126#ifdef CONFIG_IPV6
2127static int radius_server_open_socket6(int port)
2128{
2129	int s;
2130	struct sockaddr_in6 addr;
2131
2132	s = socket(PF_INET6, SOCK_DGRAM, 0);
2133	if (s < 0) {
2134		wpa_printf(MSG_INFO, "RADIUS: socket[IPv6]: %s",
2135			   strerror(errno));
2136		return -1;
2137	}
2138
2139	os_memset(&addr, 0, sizeof(addr));
2140	addr.sin6_family = AF_INET6;
2141	os_memcpy(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any));
2142	addr.sin6_port = htons(port);
2143	if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
2144		wpa_printf(MSG_INFO, "RADIUS: bind: %s", strerror(errno));
2145		close(s);
2146		return -1;
2147	}
2148
2149	return s;
2150}
2151#endif /* CONFIG_IPV6 */
2152
2153
2154static void radius_server_free_sessions(struct radius_server_data *data,
2155					struct radius_session *sessions)
2156{
2157	struct radius_session *session, *prev;
2158
2159	session = sessions;
2160	while (session) {
2161		prev = session;
2162		session = session->next;
2163		radius_server_session_free(data, prev);
2164	}
2165}
2166
2167
2168static void radius_server_free_clients(struct radius_server_data *data,
2169				       struct radius_client *clients)
2170{
2171	struct radius_client *client, *prev;
2172
2173	client = clients;
2174	while (client) {
2175		prev = client;
2176		client = client->next;
2177
2178		radius_server_free_sessions(data, prev->sessions);
2179		os_free(prev->shared_secret);
2180		radius_msg_free(prev->pending_dac_coa_req);
2181		radius_msg_free(prev->pending_dac_disconnect_req);
2182		os_free(prev);
2183	}
2184}
2185
2186
2187static struct radius_client *
2188radius_server_read_clients(const char *client_file, int ipv6)
2189{
2190	FILE *f;
2191	const int buf_size = 1024;
2192	char *buf, *pos;
2193	struct radius_client *clients, *tail, *entry;
2194	int line = 0, mask, failed = 0, i;
2195	struct in_addr addr;
2196#ifdef CONFIG_IPV6
2197	struct in6_addr addr6;
2198#endif /* CONFIG_IPV6 */
2199	unsigned int val;
2200
2201	f = fopen(client_file, "r");
2202	if (f == NULL) {
2203		RADIUS_ERROR("Could not open client file '%s'", client_file);
2204		return NULL;
2205	}
2206
2207	buf = os_malloc(buf_size);
2208	if (buf == NULL) {
2209		fclose(f);
2210		return NULL;
2211	}
2212
2213	clients = tail = NULL;
2214	while (fgets(buf, buf_size, f)) {
2215		/* Configuration file format:
2216		 * 192.168.1.0/24 secret
2217		 * 192.168.1.2 secret
2218		 * fe80::211:22ff:fe33:4455/64 secretipv6
2219		 */
2220		line++;
2221		buf[buf_size - 1] = '\0';
2222		pos = buf;
2223		while (*pos != '\0' && *pos != '\n')
2224			pos++;
2225		if (*pos == '\n')
2226			*pos = '\0';
2227		if (*buf == '\0' || *buf == '#')
2228			continue;
2229
2230		pos = buf;
2231		while ((*pos >= '0' && *pos <= '9') || *pos == '.' ||
2232		       (*pos >= 'a' && *pos <= 'f') || *pos == ':' ||
2233		       (*pos >= 'A' && *pos <= 'F')) {
2234			pos++;
2235		}
2236
2237		if (*pos == '\0') {
2238			failed = 1;
2239			break;
2240		}
2241
2242		if (*pos == '/') {
2243			char *end;
2244			*pos++ = '\0';
2245			mask = strtol(pos, &end, 10);
2246			if ((pos == end) ||
2247			    (mask < 0 || mask > (ipv6 ? 128 : 32))) {
2248				failed = 1;
2249				break;
2250			}
2251			pos = end;
2252		} else {
2253			mask = ipv6 ? 128 : 32;
2254			*pos++ = '\0';
2255		}
2256
2257		if (!ipv6 && inet_aton(buf, &addr) == 0) {
2258			failed = 1;
2259			break;
2260		}
2261#ifdef CONFIG_IPV6
2262		if (ipv6 && inet_pton(AF_INET6, buf, &addr6) <= 0) {
2263			if (inet_pton(AF_INET, buf, &addr) <= 0) {
2264				failed = 1;
2265				break;
2266			}
2267			/* Convert IPv4 address to IPv6 */
2268			if (mask <= 32)
2269				mask += (128 - 32);
2270			os_memset(addr6.s6_addr, 0, 10);
2271			addr6.s6_addr[10] = 0xff;
2272			addr6.s6_addr[11] = 0xff;
2273			os_memcpy(addr6.s6_addr + 12, (char *) &addr.s_addr,
2274				  4);
2275		}
2276#endif /* CONFIG_IPV6 */
2277
2278		while (*pos == ' ' || *pos == '\t') {
2279			pos++;
2280		}
2281
2282		if (*pos == '\0') {
2283			failed = 1;
2284			break;
2285		}
2286
2287		entry = os_zalloc(sizeof(*entry));
2288		if (entry == NULL) {
2289			failed = 1;
2290			break;
2291		}
2292		entry->shared_secret = os_strdup(pos);
2293		if (entry->shared_secret == NULL) {
2294			failed = 1;
2295			os_free(entry);
2296			break;
2297		}
2298		entry->shared_secret_len = os_strlen(entry->shared_secret);
2299		if (!ipv6) {
2300			entry->addr.s_addr = addr.s_addr;
2301			val = 0;
2302			for (i = 0; i < mask; i++)
2303				val |= 1U << (31 - i);
2304			entry->mask.s_addr = htonl(val);
2305		}
2306#ifdef CONFIG_IPV6
2307		if (ipv6) {
2308			int offset = mask / 8;
2309
2310			os_memcpy(entry->addr6.s6_addr, addr6.s6_addr, 16);
2311			os_memset(entry->mask6.s6_addr, 0xff, offset);
2312			val = 0;
2313			for (i = 0; i < (mask % 8); i++)
2314				val |= 1 << (7 - i);
2315			if (offset < 16)
2316				entry->mask6.s6_addr[offset] = val;
2317		}
2318#endif /* CONFIG_IPV6 */
2319
2320		if (tail == NULL) {
2321			clients = tail = entry;
2322		} else {
2323			tail->next = entry;
2324			tail = entry;
2325		}
2326	}
2327
2328	if (failed) {
2329		RADIUS_ERROR("Invalid line %d in '%s'", line, client_file);
2330		radius_server_free_clients(NULL, clients);
2331		clients = NULL;
2332	}
2333
2334	os_free(buf);
2335	fclose(f);
2336
2337	return clients;
2338}
2339
2340
2341/**
2342 * radius_server_init - Initialize RADIUS server
2343 * @conf: Configuration for the RADIUS server
2344 * Returns: Pointer to private RADIUS server context or %NULL on failure
2345 *
2346 * This initializes a RADIUS server instance and returns a context pointer that
2347 * will be used in other calls to the RADIUS server module. The server can be
2348 * deinitialize by calling radius_server_deinit().
2349 */
2350struct radius_server_data *
2351radius_server_init(struct radius_server_conf *conf)
2352{
2353	struct radius_server_data *data;
2354
2355#ifndef CONFIG_IPV6
2356	if (conf->ipv6) {
2357		wpa_printf(MSG_ERROR, "RADIUS server compiled without IPv6 support");
2358		return NULL;
2359	}
2360#endif /* CONFIG_IPV6 */
2361
2362	data = os_zalloc(sizeof(*data));
2363	if (data == NULL)
2364		return NULL;
2365
2366	data->auth_sock = -1;
2367	data->acct_sock = -1;
2368	dl_list_init(&data->erp_keys);
2369	os_get_reltime(&data->start_time);
2370	data->conf_ctx = conf->conf_ctx;
2371	data->eap_sim_db_priv = conf->eap_sim_db_priv;
2372	data->ssl_ctx = conf->ssl_ctx;
2373	data->msg_ctx = conf->msg_ctx;
2374	data->ipv6 = conf->ipv6;
2375	if (conf->pac_opaque_encr_key) {
2376		data->pac_opaque_encr_key = os_malloc(16);
2377		if (data->pac_opaque_encr_key) {
2378			os_memcpy(data->pac_opaque_encr_key,
2379				  conf->pac_opaque_encr_key, 16);
2380		}
2381	}
2382	if (conf->eap_fast_a_id) {
2383		data->eap_fast_a_id = os_malloc(conf->eap_fast_a_id_len);
2384		if (data->eap_fast_a_id) {
2385			os_memcpy(data->eap_fast_a_id, conf->eap_fast_a_id,
2386				  conf->eap_fast_a_id_len);
2387			data->eap_fast_a_id_len = conf->eap_fast_a_id_len;
2388		}
2389	}
2390	if (conf->eap_fast_a_id_info)
2391		data->eap_fast_a_id_info = os_strdup(conf->eap_fast_a_id_info);
2392	data->eap_fast_prov = conf->eap_fast_prov;
2393	data->pac_key_lifetime = conf->pac_key_lifetime;
2394	data->pac_key_refresh_time = conf->pac_key_refresh_time;
2395	data->eap_teap_auth = conf->eap_teap_auth;
2396	data->eap_teap_pac_no_inner = conf->eap_teap_pac_no_inner;
2397	data->get_eap_user = conf->get_eap_user;
2398	data->eap_sim_aka_result_ind = conf->eap_sim_aka_result_ind;
2399	data->eap_sim_id = conf->eap_sim_id;
2400	data->tnc = conf->tnc;
2401	data->wps = conf->wps;
2402	data->pwd_group = conf->pwd_group;
2403	data->server_id = conf->server_id;
2404	if (conf->eap_req_id_text) {
2405		data->eap_req_id_text = os_malloc(conf->eap_req_id_text_len);
2406		if (data->eap_req_id_text) {
2407			os_memcpy(data->eap_req_id_text, conf->eap_req_id_text,
2408				  conf->eap_req_id_text_len);
2409			data->eap_req_id_text_len = conf->eap_req_id_text_len;
2410		}
2411	}
2412	data->erp = conf->erp;
2413	data->erp_domain = conf->erp_domain;
2414	data->tls_session_lifetime = conf->tls_session_lifetime;
2415	data->tls_flags = conf->tls_flags;
2416
2417	if (conf->subscr_remediation_url) {
2418		data->subscr_remediation_url =
2419			os_strdup(conf->subscr_remediation_url);
2420	}
2421	data->subscr_remediation_method = conf->subscr_remediation_method;
2422	if (conf->hs20_sim_provisioning_url)
2423		data->hs20_sim_provisioning_url =
2424			os_strdup(conf->hs20_sim_provisioning_url);
2425
2426	if (conf->t_c_server_url)
2427		data->t_c_server_url = os_strdup(conf->t_c_server_url);
2428
2429#ifdef CONFIG_SQLITE
2430	if (conf->sqlite_file) {
2431		if (sqlite3_open(conf->sqlite_file, &data->db)) {
2432			RADIUS_ERROR("Could not open SQLite file '%s'",
2433				     conf->sqlite_file);
2434			radius_server_deinit(data);
2435			return NULL;
2436		}
2437	}
2438#endif /* CONFIG_SQLITE */
2439
2440#ifdef CONFIG_RADIUS_TEST
2441	if (conf->dump_msk_file)
2442		data->dump_msk_file = os_strdup(conf->dump_msk_file);
2443#endif /* CONFIG_RADIUS_TEST */
2444
2445	data->clients = radius_server_read_clients(conf->client_file,
2446						   conf->ipv6);
2447	if (data->clients == NULL) {
2448		wpa_printf(MSG_ERROR, "No RADIUS clients configured");
2449		radius_server_deinit(data);
2450		return NULL;
2451	}
2452
2453#ifdef CONFIG_IPV6
2454	if (conf->ipv6)
2455		data->auth_sock = radius_server_open_socket6(conf->auth_port);
2456	else
2457#endif /* CONFIG_IPV6 */
2458	data->auth_sock = radius_server_open_socket(conf->auth_port);
2459	if (data->auth_sock < 0) {
2460		wpa_printf(MSG_ERROR, "Failed to open UDP socket for RADIUS authentication server");
2461		radius_server_deinit(data);
2462		return NULL;
2463	}
2464	if (eloop_register_read_sock(data->auth_sock,
2465				     radius_server_receive_auth,
2466				     data, NULL)) {
2467		radius_server_deinit(data);
2468		return NULL;
2469	}
2470
2471	if (conf->acct_port) {
2472#ifdef CONFIG_IPV6
2473		if (conf->ipv6)
2474			data->acct_sock = radius_server_open_socket6(
2475				conf->acct_port);
2476		else
2477#endif /* CONFIG_IPV6 */
2478		data->acct_sock = radius_server_open_socket(conf->acct_port);
2479		if (data->acct_sock < 0) {
2480			wpa_printf(MSG_ERROR, "Failed to open UDP socket for RADIUS accounting server");
2481			radius_server_deinit(data);
2482			return NULL;
2483		}
2484		if (eloop_register_read_sock(data->acct_sock,
2485					     radius_server_receive_acct,
2486					     data, NULL)) {
2487			radius_server_deinit(data);
2488			return NULL;
2489		}
2490	} else {
2491		data->acct_sock = -1;
2492	}
2493
2494	return data;
2495}
2496
2497
2498/**
2499 * radius_server_erp_flush - Flush all ERP keys
2500 * @data: RADIUS server context from radius_server_init()
2501 */
2502void radius_server_erp_flush(struct radius_server_data *data)
2503{
2504	struct eap_server_erp_key *erp;
2505
2506	if (data == NULL)
2507		return;
2508	while ((erp = dl_list_first(&data->erp_keys, struct eap_server_erp_key,
2509				    list)) != NULL) {
2510		dl_list_del(&erp->list);
2511		bin_clear_free(erp, sizeof(*erp));
2512	}
2513}
2514
2515
2516/**
2517 * radius_server_deinit - Deinitialize RADIUS server
2518 * @data: RADIUS server context from radius_server_init()
2519 */
2520void radius_server_deinit(struct radius_server_data *data)
2521{
2522	if (data == NULL)
2523		return;
2524
2525	if (data->auth_sock >= 0) {
2526		eloop_unregister_read_sock(data->auth_sock);
2527		close(data->auth_sock);
2528	}
2529
2530	if (data->acct_sock >= 0) {
2531		eloop_unregister_read_sock(data->acct_sock);
2532		close(data->acct_sock);
2533	}
2534
2535	radius_server_free_clients(data, data->clients);
2536
2537	os_free(data->pac_opaque_encr_key);
2538	os_free(data->eap_fast_a_id);
2539	os_free(data->eap_fast_a_id_info);
2540	os_free(data->eap_req_id_text);
2541#ifdef CONFIG_RADIUS_TEST
2542	os_free(data->dump_msk_file);
2543#endif /* CONFIG_RADIUS_TEST */
2544	os_free(data->subscr_remediation_url);
2545	os_free(data->hs20_sim_provisioning_url);
2546	os_free(data->t_c_server_url);
2547
2548#ifdef CONFIG_SQLITE
2549	if (data->db)
2550		sqlite3_close(data->db);
2551#endif /* CONFIG_SQLITE */
2552
2553	radius_server_erp_flush(data);
2554
2555	os_free(data);
2556}
2557
2558
2559/**
2560 * radius_server_get_mib - Get RADIUS server MIB information
2561 * @data: RADIUS server context from radius_server_init()
2562 * @buf: Buffer for returning the MIB data in text format
2563 * @buflen: buf length in octets
2564 * Returns: Number of octets written into buf
2565 */
2566int radius_server_get_mib(struct radius_server_data *data, char *buf,
2567			  size_t buflen)
2568{
2569	int ret, uptime;
2570	unsigned int idx;
2571	char *end, *pos;
2572	struct os_reltime now;
2573	struct radius_client *cli;
2574
2575	/* RFC 2619 - RADIUS Authentication Server MIB */
2576
2577	if (data == NULL || buflen == 0)
2578		return 0;
2579
2580	pos = buf;
2581	end = buf + buflen;
2582
2583	os_get_reltime(&now);
2584	uptime = (now.sec - data->start_time.sec) * 100 +
2585		((now.usec - data->start_time.usec) / 10000) % 100;
2586	ret = os_snprintf(pos, end - pos,
2587			  "RADIUS-AUTH-SERVER-MIB\n"
2588			  "radiusAuthServIdent=hostapd\n"
2589			  "radiusAuthServUpTime=%d\n"
2590			  "radiusAuthServResetTime=0\n"
2591			  "radiusAuthServConfigReset=4\n",
2592			  uptime);
2593	if (os_snprintf_error(end - pos, ret)) {
2594		*pos = '\0';
2595		return pos - buf;
2596	}
2597	pos += ret;
2598
2599	ret = os_snprintf(pos, end - pos,
2600			  "radiusAuthServTotalAccessRequests=%u\n"
2601			  "radiusAuthServTotalInvalidRequests=%u\n"
2602			  "radiusAuthServTotalDupAccessRequests=%u\n"
2603			  "radiusAuthServTotalAccessAccepts=%u\n"
2604			  "radiusAuthServTotalAccessRejects=%u\n"
2605			  "radiusAuthServTotalAccessChallenges=%u\n"
2606			  "radiusAuthServTotalMalformedAccessRequests=%u\n"
2607			  "radiusAuthServTotalBadAuthenticators=%u\n"
2608			  "radiusAuthServTotalPacketsDropped=%u\n"
2609			  "radiusAuthServTotalUnknownTypes=%u\n"
2610			  "radiusAccServTotalRequests=%u\n"
2611			  "radiusAccServTotalInvalidRequests=%u\n"
2612			  "radiusAccServTotalResponses=%u\n"
2613			  "radiusAccServTotalMalformedRequests=%u\n"
2614			  "radiusAccServTotalBadAuthenticators=%u\n"
2615			  "radiusAccServTotalUnknownTypes=%u\n",
2616			  data->counters.access_requests,
2617			  data->counters.invalid_requests,
2618			  data->counters.dup_access_requests,
2619			  data->counters.access_accepts,
2620			  data->counters.access_rejects,
2621			  data->counters.access_challenges,
2622			  data->counters.malformed_access_requests,
2623			  data->counters.bad_authenticators,
2624			  data->counters.packets_dropped,
2625			  data->counters.unknown_types,
2626			  data->counters.acct_requests,
2627			  data->counters.invalid_acct_requests,
2628			  data->counters.acct_responses,
2629			  data->counters.malformed_acct_requests,
2630			  data->counters.acct_bad_authenticators,
2631			  data->counters.unknown_acct_types);
2632	if (os_snprintf_error(end - pos, ret)) {
2633		*pos = '\0';
2634		return pos - buf;
2635	}
2636	pos += ret;
2637
2638	for (cli = data->clients, idx = 0; cli; cli = cli->next, idx++) {
2639		char abuf[50], mbuf[50];
2640#ifdef CONFIG_IPV6
2641		if (data->ipv6) {
2642			if (inet_ntop(AF_INET6, &cli->addr6, abuf,
2643				      sizeof(abuf)) == NULL)
2644				abuf[0] = '\0';
2645			if (inet_ntop(AF_INET6, &cli->mask6, mbuf,
2646				      sizeof(mbuf)) == NULL)
2647				mbuf[0] = '\0';
2648		}
2649#endif /* CONFIG_IPV6 */
2650		if (!data->ipv6) {
2651			os_strlcpy(abuf, inet_ntoa(cli->addr), sizeof(abuf));
2652			os_strlcpy(mbuf, inet_ntoa(cli->mask), sizeof(mbuf));
2653		}
2654
2655		ret = os_snprintf(pos, end - pos,
2656				  "radiusAuthClientIndex=%u\n"
2657				  "radiusAuthClientAddress=%s/%s\n"
2658				  "radiusAuthServAccessRequests=%u\n"
2659				  "radiusAuthServDupAccessRequests=%u\n"
2660				  "radiusAuthServAccessAccepts=%u\n"
2661				  "radiusAuthServAccessRejects=%u\n"
2662				  "radiusAuthServAccessChallenges=%u\n"
2663				  "radiusAuthServMalformedAccessRequests=%u\n"
2664				  "radiusAuthServBadAuthenticators=%u\n"
2665				  "radiusAuthServPacketsDropped=%u\n"
2666				  "radiusAuthServUnknownTypes=%u\n"
2667				  "radiusAccServTotalRequests=%u\n"
2668				  "radiusAccServTotalInvalidRequests=%u\n"
2669				  "radiusAccServTotalResponses=%u\n"
2670				  "radiusAccServTotalMalformedRequests=%u\n"
2671				  "radiusAccServTotalBadAuthenticators=%u\n"
2672				  "radiusAccServTotalUnknownTypes=%u\n",
2673				  idx,
2674				  abuf, mbuf,
2675				  cli->counters.access_requests,
2676				  cli->counters.dup_access_requests,
2677				  cli->counters.access_accepts,
2678				  cli->counters.access_rejects,
2679				  cli->counters.access_challenges,
2680				  cli->counters.malformed_access_requests,
2681				  cli->counters.bad_authenticators,
2682				  cli->counters.packets_dropped,
2683				  cli->counters.unknown_types,
2684				  cli->counters.acct_requests,
2685				  cli->counters.invalid_acct_requests,
2686				  cli->counters.acct_responses,
2687				  cli->counters.malformed_acct_requests,
2688				  cli->counters.acct_bad_authenticators,
2689				  cli->counters.unknown_acct_types);
2690		if (os_snprintf_error(end - pos, ret)) {
2691			*pos = '\0';
2692			return pos - buf;
2693		}
2694		pos += ret;
2695	}
2696
2697	return pos - buf;
2698}
2699
2700
2701static int radius_server_get_eap_user(void *ctx, const u8 *identity,
2702				      size_t identity_len, int phase2,
2703				      struct eap_user *user)
2704{
2705	struct radius_session *sess = ctx;
2706	struct radius_server_data *data = sess->server;
2707	int ret;
2708
2709	ret = data->get_eap_user(data->conf_ctx, identity, identity_len,
2710				 phase2, user);
2711	if (ret == 0 && user) {
2712		sess->accept_attr = user->accept_attr;
2713		sess->remediation = user->remediation;
2714		sess->macacl = user->macacl;
2715		sess->t_c_timestamp = user->t_c_timestamp;
2716	}
2717
2718	if (ret) {
2719		RADIUS_DEBUG("%s: User-Name not found from user database",
2720			     __func__);
2721	}
2722
2723	return ret;
2724}
2725
2726
2727static const char * radius_server_get_eap_req_id_text(void *ctx, size_t *len)
2728{
2729	struct radius_session *sess = ctx;
2730	struct radius_server_data *data = sess->server;
2731	*len = data->eap_req_id_text_len;
2732	return data->eap_req_id_text;
2733}
2734
2735
2736static void radius_server_log_msg(void *ctx, const char *msg)
2737{
2738	struct radius_session *sess = ctx;
2739	srv_log(sess, "EAP: %s", msg);
2740}
2741
2742
2743#ifdef CONFIG_ERP
2744
2745static const char * radius_server_get_erp_domain(void *ctx)
2746{
2747	struct radius_session *sess = ctx;
2748	struct radius_server_data *data = sess->server;
2749
2750	return data->erp_domain;
2751}
2752
2753
2754static struct eap_server_erp_key *
2755radius_server_erp_get_key(void *ctx, const char *keyname)
2756{
2757	struct radius_session *sess = ctx;
2758	struct radius_server_data *data = sess->server;
2759
2760	return radius_server_erp_find_key(data, keyname);
2761}
2762
2763
2764static int radius_server_erp_add_key(void *ctx, struct eap_server_erp_key *erp)
2765{
2766	struct radius_session *sess = ctx;
2767	struct radius_server_data *data = sess->server;
2768
2769	dl_list_add(&data->erp_keys, &erp->list);
2770	return 0;
2771}
2772
2773#endif /* CONFIG_ERP */
2774
2775
2776static const struct eapol_callbacks radius_server_eapol_cb =
2777{
2778	.get_eap_user = radius_server_get_eap_user,
2779	.get_eap_req_id_text = radius_server_get_eap_req_id_text,
2780	.log_msg = radius_server_log_msg,
2781#ifdef CONFIG_ERP
2782	.get_erp_send_reauth_start = NULL,
2783	.get_erp_domain = radius_server_get_erp_domain,
2784	.erp_get_key = radius_server_erp_get_key,
2785	.erp_add_key = radius_server_erp_add_key,
2786#endif /* CONFIG_ERP */
2787};
2788
2789
2790/**
2791 * radius_server_eap_pending_cb - Pending EAP data notification
2792 * @data: RADIUS server context from radius_server_init()
2793 * @ctx: Pending EAP context pointer
2794 *
2795 * This function is used to notify EAP server module that a pending operation
2796 * has been completed and processing of the EAP session can proceed.
2797 */
2798void radius_server_eap_pending_cb(struct radius_server_data *data, void *ctx)
2799{
2800	struct radius_client *cli;
2801	struct radius_session *s, *sess = NULL;
2802	struct radius_msg *msg;
2803
2804	if (data == NULL)
2805		return;
2806
2807	for (cli = data->clients; cli; cli = cli->next) {
2808		for (s = cli->sessions; s; s = s->next) {
2809			if (s->eap == ctx && s->last_msg) {
2810				sess = s;
2811				break;
2812			}
2813		}
2814		if (sess)
2815			break;
2816	}
2817
2818	if (sess == NULL) {
2819		RADIUS_DEBUG("No session matched callback ctx");
2820		return;
2821	}
2822
2823	msg = sess->last_msg;
2824	sess->last_msg = NULL;
2825	eap_sm_pending_cb(sess->eap);
2826	if (radius_server_request(data, msg,
2827				  (struct sockaddr *) &sess->last_from,
2828				  sess->last_fromlen, cli,
2829				  sess->last_from_addr,
2830				  sess->last_from_port, sess) == -2)
2831		return; /* msg was stored with the session */
2832
2833	radius_msg_free(msg);
2834}
2835
2836
2837#ifdef CONFIG_SQLITE
2838
2839struct db_session_fields {
2840	char *identity;
2841	char *nas;
2842	int hs20_t_c_filtering;
2843	int waiting_coa_ack;
2844	int coa_ack_received;
2845};
2846
2847
2848static int get_db_session_fields(void *ctx, int argc, char *argv[], char *col[])
2849{
2850	struct db_session_fields *fields = ctx;
2851	int i;
2852
2853	for (i = 0; i < argc; i++) {
2854		if (!argv[i])
2855			continue;
2856
2857		RADIUS_DEBUG("Session DB: %s=%s", col[i], argv[i]);
2858
2859		if (os_strcmp(col[i], "identity") == 0) {
2860			os_free(fields->identity);
2861			fields->identity = os_strdup(argv[i]);
2862		} else if (os_strcmp(col[i], "nas") == 0) {
2863			os_free(fields->nas);
2864			fields->nas = os_strdup(argv[i]);
2865		} else if (os_strcmp(col[i], "hs20_t_c_filtering") == 0) {
2866			fields->hs20_t_c_filtering = atoi(argv[i]);
2867		} else if (os_strcmp(col[i], "waiting_coa_ack") == 0) {
2868			fields->waiting_coa_ack = atoi(argv[i]);
2869		} else if (os_strcmp(col[i], "coa_ack_received") == 0) {
2870			fields->coa_ack_received = atoi(argv[i]);
2871		}
2872	}
2873
2874	return 0;
2875}
2876
2877
2878static void free_db_session_fields(struct db_session_fields *fields)
2879{
2880	os_free(fields->identity);
2881	fields->identity = NULL;
2882	os_free(fields->nas);
2883	fields->nas = NULL;
2884}
2885
2886#endif /* CONFIG_SQLITE */
2887
2888
2889int radius_server_dac_request(struct radius_server_data *data, const char *req)
2890{
2891#ifdef CONFIG_SQLITE
2892	char *sql;
2893	int res;
2894	int disconnect;
2895	const char *pos = req;
2896	u8 addr[ETH_ALEN];
2897	char addrtxt[3 * ETH_ALEN];
2898	int t_c_clear = 0;
2899	struct db_session_fields fields;
2900	struct sockaddr_in das;
2901	struct radius_client *client;
2902	struct radius_msg *msg;
2903	struct wpabuf *buf;
2904	u8 identifier;
2905	struct os_time now;
2906
2907	if (!data)
2908		return -1;
2909
2910	/* req: <disconnect|coa> <MAC Address> [t_c_clear] */
2911
2912	if (os_strncmp(pos, "disconnect ", 11) == 0) {
2913		disconnect = 1;
2914		pos += 11;
2915	} else if (os_strncmp(req, "coa ", 4) == 0) {
2916		disconnect = 0;
2917		pos += 4;
2918	} else {
2919		return -1;
2920	}
2921
2922	if (hwaddr_aton(pos, addr))
2923		return -1;
2924	pos = os_strchr(pos, ' ');
2925	if (pos) {
2926		if (os_strstr(pos, "t_c_clear"))
2927			t_c_clear = 1;
2928	}
2929
2930	if (!disconnect && !t_c_clear) {
2931		RADIUS_ERROR("DAC request for CoA without any authorization change");
2932		return -1;
2933	}
2934
2935	if (!data->db) {
2936		RADIUS_ERROR("SQLite database not in use");
2937		return -1;
2938	}
2939
2940	os_snprintf(addrtxt, sizeof(addrtxt), MACSTR, MAC2STR(addr));
2941
2942	sql = sqlite3_mprintf("SELECT * FROM current_sessions WHERE mac_addr=%Q",
2943			      addrtxt);
2944	if (!sql)
2945		return -1;
2946
2947	os_memset(&fields, 0, sizeof(fields));
2948	res = sqlite3_exec(data->db, sql, get_db_session_fields, &fields, NULL);
2949	sqlite3_free(sql);
2950	if (res != SQLITE_OK) {
2951		RADIUS_ERROR("Failed to find matching current_sessions entry from sqlite database: %s",
2952			     sqlite3_errmsg(data->db));
2953		free_db_session_fields(&fields);
2954		return -1;
2955	}
2956
2957	if (!fields.nas) {
2958		RADIUS_ERROR("No NAS information found from current_sessions");
2959		free_db_session_fields(&fields);
2960		return -1;
2961	}
2962
2963	os_memset(&das, 0, sizeof(das));
2964	das.sin_family = AF_INET;
2965	das.sin_addr.s_addr = inet_addr(fields.nas);
2966	das.sin_port = htons(3799);
2967
2968	free_db_session_fields(&fields);
2969
2970	client = radius_server_get_client(data, &das.sin_addr, 0);
2971	if (!client) {
2972		RADIUS_ERROR("No NAS information available to protect the packet");
2973		return -1;
2974	}
2975
2976	identifier = client->next_dac_identifier++;
2977
2978	msg = radius_msg_new(disconnect ? RADIUS_CODE_DISCONNECT_REQUEST :
2979			     RADIUS_CODE_COA_REQUEST, identifier);
2980	if (!msg)
2981		return -1;
2982
2983	os_snprintf(addrtxt, sizeof(addrtxt), RADIUS_802_1X_ADDR_FORMAT,
2984		    MAC2STR(addr));
2985	if (!radius_msg_add_attr(msg, RADIUS_ATTR_CALLING_STATION_ID,
2986				 (u8 *) addrtxt, os_strlen(addrtxt))) {
2987		RADIUS_ERROR("Could not add Calling-Station-Id");
2988		radius_msg_free(msg);
2989		return -1;
2990	}
2991
2992	if (!disconnect && t_c_clear) {
2993		u8 val[4] = { 0x00, 0x00, 0x00, 0x00 }; /* E=0 */
2994
2995		if (!radius_msg_add_wfa(
2996			    msg, RADIUS_VENDOR_ATTR_WFA_HS20_T_C_FILTERING,
2997			    val, sizeof(val))) {
2998			RADIUS_DEBUG("Failed to add WFA-HS20-T-C-Filtering");
2999			radius_msg_free(msg);
3000			return -1;
3001		}
3002	}
3003
3004	os_get_time(&now);
3005	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_EVENT_TIMESTAMP,
3006				       now.sec)) {
3007		RADIUS_ERROR("Failed to add Event-Timestamp attribute");
3008		radius_msg_free(msg);
3009		return -1;
3010	}
3011
3012	radius_msg_finish_acct(msg, (u8 *) client->shared_secret,
3013			       client->shared_secret_len);
3014
3015	if (wpa_debug_level <= MSG_MSGDUMP)
3016		radius_msg_dump(msg);
3017
3018	buf = radius_msg_get_buf(msg);
3019	if (sendto(data->auth_sock, wpabuf_head(buf), wpabuf_len(buf), 0,
3020		   (struct sockaddr *) &das, sizeof(das)) < 0) {
3021		RADIUS_ERROR("Failed to send packet - sendto: %s",
3022			     strerror(errno));
3023		radius_msg_free(msg);
3024		return -1;
3025	}
3026
3027	if (disconnect) {
3028		radius_msg_free(client->pending_dac_disconnect_req);
3029		client->pending_dac_disconnect_req = msg;
3030		client->pending_dac_disconnect_id = identifier;
3031		os_memcpy(client->pending_dac_disconnect_addr, addr, ETH_ALEN);
3032	} else {
3033		radius_msg_free(client->pending_dac_coa_req);
3034		client->pending_dac_coa_req = msg;
3035		client->pending_dac_coa_id = identifier;
3036		os_memcpy(client->pending_dac_coa_addr, addr, ETH_ALEN);
3037	}
3038
3039	return 0;
3040#else /* CONFIG_SQLITE */
3041	return -1;
3042#endif /* CONFIG_SQLITE */
3043}
3044