Declare all read only data structures as const
[mech_eap.git] / src / radius / radius_server.c
1 /*
2  * RADIUS authentication server
3  * Copyright (c) 2005-2009, 2011-2014, 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_MAX_SESSION - Maximum number of active sessions
30  */
31 #define RADIUS_MAX_SESSION 100
32
33 /**
34  * RADIUS_MAX_MSG_LEN - Maximum message length for incoming RADIUS messages
35  */
36 #define RADIUS_MAX_MSG_LEN 3000
37
38 static const struct eapol_callbacks radius_server_eapol_cb;
39
40 struct radius_client;
41 struct radius_server_data;
42
43 /**
44  * struct radius_server_counters - RADIUS server statistics counters
45  */
46 struct radius_server_counters {
47         u32 access_requests;
48         u32 invalid_requests;
49         u32 dup_access_requests;
50         u32 access_accepts;
51         u32 access_rejects;
52         u32 access_challenges;
53         u32 malformed_access_requests;
54         u32 bad_authenticators;
55         u32 packets_dropped;
56         u32 unknown_types;
57
58         u32 acct_requests;
59         u32 invalid_acct_requests;
60         u32 acct_responses;
61         u32 malformed_acct_requests;
62         u32 acct_bad_authenticators;
63         u32 unknown_acct_types;
64 };
65
66 /**
67  * struct radius_session - Internal RADIUS server data for a session
68  */
69 struct radius_session {
70         struct radius_session *next;
71         struct radius_client *client;
72         struct radius_server_data *server;
73         unsigned int sess_id;
74         struct eap_sm *eap;
75         struct eap_eapol_interface *eap_if;
76         char *username; /* from User-Name attribute */
77         char *nas_ip;
78
79         struct radius_msg *last_msg;
80         char *last_from_addr;
81         int last_from_port;
82         struct sockaddr_storage last_from;
83         socklen_t last_fromlen;
84         u8 last_identifier;
85         struct radius_msg *last_reply;
86         u8 last_authenticator[16];
87
88         unsigned int remediation:1;
89         unsigned int macacl:1;
90
91         struct hostapd_radius_attr *accept_attr;
92 };
93
94 /**
95  * struct radius_client - Internal RADIUS server data for a client
96  */
97 struct radius_client {
98         struct radius_client *next;
99         struct in_addr addr;
100         struct in_addr mask;
101 #ifdef CONFIG_IPV6
102         struct in6_addr addr6;
103         struct in6_addr mask6;
104 #endif /* CONFIG_IPV6 */
105         char *shared_secret;
106         int shared_secret_len;
107         struct radius_session *sessions;
108         struct radius_server_counters counters;
109 };
110
111 /**
112  * struct radius_server_data - Internal RADIUS server data
113  */
114 struct radius_server_data {
115         /**
116          * auth_sock - Socket for RADIUS authentication messages
117          */
118         int auth_sock;
119
120         /**
121          * acct_sock - Socket for RADIUS accounting messages
122          */
123         int acct_sock;
124
125         /**
126          * clients - List of authorized RADIUS clients
127          */
128         struct radius_client *clients;
129
130         /**
131          * next_sess_id - Next session identifier
132          */
133         unsigned int next_sess_id;
134
135         /**
136          * conf_ctx - Context pointer for callbacks
137          *
138          * This is used as the ctx argument in get_eap_user() calls.
139          */
140         void *conf_ctx;
141
142         /**
143          * num_sess - Number of active sessions
144          */
145         int num_sess;
146
147         /**
148          * eap_sim_db_priv - EAP-SIM/AKA database context
149          *
150          * This is passed to the EAP-SIM/AKA server implementation as a
151          * callback context.
152          */
153         void *eap_sim_db_priv;
154
155         /**
156          * ssl_ctx - TLS context
157          *
158          * This is passed to the EAP server implementation as a callback
159          * context for TLS operations.
160          */
161         void *ssl_ctx;
162
163         /**
164          * pac_opaque_encr_key - PAC-Opaque encryption key for EAP-FAST
165          *
166          * This parameter is used to set a key for EAP-FAST to encrypt the
167          * PAC-Opaque data. It can be set to %NULL if EAP-FAST is not used. If
168          * set, must point to a 16-octet key.
169          */
170         u8 *pac_opaque_encr_key;
171
172         /**
173          * eap_fast_a_id - EAP-FAST authority identity (A-ID)
174          *
175          * If EAP-FAST is not used, this can be set to %NULL. In theory, this
176          * is a variable length field, but due to some existing implementations
177          * requiring A-ID to be 16 octets in length, it is recommended to use
178          * that length for the field to provide interoperability with deployed
179          * peer implementations.
180          */
181         u8 *eap_fast_a_id;
182
183         /**
184          * eap_fast_a_id_len - Length of eap_fast_a_id buffer in octets
185          */
186         size_t eap_fast_a_id_len;
187
188         /**
189          * eap_fast_a_id_info - EAP-FAST authority identifier information
190          *
191          * This A-ID-Info contains a user-friendly name for the A-ID. For
192          * example, this could be the enterprise and server names in
193          * human-readable format. This field is encoded as UTF-8. If EAP-FAST
194          * is not used, this can be set to %NULL.
195          */
196         char *eap_fast_a_id_info;
197
198         /**
199          * eap_fast_prov - EAP-FAST provisioning modes
200          *
201          * 0 = provisioning disabled, 1 = only anonymous provisioning allowed,
202          * 2 = only authenticated provisioning allowed, 3 = both provisioning
203          * modes allowed.
204          */
205         int eap_fast_prov;
206
207         /**
208          * pac_key_lifetime - EAP-FAST PAC-Key lifetime in seconds
209          *
210          * This is the hard limit on how long a provisioned PAC-Key can be
211          * used.
212          */
213         int pac_key_lifetime;
214
215         /**
216          * pac_key_refresh_time - EAP-FAST PAC-Key refresh time in seconds
217          *
218          * This is a soft limit on the PAC-Key. The server will automatically
219          * generate a new PAC-Key when this number of seconds (or fewer) of the
220          * lifetime remains.
221          */
222         int pac_key_refresh_time;
223
224         /**
225          * eap_sim_aka_result_ind - EAP-SIM/AKA protected success indication
226          *
227          * This controls whether the protected success/failure indication
228          * (AT_RESULT_IND) is used with EAP-SIM and EAP-AKA.
229          */
230         int eap_sim_aka_result_ind;
231
232         /**
233          * tnc - Trusted Network Connect (TNC)
234          *
235          * This controls whether TNC is enabled and will be required before the
236          * peer is allowed to connect. Note: This is only used with EAP-TTLS
237          * and EAP-FAST. If any other EAP method is enabled, the peer will be
238          * allowed to connect without TNC.
239          */
240         int tnc;
241
242         /**
243          * pwd_group - The D-H group assigned for EAP-pwd
244          *
245          * If EAP-pwd is not used it can be set to zero.
246          */
247         u16 pwd_group;
248
249         /**
250          * server_id - Server identity
251          */
252         const char *server_id;
253
254         /**
255          * erp - Whether EAP Re-authentication Protocol (ERP) is enabled
256          *
257          * This controls whether the authentication server derives ERP key
258          * hierarchy (rRK and rIK) from full EAP authentication and allows
259          * these keys to be used to perform ERP to derive rMSK instead of full
260          * EAP authentication to derive MSK.
261          */
262         int erp;
263
264         const char *erp_domain;
265
266         struct dl_list erp_keys; /* struct eap_server_erp_key */
267
268         /**
269          * wps - Wi-Fi Protected Setup context
270          *
271          * If WPS is used with an external RADIUS server (which is quite
272          * unlikely configuration), this is used to provide a pointer to WPS
273          * context data. Normally, this can be set to %NULL.
274          */
275         struct wps_context *wps;
276
277         /**
278          * ipv6 - Whether to enable IPv6 support in the RADIUS server
279          */
280         int ipv6;
281
282         /**
283          * start_time - Timestamp of server start
284          */
285         struct os_reltime start_time;
286
287         /**
288          * counters - Statistics counters for server operations
289          *
290          * These counters are the sum over all clients.
291          */
292         struct radius_server_counters counters;
293
294         /**
295          * get_eap_user - Callback for fetching EAP user information
296          * @ctx: Context data from conf_ctx
297          * @identity: User identity
298          * @identity_len: identity buffer length in octets
299          * @phase2: Whether this is for Phase 2 identity
300          * @user: Data structure for filling in the user information
301          * Returns: 0 on success, -1 on failure
302          *
303          * This is used to fetch information from user database. The callback
304          * will fill in information about allowed EAP methods and the user
305          * password. The password field will be an allocated copy of the
306          * password data and RADIUS server will free it after use.
307          */
308         int (*get_eap_user)(void *ctx, const u8 *identity, size_t identity_len,
309                             int phase2, struct eap_user *user);
310
311         /**
312          * eap_req_id_text - Optional data for EAP-Request/Identity
313          *
314          * This can be used to configure an optional, displayable message that
315          * will be sent in EAP-Request/Identity. This string can contain an
316          * ASCII-0 character (nul) to separate network infromation per RFC
317          * 4284. The actual string length is explicit provided in
318          * eap_req_id_text_len since nul character will not be used as a string
319          * terminator.
320          */
321         char *eap_req_id_text;
322
323         /**
324          * eap_req_id_text_len - Length of eap_req_id_text buffer in octets
325          */
326         size_t eap_req_id_text_len;
327
328         /*
329          * msg_ctx - Context data for wpa_msg() calls
330          */
331         void *msg_ctx;
332
333 #ifdef CONFIG_RADIUS_TEST
334         char *dump_msk_file;
335 #endif /* CONFIG_RADIUS_TEST */
336
337         char *subscr_remediation_url;
338         u8 subscr_remediation_method;
339
340 #ifdef CONFIG_SQLITE
341         sqlite3 *db;
342 #endif /* CONFIG_SQLITE */
343 };
344
345
346 #define RADIUS_DEBUG(args...) \
347 wpa_printf(MSG_DEBUG, "RADIUS SRV: " args)
348 #define RADIUS_ERROR(args...) \
349 wpa_printf(MSG_ERROR, "RADIUS SRV: " args)
350 #define RADIUS_DUMP(args...) \
351 wpa_hexdump(MSG_MSGDUMP, "RADIUS SRV: " args)
352 #define RADIUS_DUMP_ASCII(args...) \
353 wpa_hexdump_ascii(MSG_MSGDUMP, "RADIUS SRV: " args)
354
355
356 static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx);
357 static void radius_server_session_remove_timeout(void *eloop_ctx,
358                                                  void *timeout_ctx);
359
360 void srv_log(struct radius_session *sess, const char *fmt, ...)
361 PRINTF_FORMAT(2, 3);
362
363 void srv_log(struct radius_session *sess, const char *fmt, ...)
364 {
365         va_list ap;
366         char *buf;
367         int buflen;
368
369         va_start(ap, fmt);
370         buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
371         va_end(ap);
372
373         buf = os_malloc(buflen);
374         if (buf == NULL)
375                 return;
376         va_start(ap, fmt);
377         vsnprintf(buf, buflen, fmt, ap);
378         va_end(ap);
379
380         RADIUS_DEBUG("[0x%x %s] %s", sess->sess_id, sess->nas_ip, buf);
381
382 #ifdef CONFIG_SQLITE
383         if (sess->server->db) {
384                 char *sql;
385                 sql = sqlite3_mprintf("INSERT INTO authlog"
386                                       "(timestamp,session,nas_ip,username,note)"
387                                       " VALUES ("
388                                       "strftime('%%Y-%%m-%%d %%H:%%M:%%f',"
389                                       "'now'),%u,%Q,%Q,%Q)",
390                                       sess->sess_id, sess->nas_ip,
391                                       sess->username, buf);
392                 if (sql) {
393                         if (sqlite3_exec(sess->server->db, sql, NULL, NULL,
394                                          NULL) != SQLITE_OK) {
395                                 RADIUS_ERROR("Failed to add authlog entry into sqlite database: %s",
396                                              sqlite3_errmsg(sess->server->db));
397                         }
398                         sqlite3_free(sql);
399                 }
400         }
401 #endif /* CONFIG_SQLITE */
402
403         os_free(buf);
404 }
405
406
407 static struct radius_client *
408 radius_server_get_client(struct radius_server_data *data, struct in_addr *addr,
409                          int ipv6)
410 {
411         struct radius_client *client = data->clients;
412
413         while (client) {
414 #ifdef CONFIG_IPV6
415                 if (ipv6) {
416                         struct in6_addr *addr6;
417                         int i;
418
419                         addr6 = (struct in6_addr *) addr;
420                         for (i = 0; i < 16; i++) {
421                                 if ((addr6->s6_addr[i] &
422                                      client->mask6.s6_addr[i]) !=
423                                     (client->addr6.s6_addr[i] &
424                                      client->mask6.s6_addr[i])) {
425                                         i = 17;
426                                         break;
427                                 }
428                         }
429                         if (i == 16) {
430                                 break;
431                         }
432                 }
433 #endif /* CONFIG_IPV6 */
434                 if (!ipv6 && (client->addr.s_addr & client->mask.s_addr) ==
435                     (addr->s_addr & client->mask.s_addr)) {
436                         break;
437                 }
438
439                 client = client->next;
440         }
441
442         return client;
443 }
444
445
446 static struct radius_session *
447 radius_server_get_session(struct radius_client *client, unsigned int sess_id)
448 {
449         struct radius_session *sess = client->sessions;
450
451         while (sess) {
452                 if (sess->sess_id == sess_id) {
453                         break;
454                 }
455                 sess = sess->next;
456         }
457
458         return sess;
459 }
460
461
462 static void radius_server_session_free(struct radius_server_data *data,
463                                        struct radius_session *sess)
464 {
465         eloop_cancel_timeout(radius_server_session_timeout, data, sess);
466         eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);
467         eap_server_sm_deinit(sess->eap);
468         radius_msg_free(sess->last_msg);
469         os_free(sess->last_from_addr);
470         radius_msg_free(sess->last_reply);
471         os_free(sess->username);
472         os_free(sess->nas_ip);
473         os_free(sess);
474         data->num_sess--;
475 }
476
477
478 static void radius_server_session_remove(struct radius_server_data *data,
479                                          struct radius_session *sess)
480 {
481         struct radius_client *client = sess->client;
482         struct radius_session *session, *prev;
483
484         eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);
485
486         prev = NULL;
487         session = client->sessions;
488         while (session) {
489                 if (session == sess) {
490                         if (prev == NULL) {
491                                 client->sessions = sess->next;
492                         } else {
493                                 prev->next = sess->next;
494                         }
495                         radius_server_session_free(data, sess);
496                         break;
497                 }
498                 prev = session;
499                 session = session->next;
500         }
501 }
502
503
504 static void radius_server_session_remove_timeout(void *eloop_ctx,
505                                                  void *timeout_ctx)
506 {
507         struct radius_server_data *data = eloop_ctx;
508         struct radius_session *sess = timeout_ctx;
509         RADIUS_DEBUG("Removing completed session 0x%x", sess->sess_id);
510         radius_server_session_remove(data, sess);
511 }
512
513
514 static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx)
515 {
516         struct radius_server_data *data = eloop_ctx;
517         struct radius_session *sess = timeout_ctx;
518
519         RADIUS_DEBUG("Timing out authentication session 0x%x", sess->sess_id);
520         radius_server_session_remove(data, sess);
521 }
522
523
524 static struct radius_session *
525 radius_server_new_session(struct radius_server_data *data,
526                           struct radius_client *client)
527 {
528         struct radius_session *sess;
529
530         if (data->num_sess >= RADIUS_MAX_SESSION) {
531                 RADIUS_DEBUG("Maximum number of existing session - no room "
532                              "for a new session");
533                 return NULL;
534         }
535
536         sess = os_zalloc(sizeof(*sess));
537         if (sess == NULL)
538                 return NULL;
539
540         sess->server = data;
541         sess->client = client;
542         sess->sess_id = data->next_sess_id++;
543         sess->next = client->sessions;
544         client->sessions = sess;
545         eloop_register_timeout(RADIUS_SESSION_TIMEOUT, 0,
546                                radius_server_session_timeout, data, sess);
547         data->num_sess++;
548         return sess;
549 }
550
551
552 #ifdef CONFIG_TESTING_OPTIONS
553 static void radius_server_testing_options_tls(struct radius_session *sess,
554                                               const char *tls,
555                                               struct eap_config *eap_conf)
556 {
557         int test = atoi(tls);
558
559         switch (test) {
560         case 1:
561                 srv_log(sess, "TLS test - break VerifyData");
562                 eap_conf->tls_test_flags = TLS_BREAK_VERIFY_DATA;
563                 break;
564         case 2:
565                 srv_log(sess, "TLS test - break ServerKeyExchange ServerParams hash");
566                 eap_conf->tls_test_flags = TLS_BREAK_SRV_KEY_X_HASH;
567                 break;
568         case 3:
569                 srv_log(sess, "TLS test - break ServerKeyExchange ServerParams Signature");
570                 eap_conf->tls_test_flags = TLS_BREAK_SRV_KEY_X_SIGNATURE;
571                 break;
572         case 4:
573                 srv_log(sess, "TLS test - RSA-DHE using a short 511-bit prime");
574                 eap_conf->tls_test_flags = TLS_DHE_PRIME_511B;
575                 break;
576         case 5:
577                 srv_log(sess, "TLS test - RSA-DHE using a short 767-bit prime");
578                 eap_conf->tls_test_flags = TLS_DHE_PRIME_767B;
579                 break;
580         case 6:
581                 srv_log(sess, "TLS test - RSA-DHE using a bogus 15 \"prime\"");
582                 eap_conf->tls_test_flags = TLS_DHE_PRIME_15;
583                 break;
584         case 7:
585                 srv_log(sess, "TLS test - RSA-DHE using a short 58-bit prime in long container");
586                 eap_conf->tls_test_flags = TLS_DHE_PRIME_58B;
587                 break;
588         case 8:
589                 srv_log(sess, "TLS test - RSA-DHE using a non-prime");
590                 eap_conf->tls_test_flags = TLS_DHE_NON_PRIME;
591                 break;
592         default:
593                 srv_log(sess, "Unrecognized TLS test");
594                 break;
595         }
596 }
597 #endif /* CONFIG_TESTING_OPTIONS */
598
599 static void radius_server_testing_options(struct radius_session *sess,
600                                           struct eap_config *eap_conf)
601 {
602 #ifdef CONFIG_TESTING_OPTIONS
603         const char *pos;
604
605         pos = os_strstr(sess->username, "@test-");
606         if (pos == NULL)
607                 return;
608         pos += 6;
609         if (os_strncmp(pos, "tls-", 4) == 0)
610                 radius_server_testing_options_tls(sess, pos + 4, eap_conf);
611         else
612                 srv_log(sess, "Unrecognized test: %s", pos);
613 #endif /* CONFIG_TESTING_OPTIONS */
614 }
615
616
617 static struct radius_session *
618 radius_server_get_new_session(struct radius_server_data *data,
619                               struct radius_client *client,
620                               struct radius_msg *msg, const char *from_addr)
621 {
622         u8 *user;
623         size_t user_len;
624         int res;
625         struct radius_session *sess;
626         struct eap_config eap_conf;
627         struct eap_user tmp;
628
629         RADIUS_DEBUG("Creating a new session");
630
631         if (radius_msg_get_attr_ptr(msg, RADIUS_ATTR_USER_NAME, &user,
632                                     &user_len, NULL) < 0) {
633                 RADIUS_DEBUG("Could not get User-Name");
634                 return NULL;
635         }
636         RADIUS_DUMP_ASCII("User-Name", user, user_len);
637
638         os_memset(&tmp, 0, sizeof(tmp));
639         res = data->get_eap_user(data->conf_ctx, user, user_len, 0, &tmp);
640         bin_clear_free(tmp.password, tmp.password_len);
641
642         if (res != 0) {
643                 RADIUS_DEBUG("User-Name not found from user database");
644                 return NULL;
645         }
646
647         RADIUS_DEBUG("Matching user entry found");
648         sess = radius_server_new_session(data, client);
649         if (sess == NULL) {
650                 RADIUS_DEBUG("Failed to create a new session");
651                 return NULL;
652         }
653         sess->accept_attr = tmp.accept_attr;
654         sess->macacl = tmp.macacl;
655
656         sess->username = os_malloc(user_len * 4 + 1);
657         if (sess->username == NULL) {
658                 radius_server_session_free(data, sess);
659                 return NULL;
660         }
661         printf_encode(sess->username, user_len * 4 + 1, user, user_len);
662
663         sess->nas_ip = os_strdup(from_addr);
664         if (sess->nas_ip == NULL) {
665                 radius_server_session_free(data, sess);
666                 return NULL;
667         }
668
669         srv_log(sess, "New session created");
670
671         os_memset(&eap_conf, 0, sizeof(eap_conf));
672         eap_conf.ssl_ctx = data->ssl_ctx;
673         eap_conf.msg_ctx = data->msg_ctx;
674         eap_conf.eap_sim_db_priv = data->eap_sim_db_priv;
675         eap_conf.backend_auth = TRUE;
676         eap_conf.eap_server = 1;
677         eap_conf.pac_opaque_encr_key = data->pac_opaque_encr_key;
678         eap_conf.eap_fast_a_id = data->eap_fast_a_id;
679         eap_conf.eap_fast_a_id_len = data->eap_fast_a_id_len;
680         eap_conf.eap_fast_a_id_info = data->eap_fast_a_id_info;
681         eap_conf.eap_fast_prov = data->eap_fast_prov;
682         eap_conf.pac_key_lifetime = data->pac_key_lifetime;
683         eap_conf.pac_key_refresh_time = data->pac_key_refresh_time;
684         eap_conf.eap_sim_aka_result_ind = data->eap_sim_aka_result_ind;
685         eap_conf.tnc = data->tnc;
686         eap_conf.wps = data->wps;
687         eap_conf.pwd_group = data->pwd_group;
688         eap_conf.server_id = (const u8 *) data->server_id;
689         eap_conf.server_id_len = os_strlen(data->server_id);
690         eap_conf.erp = data->erp;
691         radius_server_testing_options(sess, &eap_conf);
692         sess->eap = eap_server_sm_init(sess, &radius_server_eapol_cb,
693                                        &eap_conf);
694         if (sess->eap == NULL) {
695                 RADIUS_DEBUG("Failed to initialize EAP state machine for the "
696                              "new session");
697                 radius_server_session_free(data, sess);
698                 return NULL;
699         }
700         sess->eap_if = eap_get_interface(sess->eap);
701         sess->eap_if->eapRestart = TRUE;
702         sess->eap_if->portEnabled = TRUE;
703
704         RADIUS_DEBUG("New session 0x%x initialized", sess->sess_id);
705
706         return sess;
707 }
708
709
710 static struct radius_msg *
711 radius_server_encapsulate_eap(struct radius_server_data *data,
712                               struct radius_client *client,
713                               struct radius_session *sess,
714                               struct radius_msg *request)
715 {
716         struct radius_msg *msg;
717         int code;
718         unsigned int sess_id;
719         struct radius_hdr *hdr = radius_msg_get_hdr(request);
720
721         if (sess->eap_if->eapFail) {
722                 sess->eap_if->eapFail = FALSE;
723                 code = RADIUS_CODE_ACCESS_REJECT;
724         } else if (sess->eap_if->eapSuccess) {
725                 sess->eap_if->eapSuccess = FALSE;
726                 code = RADIUS_CODE_ACCESS_ACCEPT;
727         } else {
728                 sess->eap_if->eapReq = FALSE;
729                 code = RADIUS_CODE_ACCESS_CHALLENGE;
730         }
731
732         msg = radius_msg_new(code, hdr->identifier);
733         if (msg == NULL) {
734                 RADIUS_DEBUG("Failed to allocate reply message");
735                 return NULL;
736         }
737
738         sess_id = htonl(sess->sess_id);
739         if (code == RADIUS_CODE_ACCESS_CHALLENGE &&
740             !radius_msg_add_attr(msg, RADIUS_ATTR_STATE,
741                                  (u8 *) &sess_id, sizeof(sess_id))) {
742                 RADIUS_DEBUG("Failed to add State attribute");
743         }
744
745         if (sess->eap_if->eapReqData &&
746             !radius_msg_add_eap(msg, wpabuf_head(sess->eap_if->eapReqData),
747                                 wpabuf_len(sess->eap_if->eapReqData))) {
748                 RADIUS_DEBUG("Failed to add EAP-Message attribute");
749         }
750
751         if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->eap_if->eapKeyData) {
752                 int len;
753 #ifdef CONFIG_RADIUS_TEST
754                 if (data->dump_msk_file) {
755                         FILE *f;
756                         char buf[2 * 64 + 1];
757                         f = fopen(data->dump_msk_file, "a");
758                         if (f) {
759                                 len = sess->eap_if->eapKeyDataLen;
760                                 if (len > 64)
761                                         len = 64;
762                                 len = wpa_snprintf_hex(
763                                         buf, sizeof(buf),
764                                         sess->eap_if->eapKeyData, len);
765                                 buf[len] = '\0';
766                                 fprintf(f, "%s\n", buf);
767                                 fclose(f);
768                         }
769                 }
770 #endif /* CONFIG_RADIUS_TEST */
771                 if (sess->eap_if->eapKeyDataLen > 64) {
772                         len = 32;
773                 } else {
774                         len = sess->eap_if->eapKeyDataLen / 2;
775                 }
776                 if (!radius_msg_add_mppe_keys(msg, hdr->authenticator,
777                                               (u8 *) client->shared_secret,
778                                               client->shared_secret_len,
779                                               sess->eap_if->eapKeyData + len,
780                                               len, sess->eap_if->eapKeyData,
781                                               len)) {
782                         RADIUS_DEBUG("Failed to add MPPE key attributes");
783                 }
784         }
785
786 #ifdef CONFIG_HS20
787         if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->remediation &&
788             data->subscr_remediation_url) {
789                 u8 *buf;
790                 size_t url_len = os_strlen(data->subscr_remediation_url);
791                 buf = os_malloc(1 + url_len);
792                 if (buf == NULL) {
793                         radius_msg_free(msg);
794                         return NULL;
795                 }
796                 buf[0] = data->subscr_remediation_method;
797                 os_memcpy(&buf[1], data->subscr_remediation_url, url_len);
798                 if (!radius_msg_add_wfa(
799                             msg, RADIUS_VENDOR_ATTR_WFA_HS20_SUBSCR_REMEDIATION,
800                             buf, 1 + url_len)) {
801                         RADIUS_DEBUG("Failed to add WFA-HS20-SubscrRem");
802                 }
803                 os_free(buf);
804         } else if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->remediation) {
805                 u8 buf[1];
806                 if (!radius_msg_add_wfa(
807                             msg, RADIUS_VENDOR_ATTR_WFA_HS20_SUBSCR_REMEDIATION,
808                             buf, 0)) {
809                         RADIUS_DEBUG("Failed to add WFA-HS20-SubscrRem");
810                 }
811         }
812 #endif /* CONFIG_HS20 */
813
814         if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
815                 RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
816                 radius_msg_free(msg);
817                 return NULL;
818         }
819
820         if (code == RADIUS_CODE_ACCESS_ACCEPT) {
821                 struct hostapd_radius_attr *attr;
822                 for (attr = sess->accept_attr; attr; attr = attr->next) {
823                         if (!radius_msg_add_attr(msg, attr->type,
824                                                  wpabuf_head(attr->val),
825                                                  wpabuf_len(attr->val))) {
826                                 wpa_printf(MSG_ERROR, "Could not add RADIUS attribute");
827                                 radius_msg_free(msg);
828                                 return NULL;
829                         }
830                 }
831         }
832
833         if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
834                                   client->shared_secret_len,
835                                   hdr->authenticator) < 0) {
836                 RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
837         }
838
839         return msg;
840 }
841
842
843 static struct radius_msg *
844 radius_server_macacl(struct radius_server_data *data,
845                      struct radius_client *client,
846                      struct radius_session *sess,
847                      struct radius_msg *request)
848 {
849         struct radius_msg *msg;
850         int code;
851         struct radius_hdr *hdr = radius_msg_get_hdr(request);
852         u8 *pw;
853         size_t pw_len;
854
855         code = RADIUS_CODE_ACCESS_ACCEPT;
856
857         if (radius_msg_get_attr_ptr(request, RADIUS_ATTR_USER_PASSWORD, &pw,
858                                     &pw_len, NULL) < 0) {
859                 RADIUS_DEBUG("Could not get User-Password");
860                 code = RADIUS_CODE_ACCESS_REJECT;
861         } else {
862                 int res;
863                 struct eap_user tmp;
864
865                 os_memset(&tmp, 0, sizeof(tmp));
866                 res = data->get_eap_user(data->conf_ctx, (u8 *) sess->username,
867                                          os_strlen(sess->username), 0, &tmp);
868                 if (res || !tmp.macacl || tmp.password == NULL) {
869                         RADIUS_DEBUG("No MAC ACL user entry");
870                         bin_clear_free(tmp.password, tmp.password_len);
871                         code = RADIUS_CODE_ACCESS_REJECT;
872                 } else {
873                         u8 buf[128];
874                         res = radius_user_password_hide(
875                                 request, tmp.password, tmp.password_len,
876                                 (u8 *) client->shared_secret,
877                                 client->shared_secret_len,
878                                 buf, sizeof(buf));
879                         bin_clear_free(tmp.password, tmp.password_len);
880
881                         if (res < 0 || pw_len != (size_t) res ||
882                             os_memcmp_const(pw, buf, res) != 0) {
883                                 RADIUS_DEBUG("Incorrect User-Password");
884                                 code = RADIUS_CODE_ACCESS_REJECT;
885                         }
886                 }
887         }
888
889         msg = radius_msg_new(code, hdr->identifier);
890         if (msg == NULL) {
891                 RADIUS_DEBUG("Failed to allocate reply message");
892                 return NULL;
893         }
894
895         if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
896                 RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
897                 radius_msg_free(msg);
898                 return NULL;
899         }
900
901         if (code == RADIUS_CODE_ACCESS_ACCEPT) {
902                 struct hostapd_radius_attr *attr;
903                 for (attr = sess->accept_attr; attr; attr = attr->next) {
904                         if (!radius_msg_add_attr(msg, attr->type,
905                                                  wpabuf_head(attr->val),
906                                                  wpabuf_len(attr->val))) {
907                                 wpa_printf(MSG_ERROR, "Could not add RADIUS attribute");
908                                 radius_msg_free(msg);
909                                 return NULL;
910                         }
911                 }
912         }
913
914         if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
915                                   client->shared_secret_len,
916                                   hdr->authenticator) < 0) {
917                 RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
918         }
919
920         return msg;
921 }
922
923
924 static int radius_server_reject(struct radius_server_data *data,
925                                 struct radius_client *client,
926                                 struct radius_msg *request,
927                                 struct sockaddr *from, socklen_t fromlen,
928                                 const char *from_addr, int from_port)
929 {
930         struct radius_msg *msg;
931         int ret = 0;
932         struct eap_hdr eapfail;
933         struct wpabuf *buf;
934         struct radius_hdr *hdr = radius_msg_get_hdr(request);
935
936         RADIUS_DEBUG("Reject invalid request from %s:%d",
937                      from_addr, from_port);
938
939         msg = radius_msg_new(RADIUS_CODE_ACCESS_REJECT, hdr->identifier);
940         if (msg == NULL) {
941                 return -1;
942         }
943
944         os_memset(&eapfail, 0, sizeof(eapfail));
945         eapfail.code = EAP_CODE_FAILURE;
946         eapfail.identifier = 0;
947         eapfail.length = host_to_be16(sizeof(eapfail));
948
949         if (!radius_msg_add_eap(msg, (u8 *) &eapfail, sizeof(eapfail))) {
950                 RADIUS_DEBUG("Failed to add EAP-Message attribute");
951         }
952
953         if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
954                 RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
955                 radius_msg_free(msg);
956                 return -1;
957         }
958
959         if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
960                                   client->shared_secret_len,
961                                   hdr->authenticator) <
962             0) {
963                 RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
964         }
965
966         if (wpa_debug_level <= MSG_MSGDUMP) {
967                 radius_msg_dump(msg);
968         }
969
970         data->counters.access_rejects++;
971         client->counters.access_rejects++;
972         buf = radius_msg_get_buf(msg);
973         if (sendto(data->auth_sock, wpabuf_head(buf), wpabuf_len(buf), 0,
974                    (struct sockaddr *) from, sizeof(*from)) < 0) {
975                 wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s", strerror(errno));
976                 ret = -1;
977         }
978
979         radius_msg_free(msg);
980
981         return ret;
982 }
983
984
985 static int radius_server_request(struct radius_server_data *data,
986                                  struct radius_msg *msg,
987                                  struct sockaddr *from, socklen_t fromlen,
988                                  struct radius_client *client,
989                                  const char *from_addr, int from_port,
990                                  struct radius_session *force_sess)
991 {
992         struct wpabuf *eap = NULL;
993         int res, state_included = 0;
994         u8 statebuf[4];
995         unsigned int state;
996         struct radius_session *sess;
997         struct radius_msg *reply;
998         int is_complete = 0;
999
1000         if (force_sess)
1001                 sess = force_sess;
1002         else {
1003                 res = radius_msg_get_attr(msg, RADIUS_ATTR_STATE, statebuf,
1004                                           sizeof(statebuf));
1005                 state_included = res >= 0;
1006                 if (res == sizeof(statebuf)) {
1007                         state = WPA_GET_BE32(statebuf);
1008                         sess = radius_server_get_session(client, state);
1009                 } else {
1010                         sess = NULL;
1011                 }
1012         }
1013
1014         if (sess) {
1015                 RADIUS_DEBUG("Request for session 0x%x", sess->sess_id);
1016         } else if (state_included) {
1017                 RADIUS_DEBUG("State attribute included but no session found");
1018                 radius_server_reject(data, client, msg, from, fromlen,
1019                                      from_addr, from_port);
1020                 return -1;
1021         } else {
1022                 sess = radius_server_get_new_session(data, client, msg,
1023                                                      from_addr);
1024                 if (sess == NULL) {
1025                         RADIUS_DEBUG("Could not create a new session");
1026                         radius_server_reject(data, client, msg, from, fromlen,
1027                                              from_addr, from_port);
1028                         return -1;
1029                 }
1030         }
1031
1032         if (sess->last_from_port == from_port &&
1033             sess->last_identifier == radius_msg_get_hdr(msg)->identifier &&
1034             os_memcmp(sess->last_authenticator,
1035                       radius_msg_get_hdr(msg)->authenticator, 16) == 0) {
1036                 RADIUS_DEBUG("Duplicate message from %s", from_addr);
1037                 data->counters.dup_access_requests++;
1038                 client->counters.dup_access_requests++;
1039
1040                 if (sess->last_reply) {
1041                         struct wpabuf *buf;
1042                         buf = radius_msg_get_buf(sess->last_reply);
1043                         res = sendto(data->auth_sock, wpabuf_head(buf),
1044                                      wpabuf_len(buf), 0,
1045                                      (struct sockaddr *) from, fromlen);
1046                         if (res < 0) {
1047                                 wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
1048                                            strerror(errno));
1049                         }
1050                         return 0;
1051                 }
1052
1053                 RADIUS_DEBUG("No previous reply available for duplicate "
1054                              "message");
1055                 return -1;
1056         }
1057                       
1058         eap = radius_msg_get_eap(msg);
1059         if (eap == NULL && sess->macacl) {
1060                 reply = radius_server_macacl(data, client, sess, msg);
1061                 if (reply == NULL)
1062                         return -1;
1063                 goto send_reply;
1064         }
1065         if (eap == NULL) {
1066                 RADIUS_DEBUG("No EAP-Message in RADIUS packet from %s",
1067                              from_addr);
1068                 data->counters.packets_dropped++;
1069                 client->counters.packets_dropped++;
1070                 return -1;
1071         }
1072
1073         RADIUS_DUMP("Received EAP data", wpabuf_head(eap), wpabuf_len(eap));
1074
1075         /* FIX: if Code is Request, Success, or Failure, send Access-Reject;
1076          * RFC3579 Sect. 2.6.2.
1077          * Include EAP-Response/Nak with no preferred method if
1078          * code == request.
1079          * If code is not 1-4, discard the packet silently.
1080          * Or is this already done by the EAP state machine? */
1081
1082         wpabuf_free(sess->eap_if->eapRespData);
1083         sess->eap_if->eapRespData = eap;
1084         sess->eap_if->eapResp = TRUE;
1085         eap_server_sm_step(sess->eap);
1086
1087         if ((sess->eap_if->eapReq || sess->eap_if->eapSuccess ||
1088              sess->eap_if->eapFail) && sess->eap_if->eapReqData) {
1089                 RADIUS_DUMP("EAP data from the state machine",
1090                             wpabuf_head(sess->eap_if->eapReqData),
1091                             wpabuf_len(sess->eap_if->eapReqData));
1092         } else if (sess->eap_if->eapFail) {
1093                 RADIUS_DEBUG("No EAP data from the state machine, but eapFail "
1094                              "set");
1095         } else if (eap_sm_method_pending(sess->eap)) {
1096                 radius_msg_free(sess->last_msg);
1097                 sess->last_msg = msg;
1098                 sess->last_from_port = from_port;
1099                 os_free(sess->last_from_addr);
1100                 sess->last_from_addr = os_strdup(from_addr);
1101                 sess->last_fromlen = fromlen;
1102                 os_memcpy(&sess->last_from, from, fromlen);
1103                 return -2;
1104         } else {
1105                 RADIUS_DEBUG("No EAP data from the state machine - ignore this"
1106                              " Access-Request silently (assuming it was a "
1107                              "duplicate)");
1108                 data->counters.packets_dropped++;
1109                 client->counters.packets_dropped++;
1110                 return -1;
1111         }
1112
1113         if (sess->eap_if->eapSuccess || sess->eap_if->eapFail)
1114                 is_complete = 1;
1115         if (sess->eap_if->eapFail)
1116                 srv_log(sess, "EAP authentication failed");
1117         else if (sess->eap_if->eapSuccess)
1118                 srv_log(sess, "EAP authentication succeeded");
1119
1120         reply = radius_server_encapsulate_eap(data, client, sess, msg);
1121
1122 send_reply:
1123         if (reply) {
1124                 struct wpabuf *buf;
1125                 struct radius_hdr *hdr;
1126
1127                 RADIUS_DEBUG("Reply to %s:%d", from_addr, from_port);
1128                 if (wpa_debug_level <= MSG_MSGDUMP) {
1129                         radius_msg_dump(reply);
1130                 }
1131
1132                 switch (radius_msg_get_hdr(reply)->code) {
1133                 case RADIUS_CODE_ACCESS_ACCEPT:
1134                         srv_log(sess, "Sending Access-Accept");
1135                         data->counters.access_accepts++;
1136                         client->counters.access_accepts++;
1137                         break;
1138                 case RADIUS_CODE_ACCESS_REJECT:
1139                         srv_log(sess, "Sending Access-Reject");
1140                         data->counters.access_rejects++;
1141                         client->counters.access_rejects++;
1142                         break;
1143                 case RADIUS_CODE_ACCESS_CHALLENGE:
1144                         data->counters.access_challenges++;
1145                         client->counters.access_challenges++;
1146                         break;
1147                 }
1148                 buf = radius_msg_get_buf(reply);
1149                 res = sendto(data->auth_sock, wpabuf_head(buf),
1150                              wpabuf_len(buf), 0,
1151                              (struct sockaddr *) from, fromlen);
1152                 if (res < 0) {
1153                         wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
1154                                    strerror(errno));
1155                 }
1156                 radius_msg_free(sess->last_reply);
1157                 sess->last_reply = reply;
1158                 sess->last_from_port = from_port;
1159                 hdr = radius_msg_get_hdr(msg);
1160                 sess->last_identifier = hdr->identifier;
1161                 os_memcpy(sess->last_authenticator, hdr->authenticator, 16);
1162         } else {
1163                 data->counters.packets_dropped++;
1164                 client->counters.packets_dropped++;
1165         }
1166
1167         if (is_complete) {
1168                 RADIUS_DEBUG("Removing completed session 0x%x after timeout",
1169                              sess->sess_id);
1170                 eloop_cancel_timeout(radius_server_session_remove_timeout,
1171                                      data, sess);
1172                 eloop_register_timeout(10, 0,
1173                                        radius_server_session_remove_timeout,
1174                                        data, sess);
1175         }
1176
1177         return 0;
1178 }
1179
1180
1181 static void radius_server_receive_auth(int sock, void *eloop_ctx,
1182                                        void *sock_ctx)
1183 {
1184         struct radius_server_data *data = eloop_ctx;
1185         u8 *buf = NULL;
1186         union {
1187                 struct sockaddr_storage ss;
1188                 struct sockaddr_in sin;
1189 #ifdef CONFIG_IPV6
1190                 struct sockaddr_in6 sin6;
1191 #endif /* CONFIG_IPV6 */
1192         } from;
1193         socklen_t fromlen;
1194         int len;
1195         struct radius_client *client = NULL;
1196         struct radius_msg *msg = NULL;
1197         char abuf[50];
1198         int from_port = 0;
1199
1200         buf = os_malloc(RADIUS_MAX_MSG_LEN);
1201         if (buf == NULL) {
1202                 goto fail;
1203         }
1204
1205         fromlen = sizeof(from);
1206         len = recvfrom(sock, buf, RADIUS_MAX_MSG_LEN, 0,
1207                        (struct sockaddr *) &from.ss, &fromlen);
1208         if (len < 0) {
1209                 wpa_printf(MSG_INFO, "recvfrom[radius_server]: %s",
1210                            strerror(errno));
1211                 goto fail;
1212         }
1213
1214 #ifdef CONFIG_IPV6
1215         if (data->ipv6) {
1216                 if (inet_ntop(AF_INET6, &from.sin6.sin6_addr, abuf,
1217                               sizeof(abuf)) == NULL)
1218                         abuf[0] = '\0';
1219                 from_port = ntohs(from.sin6.sin6_port);
1220                 RADIUS_DEBUG("Received %d bytes from %s:%d",
1221                              len, abuf, from_port);
1222
1223                 client = radius_server_get_client(data,
1224                                                   (struct in_addr *)
1225                                                   &from.sin6.sin6_addr, 1);
1226         }
1227 #endif /* CONFIG_IPV6 */
1228
1229         if (!data->ipv6) {
1230                 os_strlcpy(abuf, inet_ntoa(from.sin.sin_addr), sizeof(abuf));
1231                 from_port = ntohs(from.sin.sin_port);
1232                 RADIUS_DEBUG("Received %d bytes from %s:%d",
1233                              len, abuf, from_port);
1234
1235                 client = radius_server_get_client(data, &from.sin.sin_addr, 0);
1236         }
1237
1238         RADIUS_DUMP("Received data", buf, len);
1239
1240         if (client == NULL) {
1241                 RADIUS_DEBUG("Unknown client %s - packet ignored", abuf);
1242                 data->counters.invalid_requests++;
1243                 goto fail;
1244         }
1245
1246         msg = radius_msg_parse(buf, len);
1247         if (msg == NULL) {
1248                 RADIUS_DEBUG("Parsing incoming RADIUS frame failed");
1249                 data->counters.malformed_access_requests++;
1250                 client->counters.malformed_access_requests++;
1251                 goto fail;
1252         }
1253
1254         os_free(buf);
1255         buf = NULL;
1256
1257         if (wpa_debug_level <= MSG_MSGDUMP) {
1258                 radius_msg_dump(msg);
1259         }
1260
1261         if (radius_msg_get_hdr(msg)->code != RADIUS_CODE_ACCESS_REQUEST) {
1262                 RADIUS_DEBUG("Unexpected RADIUS code %d",
1263                              radius_msg_get_hdr(msg)->code);
1264                 data->counters.unknown_types++;
1265                 client->counters.unknown_types++;
1266                 goto fail;
1267         }
1268
1269         data->counters.access_requests++;
1270         client->counters.access_requests++;
1271
1272         if (radius_msg_verify_msg_auth(msg, (u8 *) client->shared_secret,
1273                                        client->shared_secret_len, NULL)) {
1274                 RADIUS_DEBUG("Invalid Message-Authenticator from %s", abuf);
1275                 data->counters.bad_authenticators++;
1276                 client->counters.bad_authenticators++;
1277                 goto fail;
1278         }
1279
1280         if (radius_server_request(data, msg, (struct sockaddr *) &from,
1281                                   fromlen, client, abuf, from_port, NULL) ==
1282             -2)
1283                 return; /* msg was stored with the session */
1284
1285 fail:
1286         radius_msg_free(msg);
1287         os_free(buf);
1288 }
1289
1290
1291 static void radius_server_receive_acct(int sock, void *eloop_ctx,
1292                                        void *sock_ctx)
1293 {
1294         struct radius_server_data *data = eloop_ctx;
1295         u8 *buf = NULL;
1296         union {
1297                 struct sockaddr_storage ss;
1298                 struct sockaddr_in sin;
1299 #ifdef CONFIG_IPV6
1300                 struct sockaddr_in6 sin6;
1301 #endif /* CONFIG_IPV6 */
1302         } from;
1303         socklen_t fromlen;
1304         int len, res;
1305         struct radius_client *client = NULL;
1306         struct radius_msg *msg = NULL, *resp = NULL;
1307         char abuf[50];
1308         int from_port = 0;
1309         struct radius_hdr *hdr;
1310         struct wpabuf *rbuf;
1311
1312         buf = os_malloc(RADIUS_MAX_MSG_LEN);
1313         if (buf == NULL) {
1314                 goto fail;
1315         }
1316
1317         fromlen = sizeof(from);
1318         len = recvfrom(sock, buf, RADIUS_MAX_MSG_LEN, 0,
1319                        (struct sockaddr *) &from.ss, &fromlen);
1320         if (len < 0) {
1321                 wpa_printf(MSG_INFO, "recvfrom[radius_server]: %s",
1322                            strerror(errno));
1323                 goto fail;
1324         }
1325
1326 #ifdef CONFIG_IPV6
1327         if (data->ipv6) {
1328                 if (inet_ntop(AF_INET6, &from.sin6.sin6_addr, abuf,
1329                               sizeof(abuf)) == NULL)
1330                         abuf[0] = '\0';
1331                 from_port = ntohs(from.sin6.sin6_port);
1332                 RADIUS_DEBUG("Received %d bytes from %s:%d",
1333                              len, abuf, from_port);
1334
1335                 client = radius_server_get_client(data,
1336                                                   (struct in_addr *)
1337                                                   &from.sin6.sin6_addr, 1);
1338         }
1339 #endif /* CONFIG_IPV6 */
1340
1341         if (!data->ipv6) {
1342                 os_strlcpy(abuf, inet_ntoa(from.sin.sin_addr), sizeof(abuf));
1343                 from_port = ntohs(from.sin.sin_port);
1344                 RADIUS_DEBUG("Received %d bytes from %s:%d",
1345                              len, abuf, from_port);
1346
1347                 client = radius_server_get_client(data, &from.sin.sin_addr, 0);
1348         }
1349
1350         RADIUS_DUMP("Received data", buf, len);
1351
1352         if (client == NULL) {
1353                 RADIUS_DEBUG("Unknown client %s - packet ignored", abuf);
1354                 data->counters.invalid_acct_requests++;
1355                 goto fail;
1356         }
1357
1358         msg = radius_msg_parse(buf, len);
1359         if (msg == NULL) {
1360                 RADIUS_DEBUG("Parsing incoming RADIUS frame failed");
1361                 data->counters.malformed_acct_requests++;
1362                 client->counters.malformed_acct_requests++;
1363                 goto fail;
1364         }
1365
1366         os_free(buf);
1367         buf = NULL;
1368
1369         if (wpa_debug_level <= MSG_MSGDUMP) {
1370                 radius_msg_dump(msg);
1371         }
1372
1373         if (radius_msg_get_hdr(msg)->code != RADIUS_CODE_ACCOUNTING_REQUEST) {
1374                 RADIUS_DEBUG("Unexpected RADIUS code %d",
1375                              radius_msg_get_hdr(msg)->code);
1376                 data->counters.unknown_acct_types++;
1377                 client->counters.unknown_acct_types++;
1378                 goto fail;
1379         }
1380
1381         data->counters.acct_requests++;
1382         client->counters.acct_requests++;
1383
1384         if (radius_msg_verify_acct_req(msg, (u8 *) client->shared_secret,
1385                                        client->shared_secret_len)) {
1386                 RADIUS_DEBUG("Invalid Authenticator from %s", abuf);
1387                 data->counters.acct_bad_authenticators++;
1388                 client->counters.acct_bad_authenticators++;
1389                 goto fail;
1390         }
1391
1392         /* TODO: Write accounting information to a file or database */
1393
1394         hdr = radius_msg_get_hdr(msg);
1395
1396         resp = radius_msg_new(RADIUS_CODE_ACCOUNTING_RESPONSE, hdr->identifier);
1397         if (resp == NULL)
1398                 goto fail;
1399
1400         radius_msg_finish_acct_resp(resp, (u8 *) client->shared_secret,
1401                                     client->shared_secret_len,
1402                                     hdr->authenticator);
1403
1404         RADIUS_DEBUG("Reply to %s:%d", abuf, from_port);
1405         if (wpa_debug_level <= MSG_MSGDUMP) {
1406                 radius_msg_dump(resp);
1407         }
1408         rbuf = radius_msg_get_buf(resp);
1409         data->counters.acct_responses++;
1410         client->counters.acct_responses++;
1411         res = sendto(data->acct_sock, wpabuf_head(rbuf), wpabuf_len(rbuf), 0,
1412                      (struct sockaddr *) &from.ss, fromlen);
1413         if (res < 0) {
1414                 wpa_printf(MSG_INFO, "sendto[RADIUS SRV]: %s",
1415                            strerror(errno));
1416         }
1417
1418 fail:
1419         radius_msg_free(resp);
1420         radius_msg_free(msg);
1421         os_free(buf);
1422 }
1423
1424
1425 static int radius_server_disable_pmtu_discovery(int s)
1426 {
1427         int r = -1;
1428 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1429         /* Turn off Path MTU discovery on IPv4/UDP sockets. */
1430         int action = IP_PMTUDISC_DONT;
1431         r = setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &action,
1432                        sizeof(action));
1433         if (r == -1)
1434                 wpa_printf(MSG_ERROR, "Failed to set IP_MTU_DISCOVER: "
1435                            "%s", strerror(errno));
1436 #endif
1437         return r;
1438 }
1439
1440
1441 static int radius_server_open_socket(int port)
1442 {
1443         int s;
1444         struct sockaddr_in addr;
1445
1446         s = socket(PF_INET, SOCK_DGRAM, 0);
1447         if (s < 0) {
1448                 wpa_printf(MSG_INFO, "RADIUS: socket: %s", strerror(errno));
1449                 return -1;
1450         }
1451
1452         radius_server_disable_pmtu_discovery(s);
1453
1454         os_memset(&addr, 0, sizeof(addr));
1455         addr.sin_family = AF_INET;
1456         addr.sin_port = htons(port);
1457         if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1458                 wpa_printf(MSG_INFO, "RADIUS: bind: %s", strerror(errno));
1459                 close(s);
1460                 return -1;
1461         }
1462
1463         return s;
1464 }
1465
1466
1467 #ifdef CONFIG_IPV6
1468 static int radius_server_open_socket6(int port)
1469 {
1470         int s;
1471         struct sockaddr_in6 addr;
1472
1473         s = socket(PF_INET6, SOCK_DGRAM, 0);
1474         if (s < 0) {
1475                 wpa_printf(MSG_INFO, "RADIUS: socket[IPv6]: %s",
1476                            strerror(errno));
1477                 return -1;
1478         }
1479
1480         os_memset(&addr, 0, sizeof(addr));
1481         addr.sin6_family = AF_INET6;
1482         os_memcpy(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any));
1483         addr.sin6_port = htons(port);
1484         if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1485                 wpa_printf(MSG_INFO, "RADIUS: bind: %s", strerror(errno));
1486                 close(s);
1487                 return -1;
1488         }
1489
1490         return s;
1491 }
1492 #endif /* CONFIG_IPV6 */
1493
1494
1495 static void radius_server_free_sessions(struct radius_server_data *data,
1496                                         struct radius_session *sessions)
1497 {
1498         struct radius_session *session, *prev;
1499
1500         session = sessions;
1501         while (session) {
1502                 prev = session;
1503                 session = session->next;
1504                 radius_server_session_free(data, prev);
1505         }
1506 }
1507
1508
1509 static void radius_server_free_clients(struct radius_server_data *data,
1510                                        struct radius_client *clients)
1511 {
1512         struct radius_client *client, *prev;
1513
1514         client = clients;
1515         while (client) {
1516                 prev = client;
1517                 client = client->next;
1518
1519                 radius_server_free_sessions(data, prev->sessions);
1520                 os_free(prev->shared_secret);
1521                 os_free(prev);
1522         }
1523 }
1524
1525
1526 static struct radius_client *
1527 radius_server_read_clients(const char *client_file, int ipv6)
1528 {
1529         FILE *f;
1530         const int buf_size = 1024;
1531         char *buf, *pos;
1532         struct radius_client *clients, *tail, *entry;
1533         int line = 0, mask, failed = 0, i;
1534         struct in_addr addr;
1535 #ifdef CONFIG_IPV6
1536         struct in6_addr addr6;
1537 #endif /* CONFIG_IPV6 */
1538         unsigned int val;
1539
1540         f = fopen(client_file, "r");
1541         if (f == NULL) {
1542                 RADIUS_ERROR("Could not open client file '%s'", client_file);
1543                 return NULL;
1544         }
1545
1546         buf = os_malloc(buf_size);
1547         if (buf == NULL) {
1548                 fclose(f);
1549                 return NULL;
1550         }
1551
1552         clients = tail = NULL;
1553         while (fgets(buf, buf_size, f)) {
1554                 /* Configuration file format:
1555                  * 192.168.1.0/24 secret
1556                  * 192.168.1.2 secret
1557                  * fe80::211:22ff:fe33:4455/64 secretipv6
1558                  */
1559                 line++;
1560                 buf[buf_size - 1] = '\0';
1561                 pos = buf;
1562                 while (*pos != '\0' && *pos != '\n')
1563                         pos++;
1564                 if (*pos == '\n')
1565                         *pos = '\0';
1566                 if (*buf == '\0' || *buf == '#')
1567                         continue;
1568
1569                 pos = buf;
1570                 while ((*pos >= '0' && *pos <= '9') || *pos == '.' ||
1571                        (*pos >= 'a' && *pos <= 'f') || *pos == ':' ||
1572                        (*pos >= 'A' && *pos <= 'F')) {
1573                         pos++;
1574                 }
1575
1576                 if (*pos == '\0') {
1577                         failed = 1;
1578                         break;
1579                 }
1580
1581                 if (*pos == '/') {
1582                         char *end;
1583                         *pos++ = '\0';
1584                         mask = strtol(pos, &end, 10);
1585                         if ((pos == end) ||
1586                             (mask < 0 || mask > (ipv6 ? 128 : 32))) {
1587                                 failed = 1;
1588                                 break;
1589                         }
1590                         pos = end;
1591                 } else {
1592                         mask = ipv6 ? 128 : 32;
1593                         *pos++ = '\0';
1594                 }
1595
1596                 if (!ipv6 && inet_aton(buf, &addr) == 0) {
1597                         failed = 1;
1598                         break;
1599                 }
1600 #ifdef CONFIG_IPV6
1601                 if (ipv6 && inet_pton(AF_INET6, buf, &addr6) <= 0) {
1602                         if (inet_pton(AF_INET, buf, &addr) <= 0) {
1603                                 failed = 1;
1604                                 break;
1605                         }
1606                         /* Convert IPv4 address to IPv6 */
1607                         if (mask <= 32)
1608                                 mask += (128 - 32);
1609                         os_memset(addr6.s6_addr, 0, 10);
1610                         addr6.s6_addr[10] = 0xff;
1611                         addr6.s6_addr[11] = 0xff;
1612                         os_memcpy(addr6.s6_addr + 12, (char *) &addr.s_addr,
1613                                   4);
1614                 }
1615 #endif /* CONFIG_IPV6 */
1616
1617                 while (*pos == ' ' || *pos == '\t') {
1618                         pos++;
1619                 }
1620
1621                 if (*pos == '\0') {
1622                         failed = 1;
1623                         break;
1624                 }
1625
1626                 entry = os_zalloc(sizeof(*entry));
1627                 if (entry == NULL) {
1628                         failed = 1;
1629                         break;
1630                 }
1631                 entry->shared_secret = os_strdup(pos);
1632                 if (entry->shared_secret == NULL) {
1633                         failed = 1;
1634                         os_free(entry);
1635                         break;
1636                 }
1637                 entry->shared_secret_len = os_strlen(entry->shared_secret);
1638                 if (!ipv6) {
1639                         entry->addr.s_addr = addr.s_addr;
1640                         val = 0;
1641                         for (i = 0; i < mask; i++)
1642                                 val |= 1 << (31 - i);
1643                         entry->mask.s_addr = htonl(val);
1644                 }
1645 #ifdef CONFIG_IPV6
1646                 if (ipv6) {
1647                         int offset = mask / 8;
1648
1649                         os_memcpy(entry->addr6.s6_addr, addr6.s6_addr, 16);
1650                         os_memset(entry->mask6.s6_addr, 0xff, offset);
1651                         val = 0;
1652                         for (i = 0; i < (mask % 8); i++)
1653                                 val |= 1 << (7 - i);
1654                         if (offset < 16)
1655                                 entry->mask6.s6_addr[offset] = val;
1656                 }
1657 #endif /* CONFIG_IPV6 */
1658
1659                 if (tail == NULL) {
1660                         clients = tail = entry;
1661                 } else {
1662                         tail->next = entry;
1663                         tail = entry;
1664                 }
1665         }
1666
1667         if (failed) {
1668                 RADIUS_ERROR("Invalid line %d in '%s'", line, client_file);
1669                 radius_server_free_clients(NULL, clients);
1670                 clients = NULL;
1671         }
1672
1673         os_free(buf);
1674         fclose(f);
1675
1676         return clients;
1677 }
1678
1679
1680 /**
1681  * radius_server_init - Initialize RADIUS server
1682  * @conf: Configuration for the RADIUS server
1683  * Returns: Pointer to private RADIUS server context or %NULL on failure
1684  *
1685  * This initializes a RADIUS server instance and returns a context pointer that
1686  * will be used in other calls to the RADIUS server module. The server can be
1687  * deinitialize by calling radius_server_deinit().
1688  */
1689 struct radius_server_data *
1690 radius_server_init(struct radius_server_conf *conf)
1691 {
1692         struct radius_server_data *data;
1693
1694 #ifndef CONFIG_IPV6
1695         if (conf->ipv6) {
1696                 wpa_printf(MSG_ERROR, "RADIUS server compiled without IPv6 support");
1697                 return NULL;
1698         }
1699 #endif /* CONFIG_IPV6 */
1700
1701         data = os_zalloc(sizeof(*data));
1702         if (data == NULL)
1703                 return NULL;
1704
1705         dl_list_init(&data->erp_keys);
1706         os_get_reltime(&data->start_time);
1707         data->conf_ctx = conf->conf_ctx;
1708         data->eap_sim_db_priv = conf->eap_sim_db_priv;
1709         data->ssl_ctx = conf->ssl_ctx;
1710         data->msg_ctx = conf->msg_ctx;
1711         data->ipv6 = conf->ipv6;
1712         if (conf->pac_opaque_encr_key) {
1713                 data->pac_opaque_encr_key = os_malloc(16);
1714                 os_memcpy(data->pac_opaque_encr_key, conf->pac_opaque_encr_key,
1715                           16);
1716         }
1717         if (conf->eap_fast_a_id) {
1718                 data->eap_fast_a_id = os_malloc(conf->eap_fast_a_id_len);
1719                 if (data->eap_fast_a_id) {
1720                         os_memcpy(data->eap_fast_a_id, conf->eap_fast_a_id,
1721                                   conf->eap_fast_a_id_len);
1722                         data->eap_fast_a_id_len = conf->eap_fast_a_id_len;
1723                 }
1724         }
1725         if (conf->eap_fast_a_id_info)
1726                 data->eap_fast_a_id_info = os_strdup(conf->eap_fast_a_id_info);
1727         data->eap_fast_prov = conf->eap_fast_prov;
1728         data->pac_key_lifetime = conf->pac_key_lifetime;
1729         data->pac_key_refresh_time = conf->pac_key_refresh_time;
1730         data->get_eap_user = conf->get_eap_user;
1731         data->eap_sim_aka_result_ind = conf->eap_sim_aka_result_ind;
1732         data->tnc = conf->tnc;
1733         data->wps = conf->wps;
1734         data->pwd_group = conf->pwd_group;
1735         data->server_id = conf->server_id;
1736         if (conf->eap_req_id_text) {
1737                 data->eap_req_id_text = os_malloc(conf->eap_req_id_text_len);
1738                 if (data->eap_req_id_text) {
1739                         os_memcpy(data->eap_req_id_text, conf->eap_req_id_text,
1740                                   conf->eap_req_id_text_len);
1741                         data->eap_req_id_text_len = conf->eap_req_id_text_len;
1742                 }
1743         }
1744         data->erp = conf->erp;
1745         data->erp_domain = conf->erp_domain;
1746
1747         if (conf->subscr_remediation_url) {
1748                 data->subscr_remediation_url =
1749                         os_strdup(conf->subscr_remediation_url);
1750         }
1751         data->subscr_remediation_method = conf->subscr_remediation_method;
1752
1753 #ifdef CONFIG_SQLITE
1754         if (conf->sqlite_file) {
1755                 if (sqlite3_open(conf->sqlite_file, &data->db)) {
1756                         RADIUS_ERROR("Could not open SQLite file '%s'",
1757                                      conf->sqlite_file);
1758                         radius_server_deinit(data);
1759                         return NULL;
1760                 }
1761         }
1762 #endif /* CONFIG_SQLITE */
1763
1764 #ifdef CONFIG_RADIUS_TEST
1765         if (conf->dump_msk_file)
1766                 data->dump_msk_file = os_strdup(conf->dump_msk_file);
1767 #endif /* CONFIG_RADIUS_TEST */
1768
1769         data->clients = radius_server_read_clients(conf->client_file,
1770                                                    conf->ipv6);
1771         if (data->clients == NULL) {
1772                 wpa_printf(MSG_ERROR, "No RADIUS clients configured");
1773                 radius_server_deinit(data);
1774                 return NULL;
1775         }
1776
1777 #ifdef CONFIG_IPV6
1778         if (conf->ipv6)
1779                 data->auth_sock = radius_server_open_socket6(conf->auth_port);
1780         else
1781 #endif /* CONFIG_IPV6 */
1782         data->auth_sock = radius_server_open_socket(conf->auth_port);
1783         if (data->auth_sock < 0) {
1784                 wpa_printf(MSG_ERROR, "Failed to open UDP socket for RADIUS authentication server");
1785                 radius_server_deinit(data);
1786                 return NULL;
1787         }
1788         if (eloop_register_read_sock(data->auth_sock,
1789                                      radius_server_receive_auth,
1790                                      data, NULL)) {
1791                 radius_server_deinit(data);
1792                 return NULL;
1793         }
1794
1795         if (conf->acct_port) {
1796 #ifdef CONFIG_IPV6
1797                 if (conf->ipv6)
1798                         data->acct_sock = radius_server_open_socket6(
1799                                 conf->acct_port);
1800                 else
1801 #endif /* CONFIG_IPV6 */
1802                 data->acct_sock = radius_server_open_socket(conf->acct_port);
1803                 if (data->acct_sock < 0) {
1804                         wpa_printf(MSG_ERROR, "Failed to open UDP socket for RADIUS accounting server");
1805                         radius_server_deinit(data);
1806                         return NULL;
1807                 }
1808                 if (eloop_register_read_sock(data->acct_sock,
1809                                              radius_server_receive_acct,
1810                                              data, NULL)) {
1811                         radius_server_deinit(data);
1812                         return NULL;
1813                 }
1814         } else {
1815                 data->acct_sock = -1;
1816         }
1817
1818         return data;
1819 }
1820
1821
1822 /**
1823  * radius_server_erp_flush - Flush all ERP keys
1824  * @data: RADIUS server context from radius_server_init()
1825  */
1826 void radius_server_erp_flush(struct radius_server_data *data)
1827 {
1828         struct eap_server_erp_key *erp;
1829
1830         if (data == NULL)
1831                 return;
1832         while ((erp = dl_list_first(&data->erp_keys, struct eap_server_erp_key,
1833                                     list)) != NULL) {
1834                 dl_list_del(&erp->list);
1835                 bin_clear_free(erp, sizeof(*erp));
1836         }
1837 }
1838
1839
1840 /**
1841  * radius_server_deinit - Deinitialize RADIUS server
1842  * @data: RADIUS server context from radius_server_init()
1843  */
1844 void radius_server_deinit(struct radius_server_data *data)
1845 {
1846         if (data == NULL)
1847                 return;
1848
1849         if (data->auth_sock >= 0) {
1850                 eloop_unregister_read_sock(data->auth_sock);
1851                 close(data->auth_sock);
1852         }
1853
1854         if (data->acct_sock >= 0) {
1855                 eloop_unregister_read_sock(data->acct_sock);
1856                 close(data->acct_sock);
1857         }
1858
1859         radius_server_free_clients(data, data->clients);
1860
1861         os_free(data->pac_opaque_encr_key);
1862         os_free(data->eap_fast_a_id);
1863         os_free(data->eap_fast_a_id_info);
1864         os_free(data->eap_req_id_text);
1865 #ifdef CONFIG_RADIUS_TEST
1866         os_free(data->dump_msk_file);
1867 #endif /* CONFIG_RADIUS_TEST */
1868         os_free(data->subscr_remediation_url);
1869
1870 #ifdef CONFIG_SQLITE
1871         if (data->db)
1872                 sqlite3_close(data->db);
1873 #endif /* CONFIG_SQLITE */
1874
1875         radius_server_erp_flush(data);
1876
1877         os_free(data);
1878 }
1879
1880
1881 /**
1882  * radius_server_get_mib - Get RADIUS server MIB information
1883  * @data: RADIUS server context from radius_server_init()
1884  * @buf: Buffer for returning the MIB data in text format
1885  * @buflen: buf length in octets
1886  * Returns: Number of octets written into buf
1887  */
1888 int radius_server_get_mib(struct radius_server_data *data, char *buf,
1889                           size_t buflen)
1890 {
1891         int ret, uptime;
1892         unsigned int idx;
1893         char *end, *pos;
1894         struct os_reltime now;
1895         struct radius_client *cli;
1896
1897         /* RFC 2619 - RADIUS Authentication Server MIB */
1898
1899         if (data == NULL || buflen == 0)
1900                 return 0;
1901
1902         pos = buf;
1903         end = buf + buflen;
1904
1905         os_get_reltime(&now);
1906         uptime = (now.sec - data->start_time.sec) * 100 +
1907                 ((now.usec - data->start_time.usec) / 10000) % 100;
1908         ret = os_snprintf(pos, end - pos,
1909                           "RADIUS-AUTH-SERVER-MIB\n"
1910                           "radiusAuthServIdent=hostapd\n"
1911                           "radiusAuthServUpTime=%d\n"
1912                           "radiusAuthServResetTime=0\n"
1913                           "radiusAuthServConfigReset=4\n",
1914                           uptime);
1915         if (os_snprintf_error(end - pos, ret)) {
1916                 *pos = '\0';
1917                 return pos - buf;
1918         }
1919         pos += ret;
1920
1921         ret = os_snprintf(pos, end - pos,
1922                           "radiusAuthServTotalAccessRequests=%u\n"
1923                           "radiusAuthServTotalInvalidRequests=%u\n"
1924                           "radiusAuthServTotalDupAccessRequests=%u\n"
1925                           "radiusAuthServTotalAccessAccepts=%u\n"
1926                           "radiusAuthServTotalAccessRejects=%u\n"
1927                           "radiusAuthServTotalAccessChallenges=%u\n"
1928                           "radiusAuthServTotalMalformedAccessRequests=%u\n"
1929                           "radiusAuthServTotalBadAuthenticators=%u\n"
1930                           "radiusAuthServTotalPacketsDropped=%u\n"
1931                           "radiusAuthServTotalUnknownTypes=%u\n"
1932                           "radiusAccServTotalRequests=%u\n"
1933                           "radiusAccServTotalInvalidRequests=%u\n"
1934                           "radiusAccServTotalResponses=%u\n"
1935                           "radiusAccServTotalMalformedRequests=%u\n"
1936                           "radiusAccServTotalBadAuthenticators=%u\n"
1937                           "radiusAccServTotalUnknownTypes=%u\n",
1938                           data->counters.access_requests,
1939                           data->counters.invalid_requests,
1940                           data->counters.dup_access_requests,
1941                           data->counters.access_accepts,
1942                           data->counters.access_rejects,
1943                           data->counters.access_challenges,
1944                           data->counters.malformed_access_requests,
1945                           data->counters.bad_authenticators,
1946                           data->counters.packets_dropped,
1947                           data->counters.unknown_types,
1948                           data->counters.acct_requests,
1949                           data->counters.invalid_acct_requests,
1950                           data->counters.acct_responses,
1951                           data->counters.malformed_acct_requests,
1952                           data->counters.acct_bad_authenticators,
1953                           data->counters.unknown_acct_types);
1954         if (os_snprintf_error(end - pos, ret)) {
1955                 *pos = '\0';
1956                 return pos - buf;
1957         }
1958         pos += ret;
1959
1960         for (cli = data->clients, idx = 0; cli; cli = cli->next, idx++) {
1961                 char abuf[50], mbuf[50];
1962 #ifdef CONFIG_IPV6
1963                 if (data->ipv6) {
1964                         if (inet_ntop(AF_INET6, &cli->addr6, abuf,
1965                                       sizeof(abuf)) == NULL)
1966                                 abuf[0] = '\0';
1967                         if (inet_ntop(AF_INET6, &cli->mask6, mbuf,
1968                                       sizeof(mbuf)) == NULL)
1969                                 mbuf[0] = '\0';
1970                 }
1971 #endif /* CONFIG_IPV6 */
1972                 if (!data->ipv6) {
1973                         os_strlcpy(abuf, inet_ntoa(cli->addr), sizeof(abuf));
1974                         os_strlcpy(mbuf, inet_ntoa(cli->mask), sizeof(mbuf));
1975                 }
1976
1977                 ret = os_snprintf(pos, end - pos,
1978                                   "radiusAuthClientIndex=%u\n"
1979                                   "radiusAuthClientAddress=%s/%s\n"
1980                                   "radiusAuthServAccessRequests=%u\n"
1981                                   "radiusAuthServDupAccessRequests=%u\n"
1982                                   "radiusAuthServAccessAccepts=%u\n"
1983                                   "radiusAuthServAccessRejects=%u\n"
1984                                   "radiusAuthServAccessChallenges=%u\n"
1985                                   "radiusAuthServMalformedAccessRequests=%u\n"
1986                                   "radiusAuthServBadAuthenticators=%u\n"
1987                                   "radiusAuthServPacketsDropped=%u\n"
1988                                   "radiusAuthServUnknownTypes=%u\n"
1989                                   "radiusAccServTotalRequests=%u\n"
1990                                   "radiusAccServTotalInvalidRequests=%u\n"
1991                                   "radiusAccServTotalResponses=%u\n"
1992                                   "radiusAccServTotalMalformedRequests=%u\n"
1993                                   "radiusAccServTotalBadAuthenticators=%u\n"
1994                                   "radiusAccServTotalUnknownTypes=%u\n",
1995                                   idx,
1996                                   abuf, mbuf,
1997                                   cli->counters.access_requests,
1998                                   cli->counters.dup_access_requests,
1999                                   cli->counters.access_accepts,
2000                                   cli->counters.access_rejects,
2001                                   cli->counters.access_challenges,
2002                                   cli->counters.malformed_access_requests,
2003                                   cli->counters.bad_authenticators,
2004                                   cli->counters.packets_dropped,
2005                                   cli->counters.unknown_types,
2006                                   cli->counters.acct_requests,
2007                                   cli->counters.invalid_acct_requests,
2008                                   cli->counters.acct_responses,
2009                                   cli->counters.malformed_acct_requests,
2010                                   cli->counters.acct_bad_authenticators,
2011                                   cli->counters.unknown_acct_types);
2012                 if (os_snprintf_error(end - pos, ret)) {
2013                         *pos = '\0';
2014                         return pos - buf;
2015                 }
2016                 pos += ret;
2017         }
2018
2019         return pos - buf;
2020 }
2021
2022
2023 static int radius_server_get_eap_user(void *ctx, const u8 *identity,
2024                                       size_t identity_len, int phase2,
2025                                       struct eap_user *user)
2026 {
2027         struct radius_session *sess = ctx;
2028         struct radius_server_data *data = sess->server;
2029         int ret;
2030
2031         ret = data->get_eap_user(data->conf_ctx, identity, identity_len,
2032                                  phase2, user);
2033         if (ret == 0 && user) {
2034                 sess->accept_attr = user->accept_attr;
2035                 sess->remediation = user->remediation;
2036                 sess->macacl = user->macacl;
2037         }
2038
2039         if (ret) {
2040                 RADIUS_DEBUG("%s: User-Name not found from user database",
2041                              __func__);
2042         }
2043
2044         return ret;
2045 }
2046
2047
2048 static const char * radius_server_get_eap_req_id_text(void *ctx, size_t *len)
2049 {
2050         struct radius_session *sess = ctx;
2051         struct radius_server_data *data = sess->server;
2052         *len = data->eap_req_id_text_len;
2053         return data->eap_req_id_text;
2054 }
2055
2056
2057 static void radius_server_log_msg(void *ctx, const char *msg)
2058 {
2059         struct radius_session *sess = ctx;
2060         srv_log(sess, "EAP: %s", msg);
2061 }
2062
2063
2064 #ifdef CONFIG_ERP
2065
2066 static const char * radius_server_get_erp_domain(void *ctx)
2067 {
2068         struct radius_session *sess = ctx;
2069         struct radius_server_data *data = sess->server;
2070
2071         return data->erp_domain;
2072 }
2073
2074
2075 static struct eap_server_erp_key *
2076 radius_server_erp_get_key(void *ctx, const char *keyname)
2077 {
2078         struct radius_session *sess = ctx;
2079         struct radius_server_data *data = sess->server;
2080         struct eap_server_erp_key *erp;
2081
2082         dl_list_for_each(erp, &data->erp_keys, struct eap_server_erp_key,
2083                          list) {
2084                 if (os_strcmp(erp->keyname_nai, keyname) == 0)
2085                         return erp;
2086         }
2087
2088         return NULL;
2089 }
2090
2091
2092 static int radius_server_erp_add_key(void *ctx, struct eap_server_erp_key *erp)
2093 {
2094         struct radius_session *sess = ctx;
2095         struct radius_server_data *data = sess->server;
2096
2097         dl_list_add(&data->erp_keys, &erp->list);
2098         return 0;
2099 }
2100
2101 #endif /* CONFIG_ERP */
2102
2103
2104 static const struct eapol_callbacks radius_server_eapol_cb =
2105 {
2106         .get_eap_user = radius_server_get_eap_user,
2107         .get_eap_req_id_text = radius_server_get_eap_req_id_text,
2108         .log_msg = radius_server_log_msg,
2109 #ifdef CONFIG_ERP
2110         .get_erp_send_reauth_start = NULL,
2111         .get_erp_domain = radius_server_get_erp_domain,
2112         .erp_get_key = radius_server_erp_get_key,
2113         .erp_add_key = radius_server_erp_add_key,
2114 #endif /* CONFIG_ERP */
2115 };
2116
2117
2118 /**
2119  * radius_server_eap_pending_cb - Pending EAP data notification
2120  * @data: RADIUS server context from radius_server_init()
2121  * @ctx: Pending EAP context pointer
2122  *
2123  * This function is used to notify EAP server module that a pending operation
2124  * has been completed and processing of the EAP session can proceed.
2125  */
2126 void radius_server_eap_pending_cb(struct radius_server_data *data, void *ctx)
2127 {
2128         struct radius_client *cli;
2129         struct radius_session *s, *sess = NULL;
2130         struct radius_msg *msg;
2131
2132         if (data == NULL)
2133                 return;
2134
2135         for (cli = data->clients; cli; cli = cli->next) {
2136                 for (s = cli->sessions; s; s = s->next) {
2137                         if (s->eap == ctx && s->last_msg) {
2138                                 sess = s;
2139                                 break;
2140                         }
2141                 }
2142                 if (sess)
2143                         break;
2144         }
2145
2146         if (sess == NULL) {
2147                 RADIUS_DEBUG("No session matched callback ctx");
2148                 return;
2149         }
2150
2151         msg = sess->last_msg;
2152         sess->last_msg = NULL;
2153         eap_sm_pending_cb(sess->eap);
2154         if (radius_server_request(data, msg,
2155                                   (struct sockaddr *) &sess->last_from,
2156                                   sess->last_fromlen, cli,
2157                                   sess->last_from_addr,
2158                                   sess->last_from_port, sess) == -2)
2159                 return; /* msg was stored with the session */
2160
2161         radius_msg_free(msg);
2162 }