Use type-punning to avoid breaking strict aliasing rules
[libeap.git] / src / radius / radius_server.c
1 /*
2  * hostapd / RADIUS authentication server
3  * Copyright (c) 2005-2008, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14
15 #include "includes.h"
16 #include <net/if.h>
17
18 #include "common.h"
19 #include "radius.h"
20 #include "eloop.h"
21 #include "defs.h"
22 #include "eap_server/eap.h"
23 #include "radius_server.h"
24
25 #define RADIUS_SESSION_TIMEOUT 60
26 #define RADIUS_MAX_SESSION 100
27 #define RADIUS_MAX_MSG_LEN 3000
28
29 static struct eapol_callbacks radius_server_eapol_cb;
30
31 struct radius_client;
32 struct radius_server_data;
33
34 struct radius_server_counters {
35         u32 access_requests;
36         u32 invalid_requests;
37         u32 dup_access_requests;
38         u32 access_accepts;
39         u32 access_rejects;
40         u32 access_challenges;
41         u32 malformed_access_requests;
42         u32 bad_authenticators;
43         u32 packets_dropped;
44         u32 unknown_types;
45 };
46
47 struct radius_session {
48         struct radius_session *next;
49         struct radius_client *client;
50         struct radius_server_data *server;
51         unsigned int sess_id;
52         struct eap_sm *eap;
53         struct eap_eapol_interface *eap_if;
54
55         struct radius_msg *last_msg;
56         char *last_from_addr;
57         int last_from_port;
58         struct sockaddr_storage last_from;
59         socklen_t last_fromlen;
60         u8 last_identifier;
61         struct radius_msg *last_reply;
62         u8 last_authenticator[16];
63 };
64
65 struct radius_client {
66         struct radius_client *next;
67         struct in_addr addr;
68         struct in_addr mask;
69 #ifdef CONFIG_IPV6
70         struct in6_addr addr6;
71         struct in6_addr mask6;
72 #endif /* CONFIG_IPV6 */
73         char *shared_secret;
74         int shared_secret_len;
75         struct radius_session *sessions;
76         struct radius_server_counters counters;
77 };
78
79 struct radius_server_data {
80         int auth_sock;
81         struct radius_client *clients;
82         unsigned int next_sess_id;
83         void *conf_ctx;
84         int num_sess;
85         void *eap_sim_db_priv;
86         void *ssl_ctx;
87         u8 *pac_opaque_encr_key;
88         u8 *eap_fast_a_id;
89         size_t eap_fast_a_id_len;
90         char *eap_fast_a_id_info;
91         int eap_fast_prov;
92         int pac_key_lifetime;
93         int pac_key_refresh_time;
94         int eap_sim_aka_result_ind;
95         int tnc;
96         struct wps_context *wps;
97         int ipv6;
98         struct os_time start_time;
99         struct radius_server_counters counters;
100         int (*get_eap_user)(void *ctx, const u8 *identity, size_t identity_len,
101                             int phase2, struct eap_user *user);
102         char *eap_req_id_text;
103         size_t eap_req_id_text_len;
104 };
105
106
107 extern int wpa_debug_level;
108
109 #define RADIUS_DEBUG(args...) \
110 wpa_printf(MSG_DEBUG, "RADIUS SRV: " args)
111 #define RADIUS_ERROR(args...) \
112 wpa_printf(MSG_ERROR, "RADIUS SRV: " args)
113 #define RADIUS_DUMP(args...) \
114 wpa_hexdump(MSG_MSGDUMP, "RADIUS SRV: " args)
115 #define RADIUS_DUMP_ASCII(args...) \
116 wpa_hexdump_ascii(MSG_MSGDUMP, "RADIUS SRV: " args)
117
118
119 static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx);
120
121
122
123 static struct radius_client *
124 radius_server_get_client(struct radius_server_data *data, struct in_addr *addr,
125                          int ipv6)
126 {
127         struct radius_client *client = data->clients;
128
129         while (client) {
130 #ifdef CONFIG_IPV6
131                 if (ipv6) {
132                         struct in6_addr *addr6;
133                         int i;
134
135                         addr6 = (struct in6_addr *) addr;
136                         for (i = 0; i < 16; i++) {
137                                 if ((addr6->s6_addr[i] &
138                                      client->mask6.s6_addr[i]) !=
139                                     (client->addr6.s6_addr[i] &
140                                      client->mask6.s6_addr[i])) {
141                                         i = 17;
142                                         break;
143                                 }
144                         }
145                         if (i == 16) {
146                                 break;
147                         }
148                 }
149 #endif /* CONFIG_IPV6 */
150                 if (!ipv6 && (client->addr.s_addr & client->mask.s_addr) ==
151                     (addr->s_addr & client->mask.s_addr)) {
152                         break;
153                 }
154
155                 client = client->next;
156         }
157
158         return client;
159 }
160
161
162 static struct radius_session *
163 radius_server_get_session(struct radius_client *client, unsigned int sess_id)
164 {
165         struct radius_session *sess = client->sessions;
166
167         while (sess) {
168                 if (sess->sess_id == sess_id) {
169                         break;
170                 }
171                 sess = sess->next;
172         }
173
174         return sess;
175 }
176
177
178 static void radius_server_session_free(struct radius_server_data *data,
179                                        struct radius_session *sess)
180 {
181         eloop_cancel_timeout(radius_server_session_timeout, data, sess);
182         eap_server_sm_deinit(sess->eap);
183         if (sess->last_msg) {
184                 radius_msg_free(sess->last_msg);
185                 os_free(sess->last_msg);
186         }
187         os_free(sess->last_from_addr);
188         if (sess->last_reply) {
189                 radius_msg_free(sess->last_reply);
190                 os_free(sess->last_reply);
191         }
192         os_free(sess);
193         data->num_sess--;
194 }
195
196
197 static void radius_server_session_remove_timeout(void *eloop_ctx,
198                                                  void *timeout_ctx);
199
200 static void radius_server_session_remove(struct radius_server_data *data,
201                                          struct radius_session *sess)
202 {
203         struct radius_client *client = sess->client;
204         struct radius_session *session, *prev;
205
206         eloop_cancel_timeout(radius_server_session_remove_timeout, data, sess);
207
208         prev = NULL;
209         session = client->sessions;
210         while (session) {
211                 if (session == sess) {
212                         if (prev == NULL) {
213                                 client->sessions = sess->next;
214                         } else {
215                                 prev->next = sess->next;
216                         }
217                         radius_server_session_free(data, sess);
218                         break;
219                 }
220                 prev = session;
221                 session = session->next;
222         }
223 }
224
225
226 static void radius_server_session_remove_timeout(void *eloop_ctx,
227                                                  void *timeout_ctx)
228 {
229         struct radius_server_data *data = eloop_ctx;
230         struct radius_session *sess = timeout_ctx;
231         RADIUS_DEBUG("Removing completed session 0x%x", sess->sess_id);
232         radius_server_session_remove(data, sess);
233 }
234
235
236 static void radius_server_session_timeout(void *eloop_ctx, void *timeout_ctx)
237 {
238         struct radius_server_data *data = eloop_ctx;
239         struct radius_session *sess = timeout_ctx;
240
241         RADIUS_DEBUG("Timing out authentication session 0x%x", sess->sess_id);
242         radius_server_session_remove(data, sess);
243 }
244
245
246 static struct radius_session *
247 radius_server_new_session(struct radius_server_data *data,
248                           struct radius_client *client)
249 {
250         struct radius_session *sess;
251
252         if (data->num_sess >= RADIUS_MAX_SESSION) {
253                 RADIUS_DEBUG("Maximum number of existing session - no room "
254                              "for a new session");
255                 return NULL;
256         }
257
258         sess = os_zalloc(sizeof(*sess));
259         if (sess == NULL)
260                 return NULL;
261
262         sess->server = data;
263         sess->client = client;
264         sess->sess_id = data->next_sess_id++;
265         sess->next = client->sessions;
266         client->sessions = sess;
267         eloop_register_timeout(RADIUS_SESSION_TIMEOUT, 0,
268                                radius_server_session_timeout, data, sess);
269         data->num_sess++;
270         return sess;
271 }
272
273
274 static struct radius_session *
275 radius_server_get_new_session(struct radius_server_data *data,
276                               struct radius_client *client,
277                               struct radius_msg *msg)
278 {
279         u8 *user;
280         size_t user_len;
281         int res;
282         struct radius_session *sess;
283         struct eap_config eap_conf;
284
285         RADIUS_DEBUG("Creating a new session");
286
287         user = os_malloc(256);
288         if (user == NULL) {
289                 return NULL;
290         }
291         res = radius_msg_get_attr(msg, RADIUS_ATTR_USER_NAME, user, 256);
292         if (res < 0 || res > 256) {
293                 RADIUS_DEBUG("Could not get User-Name");
294                 os_free(user);
295                 return NULL;
296         }
297         user_len = res;
298         RADIUS_DUMP_ASCII("User-Name", user, user_len);
299
300         res = data->get_eap_user(data->conf_ctx, user, user_len, 0, NULL);
301         os_free(user);
302
303         if (res == 0) {
304                 RADIUS_DEBUG("Matching user entry found");
305                 sess = radius_server_new_session(data, client);
306                 if (sess == NULL) {
307                         RADIUS_DEBUG("Failed to create a new session");
308                         return NULL;
309                 }
310         } else {
311                 RADIUS_DEBUG("User-Name not found from user database");
312                 return NULL;
313         }
314
315         os_memset(&eap_conf, 0, sizeof(eap_conf));
316         eap_conf.ssl_ctx = data->ssl_ctx;
317         eap_conf.eap_sim_db_priv = data->eap_sim_db_priv;
318         eap_conf.backend_auth = TRUE;
319         eap_conf.eap_server = 1;
320         eap_conf.pac_opaque_encr_key = data->pac_opaque_encr_key;
321         eap_conf.eap_fast_a_id = data->eap_fast_a_id;
322         eap_conf.eap_fast_a_id_len = data->eap_fast_a_id_len;
323         eap_conf.eap_fast_a_id_info = data->eap_fast_a_id_info;
324         eap_conf.eap_fast_prov = data->eap_fast_prov;
325         eap_conf.pac_key_lifetime = data->pac_key_lifetime;
326         eap_conf.pac_key_refresh_time = data->pac_key_refresh_time;
327         eap_conf.eap_sim_aka_result_ind = data->eap_sim_aka_result_ind;
328         eap_conf.tnc = data->tnc;
329         eap_conf.wps = data->wps;
330         sess->eap = eap_server_sm_init(sess, &radius_server_eapol_cb,
331                                        &eap_conf);
332         if (sess->eap == NULL) {
333                 RADIUS_DEBUG("Failed to initialize EAP state machine for the "
334                              "new session");
335                 radius_server_session_free(data, sess);
336                 return NULL;
337         }
338         sess->eap_if = eap_get_interface(sess->eap);
339         sess->eap_if->eapRestart = TRUE;
340         sess->eap_if->portEnabled = TRUE;
341
342         RADIUS_DEBUG("New session 0x%x initialized", sess->sess_id);
343
344         return sess;
345 }
346
347
348 static struct radius_msg *
349 radius_server_encapsulate_eap(struct radius_server_data *data,
350                               struct radius_client *client,
351                               struct radius_session *sess,
352                               struct radius_msg *request)
353 {
354         struct radius_msg *msg;
355         int code;
356         unsigned int sess_id;
357
358         if (sess->eap_if->eapFail) {
359                 sess->eap_if->eapFail = FALSE;
360                 code = RADIUS_CODE_ACCESS_REJECT;
361         } else if (sess->eap_if->eapSuccess) {
362                 sess->eap_if->eapSuccess = FALSE;
363                 code = RADIUS_CODE_ACCESS_ACCEPT;
364         } else {
365                 sess->eap_if->eapReq = FALSE;
366                 code = RADIUS_CODE_ACCESS_CHALLENGE;
367         }
368
369         msg = radius_msg_new(code, request->hdr->identifier);
370         if (msg == NULL) {
371                 RADIUS_DEBUG("Failed to allocate reply message");
372                 return NULL;
373         }
374
375         sess_id = htonl(sess->sess_id);
376         if (code == RADIUS_CODE_ACCESS_CHALLENGE &&
377             !radius_msg_add_attr(msg, RADIUS_ATTR_STATE,
378                                  (u8 *) &sess_id, sizeof(sess_id))) {
379                 RADIUS_DEBUG("Failed to add State attribute");
380         }
381
382         if (sess->eap_if->eapReqData &&
383             !radius_msg_add_eap(msg, wpabuf_head(sess->eap_if->eapReqData),
384                                 wpabuf_len(sess->eap_if->eapReqData))) {
385                 RADIUS_DEBUG("Failed to add EAP-Message attribute");
386         }
387
388         if (code == RADIUS_CODE_ACCESS_ACCEPT && sess->eap_if->eapKeyData) {
389                 int len;
390                 if (sess->eap_if->eapKeyDataLen > 64) {
391                         len = 32;
392                 } else {
393                         len = sess->eap_if->eapKeyDataLen / 2;
394                 }
395                 if (!radius_msg_add_mppe_keys(msg, request->hdr->authenticator,
396                                               (u8 *) client->shared_secret,
397                                               client->shared_secret_len,
398                                               sess->eap_if->eapKeyData + len,
399                                               len, sess->eap_if->eapKeyData,
400                                               len)) {
401                         RADIUS_DEBUG("Failed to add MPPE key attributes");
402                 }
403         }
404
405         if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
406                 RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
407                 radius_msg_free(msg);
408                 os_free(msg);
409                 return NULL;
410         }
411
412         if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
413                                   client->shared_secret_len,
414                                   request->hdr->authenticator) < 0) {
415                 RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
416         }
417
418         return msg;
419 }
420
421
422 static int radius_server_reject(struct radius_server_data *data,
423                                 struct radius_client *client,
424                                 struct radius_msg *request,
425                                 struct sockaddr *from, socklen_t fromlen,
426                                 const char *from_addr, int from_port)
427 {
428         struct radius_msg *msg;
429         int ret = 0;
430         struct eap_hdr eapfail;
431
432         RADIUS_DEBUG("Reject invalid request from %s:%d",
433                      from_addr, from_port);
434
435         msg = radius_msg_new(RADIUS_CODE_ACCESS_REJECT,
436                              request->hdr->identifier);
437         if (msg == NULL) {
438                 return -1;
439         }
440
441         os_memset(&eapfail, 0, sizeof(eapfail));
442         eapfail.code = EAP_CODE_FAILURE;
443         eapfail.identifier = 0;
444         eapfail.length = host_to_be16(sizeof(eapfail));
445
446         if (!radius_msg_add_eap(msg, (u8 *) &eapfail, sizeof(eapfail))) {
447                 RADIUS_DEBUG("Failed to add EAP-Message attribute");
448         }
449
450         if (radius_msg_copy_attr(msg, request, RADIUS_ATTR_PROXY_STATE) < 0) {
451                 RADIUS_DEBUG("Failed to copy Proxy-State attribute(s)");
452                 radius_msg_free(msg);
453                 os_free(msg);
454                 return -1;
455         }
456
457         if (radius_msg_finish_srv(msg, (u8 *) client->shared_secret,
458                                   client->shared_secret_len,
459                                   request->hdr->authenticator) < 0) {
460                 RADIUS_DEBUG("Failed to add Message-Authenticator attribute");
461         }
462
463         if (wpa_debug_level <= MSG_MSGDUMP) {
464                 radius_msg_dump(msg);
465         }
466
467         data->counters.access_rejects++;
468         client->counters.access_rejects++;
469         if (sendto(data->auth_sock, msg->buf, msg->buf_used, 0,
470                    (struct sockaddr *) from, sizeof(*from)) < 0) {
471                 perror("sendto[RADIUS SRV]");
472                 ret = -1;
473         }
474
475         radius_msg_free(msg);
476         os_free(msg);
477
478         return ret;
479 }
480
481
482 static int radius_server_request(struct radius_server_data *data,
483                                  struct radius_msg *msg,
484                                  struct sockaddr *from, socklen_t fromlen,
485                                  struct radius_client *client,
486                                  const char *from_addr, int from_port,
487                                  struct radius_session *force_sess)
488 {
489         u8 *eap = NULL;
490         size_t eap_len;
491         int res, state_included = 0;
492         u8 statebuf[4];
493         unsigned int state;
494         struct radius_session *sess;
495         struct radius_msg *reply;
496         int is_complete = 0;
497
498         if (force_sess)
499                 sess = force_sess;
500         else {
501                 res = radius_msg_get_attr(msg, RADIUS_ATTR_STATE, statebuf,
502                                           sizeof(statebuf));
503                 state_included = res >= 0;
504                 if (res == sizeof(statebuf)) {
505                         state = WPA_GET_BE32(statebuf);
506                         sess = radius_server_get_session(client, state);
507                 } else {
508                         sess = NULL;
509                 }
510         }
511
512         if (sess) {
513                 RADIUS_DEBUG("Request for session 0x%x", sess->sess_id);
514         } else if (state_included) {
515                 RADIUS_DEBUG("State attribute included but no session found");
516                 radius_server_reject(data, client, msg, from, fromlen,
517                                      from_addr, from_port);
518                 return -1;
519         } else {
520                 sess = radius_server_get_new_session(data, client, msg);
521                 if (sess == NULL) {
522                         RADIUS_DEBUG("Could not create a new session");
523                         radius_server_reject(data, client, msg, from, fromlen,
524                                              from_addr, from_port);
525                         return -1;
526                 }
527         }
528
529         if (sess->last_from_port == from_port &&
530             sess->last_identifier == msg->hdr->identifier &&
531             os_memcmp(sess->last_authenticator, msg->hdr->authenticator, 16) ==
532             0) {
533                 RADIUS_DEBUG("Duplicate message from %s", from_addr);
534                 data->counters.dup_access_requests++;
535                 client->counters.dup_access_requests++;
536
537                 if (sess->last_reply) {
538                         res = sendto(data->auth_sock, sess->last_reply->buf,
539                                      sess->last_reply->buf_used, 0,
540                                      (struct sockaddr *) from, fromlen);
541                         if (res < 0) {
542                                 perror("sendto[RADIUS SRV]");
543                         }
544                         return 0;
545                 }
546
547                 RADIUS_DEBUG("No previous reply available for duplicate "
548                              "message");
549                 return -1;
550         }
551                       
552         eap = radius_msg_get_eap(msg, &eap_len);
553         if (eap == NULL) {
554                 RADIUS_DEBUG("No EAP-Message in RADIUS packet from %s",
555                              from_addr);
556                 data->counters.packets_dropped++;
557                 client->counters.packets_dropped++;
558                 return -1;
559         }
560
561         RADIUS_DUMP("Received EAP data", eap, eap_len);
562
563         /* FIX: if Code is Request, Success, or Failure, send Access-Reject;
564          * RFC3579 Sect. 2.6.2.
565          * Include EAP-Response/Nak with no preferred method if
566          * code == request.
567          * If code is not 1-4, discard the packet silently.
568          * Or is this already done by the EAP state machine? */
569
570         wpabuf_free(sess->eap_if->eapRespData);
571         sess->eap_if->eapRespData = wpabuf_alloc_ext_data(eap, eap_len);
572         if (sess->eap_if->eapRespData == NULL)
573                 os_free(eap);
574         eap = NULL;
575         sess->eap_if->eapResp = TRUE;
576         eap_server_sm_step(sess->eap);
577
578         if ((sess->eap_if->eapReq || sess->eap_if->eapSuccess ||
579              sess->eap_if->eapFail) && sess->eap_if->eapReqData) {
580                 RADIUS_DUMP("EAP data from the state machine",
581                             wpabuf_head(sess->eap_if->eapReqData),
582                             wpabuf_len(sess->eap_if->eapReqData));
583         } else if (sess->eap_if->eapFail) {
584                 RADIUS_DEBUG("No EAP data from the state machine, but eapFail "
585                              "set");
586         } else if (eap_sm_method_pending(sess->eap)) {
587                 if (sess->last_msg) {
588                         radius_msg_free(sess->last_msg);
589                         os_free(sess->last_msg);
590                 }
591                 sess->last_msg = msg;
592                 sess->last_from_port = from_port;
593                 os_free(sess->last_from_addr);
594                 sess->last_from_addr = os_strdup(from_addr);
595                 sess->last_fromlen = fromlen;
596                 os_memcpy(&sess->last_from, from, fromlen);
597                 return -2;
598         } else {
599                 RADIUS_DEBUG("No EAP data from the state machine - ignore this"
600                              " Access-Request silently (assuming it was a "
601                              "duplicate)");
602                 data->counters.packets_dropped++;
603                 client->counters.packets_dropped++;
604                 return -1;
605         }
606
607         if (sess->eap_if->eapSuccess || sess->eap_if->eapFail)
608                 is_complete = 1;
609
610         reply = radius_server_encapsulate_eap(data, client, sess, msg);
611
612         if (reply) {
613                 RADIUS_DEBUG("Reply to %s:%d", from_addr, from_port);
614                 if (wpa_debug_level <= MSG_MSGDUMP) {
615                         radius_msg_dump(reply);
616                 }
617
618                 switch (reply->hdr->code) {
619                 case RADIUS_CODE_ACCESS_ACCEPT:
620                         data->counters.access_accepts++;
621                         client->counters.access_accepts++;
622                         break;
623                 case RADIUS_CODE_ACCESS_REJECT:
624                         data->counters.access_rejects++;
625                         client->counters.access_rejects++;
626                         break;
627                 case RADIUS_CODE_ACCESS_CHALLENGE:
628                         data->counters.access_challenges++;
629                         client->counters.access_challenges++;
630                         break;
631                 }
632                 res = sendto(data->auth_sock, reply->buf, reply->buf_used, 0,
633                              (struct sockaddr *) from, fromlen);
634                 if (res < 0) {
635                         perror("sendto[RADIUS SRV]");
636                 }
637                 if (sess->last_reply) {
638                         radius_msg_free(sess->last_reply);
639                         os_free(sess->last_reply);
640                 }
641                 sess->last_reply = reply;
642                 sess->last_from_port = from_port;
643                 sess->last_identifier = msg->hdr->identifier;
644                 os_memcpy(sess->last_authenticator, msg->hdr->authenticator,
645                           16);
646         } else {
647                 data->counters.packets_dropped++;
648                 client->counters.packets_dropped++;
649         }
650
651         if (is_complete) {
652                 RADIUS_DEBUG("Removing completed session 0x%x after timeout",
653                              sess->sess_id);
654                 eloop_cancel_timeout(radius_server_session_remove_timeout,
655                                      data, sess);
656                 eloop_register_timeout(10, 0,
657                                        radius_server_session_remove_timeout,
658                                        data, sess);
659         }
660
661         return 0;
662 }
663
664
665 static void radius_server_receive_auth(int sock, void *eloop_ctx,
666                                        void *sock_ctx)
667 {
668         struct radius_server_data *data = eloop_ctx;
669         u8 *buf = NULL;
670         union {
671                 struct sockaddr_storage ss;
672                 struct sockaddr_in sin;
673 #ifdef CONFIG_IPV6
674                 struct sockaddr_in6 sin6;
675 #endif /* CONFIG_IPV6 */
676         } from;
677         socklen_t fromlen;
678         int len;
679         struct radius_client *client = NULL;
680         struct radius_msg *msg = NULL;
681         char abuf[50];
682         int from_port = 0;
683
684         buf = os_malloc(RADIUS_MAX_MSG_LEN);
685         if (buf == NULL) {
686                 goto fail;
687         }
688
689         fromlen = sizeof(from);
690         len = recvfrom(sock, buf, RADIUS_MAX_MSG_LEN, 0,
691                        (struct sockaddr *) &from.ss, &fromlen);
692         if (len < 0) {
693                 perror("recvfrom[radius_server]");
694                 goto fail;
695         }
696
697 #ifdef CONFIG_IPV6
698         if (data->ipv6) {
699                 if (inet_ntop(AF_INET6, &from.sin6.sin6_addr, abuf,
700                               sizeof(abuf)) == NULL)
701                         abuf[0] = '\0';
702                 from_port = ntohs(from.sin6.sin6_port);
703                 RADIUS_DEBUG("Received %d bytes from %s:%d",
704                              len, abuf, from_port);
705
706                 client = radius_server_get_client(data,
707                                                   (struct in_addr *)
708                                                   &from.sin6.sin6_addr, 1);
709         }
710 #endif /* CONFIG_IPV6 */
711
712         if (!data->ipv6) {
713                 os_strlcpy(abuf, inet_ntoa(from.sin.sin_addr), sizeof(abuf));
714                 from_port = ntohs(from.sin.sin_port);
715                 RADIUS_DEBUG("Received %d bytes from %s:%d",
716                              len, abuf, from_port);
717
718                 client = radius_server_get_client(data, &from.sin.sin_addr, 0);
719         }
720
721         RADIUS_DUMP("Received data", buf, len);
722
723         if (client == NULL) {
724                 RADIUS_DEBUG("Unknown client %s - packet ignored", abuf);
725                 data->counters.invalid_requests++;
726                 goto fail;
727         }
728
729         msg = radius_msg_parse(buf, len);
730         if (msg == NULL) {
731                 RADIUS_DEBUG("Parsing incoming RADIUS frame failed");
732                 data->counters.malformed_access_requests++;
733                 client->counters.malformed_access_requests++;
734                 goto fail;
735         }
736
737         os_free(buf);
738         buf = NULL;
739
740         if (wpa_debug_level <= MSG_MSGDUMP) {
741                 radius_msg_dump(msg);
742         }
743
744         if (msg->hdr->code != RADIUS_CODE_ACCESS_REQUEST) {
745                 RADIUS_DEBUG("Unexpected RADIUS code %d", msg->hdr->code);
746                 data->counters.unknown_types++;
747                 client->counters.unknown_types++;
748                 goto fail;
749         }
750
751         data->counters.access_requests++;
752         client->counters.access_requests++;
753
754         if (radius_msg_verify_msg_auth(msg, (u8 *) client->shared_secret,
755                                        client->shared_secret_len, NULL)) {
756                 RADIUS_DEBUG("Invalid Message-Authenticator from %s", abuf);
757                 data->counters.bad_authenticators++;
758                 client->counters.bad_authenticators++;
759                 goto fail;
760         }
761
762         if (radius_server_request(data, msg, (struct sockaddr *) &from,
763                                   fromlen, client, abuf, from_port, NULL) ==
764             -2)
765                 return; /* msg was stored with the session */
766
767 fail:
768         if (msg) {
769                 radius_msg_free(msg);
770                 os_free(msg);
771         }
772         os_free(buf);
773 }
774
775
776 static int radius_server_disable_pmtu_discovery(int s)
777 {
778         int r = -1;
779 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
780         /* Turn off Path MTU discovery on IPv4/UDP sockets. */
781         int action = IP_PMTUDISC_DONT;
782         r = setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &action,
783                        sizeof(action));
784         if (r == -1)
785                 wpa_printf(MSG_ERROR, "Failed to set IP_MTU_DISCOVER: "
786                            "%s", strerror(errno));
787 #endif
788         return r;
789 }
790
791
792 static int radius_server_open_socket(int port)
793 {
794         int s;
795         struct sockaddr_in addr;
796
797         s = socket(PF_INET, SOCK_DGRAM, 0);
798         if (s < 0) {
799                 perror("socket");
800                 return -1;
801         }
802
803         radius_server_disable_pmtu_discovery(s);
804
805         os_memset(&addr, 0, sizeof(addr));
806         addr.sin_family = AF_INET;
807         addr.sin_port = htons(port);
808         if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
809                 perror("bind");
810                 close(s);
811                 return -1;
812         }
813
814         return s;
815 }
816
817
818 #ifdef CONFIG_IPV6
819 static int radius_server_open_socket6(int port)
820 {
821         int s;
822         struct sockaddr_in6 addr;
823
824         s = socket(PF_INET6, SOCK_DGRAM, 0);
825         if (s < 0) {
826                 perror("socket[IPv6]");
827                 return -1;
828         }
829
830         os_memset(&addr, 0, sizeof(addr));
831         addr.sin6_family = AF_INET6;
832         os_memcpy(&addr.sin6_addr, &in6addr_any, sizeof(in6addr_any));
833         addr.sin6_port = htons(port);
834         if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
835                 perror("bind");
836                 close(s);
837                 return -1;
838         }
839
840         return s;
841 }
842 #endif /* CONFIG_IPV6 */
843
844
845 static void radius_server_free_sessions(struct radius_server_data *data,
846                                         struct radius_session *sessions)
847 {
848         struct radius_session *session, *prev;
849
850         session = sessions;
851         while (session) {
852                 prev = session;
853                 session = session->next;
854                 radius_server_session_free(data, prev);
855         }
856 }
857
858
859 static void radius_server_free_clients(struct radius_server_data *data,
860                                        struct radius_client *clients)
861 {
862         struct radius_client *client, *prev;
863
864         client = clients;
865         while (client) {
866                 prev = client;
867                 client = client->next;
868
869                 radius_server_free_sessions(data, prev->sessions);
870                 os_free(prev->shared_secret);
871                 os_free(prev);
872         }
873 }
874
875
876 static struct radius_client *
877 radius_server_read_clients(const char *client_file, int ipv6)
878 {
879         FILE *f;
880         const int buf_size = 1024;
881         char *buf, *pos;
882         struct radius_client *clients, *tail, *entry;
883         int line = 0, mask, failed = 0, i;
884         struct in_addr addr;
885 #ifdef CONFIG_IPV6
886         struct in6_addr addr6;
887 #endif /* CONFIG_IPV6 */
888         unsigned int val;
889
890         f = fopen(client_file, "r");
891         if (f == NULL) {
892                 RADIUS_ERROR("Could not open client file '%s'", client_file);
893                 return NULL;
894         }
895
896         buf = os_malloc(buf_size);
897         if (buf == NULL) {
898                 fclose(f);
899                 return NULL;
900         }
901
902         clients = tail = NULL;
903         while (fgets(buf, buf_size, f)) {
904                 /* Configuration file format:
905                  * 192.168.1.0/24 secret
906                  * 192.168.1.2 secret
907                  * fe80::211:22ff:fe33:4455/64 secretipv6
908                  */
909                 line++;
910                 buf[buf_size - 1] = '\0';
911                 pos = buf;
912                 while (*pos != '\0' && *pos != '\n')
913                         pos++;
914                 if (*pos == '\n')
915                         *pos = '\0';
916                 if (*buf == '\0' || *buf == '#')
917                         continue;
918
919                 pos = buf;
920                 while ((*pos >= '0' && *pos <= '9') || *pos == '.' ||
921                        (*pos >= 'a' && *pos <= 'f') || *pos == ':' ||
922                        (*pos >= 'A' && *pos <= 'F')) {
923                         pos++;
924                 }
925
926                 if (*pos == '\0') {
927                         failed = 1;
928                         break;
929                 }
930
931                 if (*pos == '/') {
932                         char *end;
933                         *pos++ = '\0';
934                         mask = strtol(pos, &end, 10);
935                         if ((pos == end) ||
936                             (mask < 0 || mask > (ipv6 ? 128 : 32))) {
937                                 failed = 1;
938                                 break;
939                         }
940                         pos = end;
941                 } else {
942                         mask = ipv6 ? 128 : 32;
943                         *pos++ = '\0';
944                 }
945
946                 if (!ipv6 && inet_aton(buf, &addr) == 0) {
947                         failed = 1;
948                         break;
949                 }
950 #ifdef CONFIG_IPV6
951                 if (ipv6 && inet_pton(AF_INET6, buf, &addr6) <= 0) {
952                         if (inet_pton(AF_INET, buf, &addr) <= 0) {
953                                 failed = 1;
954                                 break;
955                         }
956                         /* Convert IPv4 address to IPv6 */
957                         if (mask <= 32)
958                                 mask += (128 - 32);
959                         os_memset(addr6.s6_addr, 0, 10);
960                         addr6.s6_addr[10] = 0xff;
961                         addr6.s6_addr[11] = 0xff;
962                         os_memcpy(addr6.s6_addr + 12, (char *) &addr.s_addr,
963                                   4);
964                 }
965 #endif /* CONFIG_IPV6 */
966
967                 while (*pos == ' ' || *pos == '\t') {
968                         pos++;
969                 }
970
971                 if (*pos == '\0') {
972                         failed = 1;
973                         break;
974                 }
975
976                 entry = os_zalloc(sizeof(*entry));
977                 if (entry == NULL) {
978                         failed = 1;
979                         break;
980                 }
981                 entry->shared_secret = os_strdup(pos);
982                 if (entry->shared_secret == NULL) {
983                         failed = 1;
984                         os_free(entry);
985                         break;
986                 }
987                 entry->shared_secret_len = os_strlen(entry->shared_secret);
988                 entry->addr.s_addr = addr.s_addr;
989                 if (!ipv6) {
990                         val = 0;
991                         for (i = 0; i < mask; i++)
992                                 val |= 1 << (31 - i);
993                         entry->mask.s_addr = htonl(val);
994                 }
995 #ifdef CONFIG_IPV6
996                 if (ipv6) {
997                         int offset = mask / 8;
998
999                         os_memcpy(entry->addr6.s6_addr, addr6.s6_addr, 16);
1000                         os_memset(entry->mask6.s6_addr, 0xff, offset);
1001                         val = 0;
1002                         for (i = 0; i < (mask % 8); i++)
1003                                 val |= 1 << (7 - i);
1004                         if (offset < 16)
1005                                 entry->mask6.s6_addr[offset] = val;
1006                 }
1007 #endif /* CONFIG_IPV6 */
1008
1009                 if (tail == NULL) {
1010                         clients = tail = entry;
1011                 } else {
1012                         tail->next = entry;
1013                         tail = entry;
1014                 }
1015         }
1016
1017         if (failed) {
1018                 RADIUS_ERROR("Invalid line %d in '%s'", line, client_file);
1019                 radius_server_free_clients(NULL, clients);
1020                 clients = NULL;
1021         }
1022
1023         os_free(buf);
1024         fclose(f);
1025
1026         return clients;
1027 }
1028
1029
1030 struct radius_server_data *
1031 radius_server_init(struct radius_server_conf *conf)
1032 {
1033         struct radius_server_data *data;
1034
1035 #ifndef CONFIG_IPV6
1036         if (conf->ipv6) {
1037                 fprintf(stderr, "RADIUS server compiled without IPv6 "
1038                         "support.\n");
1039                 return NULL;
1040         }
1041 #endif /* CONFIG_IPV6 */
1042
1043         data = os_zalloc(sizeof(*data));
1044         if (data == NULL)
1045                 return NULL;
1046
1047         os_get_time(&data->start_time);
1048         data->conf_ctx = conf->conf_ctx;
1049         data->eap_sim_db_priv = conf->eap_sim_db_priv;
1050         data->ssl_ctx = conf->ssl_ctx;
1051         data->ipv6 = conf->ipv6;
1052         if (conf->pac_opaque_encr_key) {
1053                 data->pac_opaque_encr_key = os_malloc(16);
1054                 os_memcpy(data->pac_opaque_encr_key, conf->pac_opaque_encr_key,
1055                           16);
1056         }
1057         if (conf->eap_fast_a_id) {
1058                 data->eap_fast_a_id = os_malloc(conf->eap_fast_a_id_len);
1059                 if (data->eap_fast_a_id) {
1060                         os_memcpy(data->eap_fast_a_id, conf->eap_fast_a_id,
1061                                   conf->eap_fast_a_id_len);
1062                         data->eap_fast_a_id_len = conf->eap_fast_a_id_len;
1063                 }
1064         }
1065         if (conf->eap_fast_a_id_info)
1066                 data->eap_fast_a_id_info = os_strdup(conf->eap_fast_a_id_info);
1067         data->eap_fast_prov = conf->eap_fast_prov;
1068         data->pac_key_lifetime = conf->pac_key_lifetime;
1069         data->pac_key_refresh_time = conf->pac_key_refresh_time;
1070         data->get_eap_user = conf->get_eap_user;
1071         data->eap_sim_aka_result_ind = conf->eap_sim_aka_result_ind;
1072         data->tnc = conf->tnc;
1073         data->wps = conf->wps;
1074         if (conf->eap_req_id_text) {
1075                 data->eap_req_id_text = os_malloc(conf->eap_req_id_text_len);
1076                 if (data->eap_req_id_text) {
1077                         os_memcpy(data->eap_req_id_text, conf->eap_req_id_text,
1078                                   conf->eap_req_id_text_len);
1079                         data->eap_req_id_text_len = conf->eap_req_id_text_len;
1080                 }
1081         }
1082
1083         data->clients = radius_server_read_clients(conf->client_file,
1084                                                    conf->ipv6);
1085         if (data->clients == NULL) {
1086                 printf("No RADIUS clients configured.\n");
1087                 radius_server_deinit(data);
1088                 return NULL;
1089         }
1090
1091 #ifdef CONFIG_IPV6
1092         if (conf->ipv6)
1093                 data->auth_sock = radius_server_open_socket6(conf->auth_port);
1094         else
1095 #endif /* CONFIG_IPV6 */
1096         data->auth_sock = radius_server_open_socket(conf->auth_port);
1097         if (data->auth_sock < 0) {
1098                 printf("Failed to open UDP socket for RADIUS authentication "
1099                        "server\n");
1100                 radius_server_deinit(data);
1101                 return NULL;
1102         }
1103         if (eloop_register_read_sock(data->auth_sock,
1104                                      radius_server_receive_auth,
1105                                      data, NULL)) {
1106                 radius_server_deinit(data);
1107                 return NULL;
1108         }
1109
1110         return data;
1111 }
1112
1113
1114 void radius_server_deinit(struct radius_server_data *data)
1115 {
1116         if (data == NULL)
1117                 return;
1118
1119         if (data->auth_sock >= 0) {
1120                 eloop_unregister_read_sock(data->auth_sock);
1121                 close(data->auth_sock);
1122         }
1123
1124         radius_server_free_clients(data, data->clients);
1125
1126         os_free(data->pac_opaque_encr_key);
1127         os_free(data->eap_fast_a_id);
1128         os_free(data->eap_fast_a_id_info);
1129         os_free(data->eap_req_id_text);
1130         os_free(data);
1131 }
1132
1133
1134 int radius_server_get_mib(struct radius_server_data *data, char *buf,
1135                           size_t buflen)
1136 {
1137         int ret, uptime;
1138         unsigned int idx;
1139         char *end, *pos;
1140         struct os_time now;
1141         struct radius_client *cli;
1142
1143         /* RFC 2619 - RADIUS Authentication Server MIB */
1144
1145         if (data == NULL || buflen == 0)
1146                 return 0;
1147
1148         pos = buf;
1149         end = buf + buflen;
1150
1151         os_get_time(&now);
1152         uptime = (now.sec - data->start_time.sec) * 100 +
1153                 ((now.usec - data->start_time.usec) / 10000) % 100;
1154         ret = os_snprintf(pos, end - pos,
1155                           "RADIUS-AUTH-SERVER-MIB\n"
1156                           "radiusAuthServIdent=hostapd\n"
1157                           "radiusAuthServUpTime=%d\n"
1158                           "radiusAuthServResetTime=0\n"
1159                           "radiusAuthServConfigReset=4\n",
1160                           uptime);
1161         if (ret < 0 || ret >= end - pos) {
1162                 *pos = '\0';
1163                 return pos - buf;
1164         }
1165         pos += ret;
1166
1167         ret = os_snprintf(pos, end - pos,
1168                           "radiusAuthServTotalAccessRequests=%u\n"
1169                           "radiusAuthServTotalInvalidRequests=%u\n"
1170                           "radiusAuthServTotalDupAccessRequests=%u\n"
1171                           "radiusAuthServTotalAccessAccepts=%u\n"
1172                           "radiusAuthServTotalAccessRejects=%u\n"
1173                           "radiusAuthServTotalAccessChallenges=%u\n"
1174                           "radiusAuthServTotalMalformedAccessRequests=%u\n"
1175                           "radiusAuthServTotalBadAuthenticators=%u\n"
1176                           "radiusAuthServTotalPacketsDropped=%u\n"
1177                           "radiusAuthServTotalUnknownTypes=%u\n",
1178                           data->counters.access_requests,
1179                           data->counters.invalid_requests,
1180                           data->counters.dup_access_requests,
1181                           data->counters.access_accepts,
1182                           data->counters.access_rejects,
1183                           data->counters.access_challenges,
1184                           data->counters.malformed_access_requests,
1185                           data->counters.bad_authenticators,
1186                           data->counters.packets_dropped,
1187                           data->counters.unknown_types);
1188         if (ret < 0 || ret >= end - pos) {
1189                 *pos = '\0';
1190                 return pos - buf;
1191         }
1192         pos += ret;
1193
1194         for (cli = data->clients, idx = 0; cli; cli = cli->next, idx++) {
1195                 char abuf[50], mbuf[50];
1196 #ifdef CONFIG_IPV6
1197                 if (data->ipv6) {
1198                         if (inet_ntop(AF_INET6, &cli->addr6, abuf,
1199                                       sizeof(abuf)) == NULL)
1200                                 abuf[0] = '\0';
1201                         if (inet_ntop(AF_INET6, &cli->mask6, abuf,
1202                                       sizeof(mbuf)) == NULL)
1203                                 mbuf[0] = '\0';
1204                 }
1205 #endif /* CONFIG_IPV6 */
1206                 if (!data->ipv6) {
1207                         os_strlcpy(abuf, inet_ntoa(cli->addr), sizeof(abuf));
1208                         os_strlcpy(mbuf, inet_ntoa(cli->mask), sizeof(mbuf));
1209                 }
1210
1211                 ret = os_snprintf(pos, end - pos,
1212                                   "radiusAuthClientIndex=%u\n"
1213                                   "radiusAuthClientAddress=%s/%s\n"
1214                                   "radiusAuthServAccessRequests=%u\n"
1215                                   "radiusAuthServDupAccessRequests=%u\n"
1216                                   "radiusAuthServAccessAccepts=%u\n"
1217                                   "radiusAuthServAccessRejects=%u\n"
1218                                   "radiusAuthServAccessChallenges=%u\n"
1219                                   "radiusAuthServMalformedAccessRequests=%u\n"
1220                                   "radiusAuthServBadAuthenticators=%u\n"
1221                                   "radiusAuthServPacketsDropped=%u\n"
1222                                   "radiusAuthServUnknownTypes=%u\n",
1223                                   idx,
1224                                   abuf, mbuf,
1225                                   cli->counters.access_requests,
1226                                   cli->counters.dup_access_requests,
1227                                   cli->counters.access_accepts,
1228                                   cli->counters.access_rejects,
1229                                   cli->counters.access_challenges,
1230                                   cli->counters.malformed_access_requests,
1231                                   cli->counters.bad_authenticators,
1232                                   cli->counters.packets_dropped,
1233                                   cli->counters.unknown_types);
1234                 if (ret < 0 || ret >= end - pos) {
1235                         *pos = '\0';
1236                         return pos - buf;
1237                 }
1238                 pos += ret;
1239         }
1240
1241         return pos - buf;
1242 }
1243
1244
1245 static int radius_server_get_eap_user(void *ctx, const u8 *identity,
1246                                       size_t identity_len, int phase2,
1247                                       struct eap_user *user)
1248 {
1249         struct radius_session *sess = ctx;
1250         struct radius_server_data *data = sess->server;
1251
1252         return data->get_eap_user(data->conf_ctx, identity, identity_len,
1253                                   phase2, user);
1254 }
1255
1256
1257 static const char * radius_server_get_eap_req_id_text(void *ctx, size_t *len)
1258 {
1259         struct radius_session *sess = ctx;
1260         struct radius_server_data *data = sess->server;
1261         *len = data->eap_req_id_text_len;
1262         return data->eap_req_id_text;
1263 }
1264
1265
1266 static struct eapol_callbacks radius_server_eapol_cb =
1267 {
1268         .get_eap_user = radius_server_get_eap_user,
1269         .get_eap_req_id_text = radius_server_get_eap_req_id_text,
1270 };
1271
1272
1273 void radius_server_eap_pending_cb(struct radius_server_data *data, void *ctx)
1274 {
1275         struct radius_client *cli;
1276         struct radius_session *s, *sess = NULL;
1277         struct radius_msg *msg;
1278
1279         if (data == NULL)
1280                 return;
1281
1282         for (cli = data->clients; cli; cli = cli->next) {
1283                 for (s = cli->sessions; s; s = s->next) {
1284                         if (s->eap == ctx && s->last_msg) {
1285                                 sess = s;
1286                                 break;
1287                         }
1288                         if (sess)
1289                                 break;
1290                 }
1291                 if (sess)
1292                         break;
1293         }
1294
1295         if (sess == NULL) {
1296                 RADIUS_DEBUG("No session matched callback ctx");
1297                 return;
1298         }
1299
1300         msg = sess->last_msg;
1301         sess->last_msg = NULL;
1302         eap_sm_pending_cb(sess->eap);
1303         if (radius_server_request(data, msg,
1304                                   (struct sockaddr *) &sess->last_from,
1305                                   sess->last_fromlen, cli,
1306                                   sess->last_from_addr,
1307                                   sess->last_from_port, sess) == -2)
1308                 return; /* msg was stored with the session */
1309
1310         radius_msg_free(msg);
1311         os_free(msg);
1312 }