Add EAPOL authenticator event callback
[libeap.git] / hostapd / ieee802_1x.c
1 /*
2  * hostapd / IEEE 802.1X-2004 Authenticator
3  * Copyright (c) 2002-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
17 #include "common.h"
18 #include "hostapd.h"
19 #include "ieee802_1x.h"
20 #include "accounting.h"
21 #include "radius/radius.h"
22 #include "radius/radius_client.h"
23 #include "eapol_sm.h"
24 #include "md5.h"
25 #include "crypto.h"
26 #include "eloop.h"
27 #include "sta_flags.h"
28 #include "sta_info.h"
29 #include "wpa.h"
30 #include "preauth.h"
31 #include "pmksa_cache.h"
32 #include "driver_i.h"
33 #include "hw_features.h"
34 #include "eap_server/eap.h"
35 #include "common/ieee802_11_defs.h"
36 #include "common/wpa_ctrl.h"
37
38
39 static void ieee802_1x_finished(struct hostapd_data *hapd,
40                                 struct sta_info *sta, int success);
41
42
43 static void ieee802_1x_send(struct hostapd_data *hapd, struct sta_info *sta,
44                             u8 type, const u8 *data, size_t datalen)
45 {
46         u8 *buf;
47         struct ieee802_1x_hdr *xhdr;
48         size_t len;
49         int encrypt = 0;
50
51         len = sizeof(*xhdr) + datalen;
52         buf = os_zalloc(len);
53         if (buf == NULL) {
54                 wpa_printf(MSG_ERROR, "malloc() failed for "
55                            "ieee802_1x_send(len=%lu)",
56                            (unsigned long) len);
57                 return;
58         }
59
60         xhdr = (struct ieee802_1x_hdr *) buf;
61         xhdr->version = hapd->conf->eapol_version;
62         xhdr->type = type;
63         xhdr->length = host_to_be16(datalen);
64
65         if (datalen > 0 && data != NULL)
66                 os_memcpy(xhdr + 1, data, datalen);
67
68         if (wpa_auth_pairwise_set(sta->wpa_sm))
69                 encrypt = 1;
70         if (sta->flags & WLAN_STA_PREAUTH) {
71                 rsn_preauth_send(hapd, sta, buf, len);
72         } else {
73                 hostapd_send_eapol(hapd, sta->addr, buf, len, encrypt);
74         }
75
76         os_free(buf);
77 }
78
79
80 void ieee802_1x_set_sta_authorized(struct hostapd_data *hapd,
81                                    struct sta_info *sta, int authorized)
82 {
83         int res;
84
85         if (sta->flags & WLAN_STA_PREAUTH)
86                 return;
87
88         if (authorized) {
89                 if (!(sta->flags & WLAN_STA_AUTHORIZED))
90                         wpa_msg(hapd->msg_ctx, MSG_INFO,
91                                 AP_STA_CONNECTED MACSTR, MAC2STR(sta->addr));
92                 sta->flags |= WLAN_STA_AUTHORIZED;
93                 res = hostapd_sta_set_flags(hapd, sta->addr, sta->flags,
94                                             WLAN_STA_AUTHORIZED, ~0);
95                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
96                                HOSTAPD_LEVEL_DEBUG, "authorizing port");
97         } else {
98                 if ((sta->flags & (WLAN_STA_AUTHORIZED | WLAN_STA_ASSOC)) ==
99                     (WLAN_STA_AUTHORIZED | WLAN_STA_ASSOC))
100                         wpa_msg(hapd->msg_ctx, MSG_INFO,
101                                 AP_STA_DISCONNECTED MACSTR,
102                                 MAC2STR(sta->addr));
103                 sta->flags &= ~WLAN_STA_AUTHORIZED;
104                 res = hostapd_sta_set_flags(hapd, sta->addr, sta->flags,
105                                             0, ~WLAN_STA_AUTHORIZED);
106                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
107                                HOSTAPD_LEVEL_DEBUG, "unauthorizing port");
108         }
109
110         if (res && errno != ENOENT) {
111                 printf("Could not set station " MACSTR " flags for kernel "
112                        "driver (errno=%d).\n", MAC2STR(sta->addr), errno);
113         }
114
115         if (authorized)
116                 accounting_sta_start(hapd, sta);
117 }
118
119
120 static void ieee802_1x_tx_key_one(struct hostapd_data *hapd,
121                                   struct sta_info *sta,
122                                   int idx, int broadcast,
123                                   u8 *key_data, size_t key_len)
124 {
125         u8 *buf, *ekey;
126         struct ieee802_1x_hdr *hdr;
127         struct ieee802_1x_eapol_key *key;
128         size_t len, ekey_len;
129         struct eapol_state_machine *sm = sta->eapol_sm;
130
131         if (sm == NULL)
132                 return;
133
134         len = sizeof(*key) + key_len;
135         buf = os_zalloc(sizeof(*hdr) + len);
136         if (buf == NULL)
137                 return;
138
139         hdr = (struct ieee802_1x_hdr *) buf;
140         key = (struct ieee802_1x_eapol_key *) (hdr + 1);
141         key->type = EAPOL_KEY_TYPE_RC4;
142         key->key_length = htons(key_len);
143         wpa_get_ntp_timestamp(key->replay_counter);
144
145         if (os_get_random(key->key_iv, sizeof(key->key_iv))) {
146                 wpa_printf(MSG_ERROR, "Could not get random numbers");
147                 os_free(buf);
148                 return;
149         }
150
151         key->key_index = idx | (broadcast ? 0 : BIT(7));
152         if (hapd->conf->eapol_key_index_workaround) {
153                 /* According to some information, WinXP Supplicant seems to
154                  * interpret bit7 as an indication whether the key is to be
155                  * activated, so make it possible to enable workaround that
156                  * sets this bit for all keys. */
157                 key->key_index |= BIT(7);
158         }
159
160         /* Key is encrypted using "Key-IV + MSK[0..31]" as the RC4-key and
161          * MSK[32..63] is used to sign the message. */
162         if (sm->eap_if->eapKeyData == NULL || sm->eap_if->eapKeyDataLen < 64) {
163                 wpa_printf(MSG_ERROR, "No eapKeyData available for encrypting "
164                            "and signing EAPOL-Key");
165                 os_free(buf);
166                 return;
167         }
168         os_memcpy((u8 *) (key + 1), key_data, key_len);
169         ekey_len = sizeof(key->key_iv) + 32;
170         ekey = os_malloc(ekey_len);
171         if (ekey == NULL) {
172                 wpa_printf(MSG_ERROR, "Could not encrypt key");
173                 os_free(buf);
174                 return;
175         }
176         os_memcpy(ekey, key->key_iv, sizeof(key->key_iv));
177         os_memcpy(ekey + sizeof(key->key_iv), sm->eap_if->eapKeyData, 32);
178         rc4_skip(ekey, ekey_len, 0, (u8 *) (key + 1), key_len);
179         os_free(ekey);
180
181         /* This header is needed here for HMAC-MD5, but it will be regenerated
182          * in ieee802_1x_send() */
183         hdr->version = hapd->conf->eapol_version;
184         hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
185         hdr->length = host_to_be16(len);
186         hmac_md5(sm->eap_if->eapKeyData + 32, 32, buf, sizeof(*hdr) + len,
187                  key->key_signature);
188
189         wpa_printf(MSG_DEBUG, "IEEE 802.1X: Sending EAPOL-Key to " MACSTR
190                    " (%s index=%d)", MAC2STR(sm->addr),
191                    broadcast ? "broadcast" : "unicast", idx);
192         ieee802_1x_send(hapd, sta, IEEE802_1X_TYPE_EAPOL_KEY, (u8 *) key, len);
193         if (sta->eapol_sm)
194                 sta->eapol_sm->dot1xAuthEapolFramesTx++;
195         os_free(buf);
196 }
197
198
199 #ifndef CONFIG_NO_VLAN
200 static struct hostapd_wep_keys *
201 ieee802_1x_group_alloc(struct hostapd_data *hapd, const char *ifname)
202 {
203         struct hostapd_wep_keys *key;
204
205         key = os_zalloc(sizeof(*key));
206         if (key == NULL)
207                 return NULL;
208
209         key->default_len = hapd->conf->default_wep_key_len;
210
211         if (key->idx >= hapd->conf->broadcast_key_idx_max ||
212             key->idx < hapd->conf->broadcast_key_idx_min)
213                 key->idx = hapd->conf->broadcast_key_idx_min;
214         else
215                 key->idx++;
216
217         if (!key->key[key->idx])
218                 key->key[key->idx] = os_malloc(key->default_len);
219         if (key->key[key->idx] == NULL ||
220             os_get_random(key->key[key->idx], key->default_len)) {
221                 printf("Could not generate random WEP key (dynamic VLAN).\n");
222                 os_free(key->key[key->idx]);
223                 key->key[key->idx] = NULL;
224                 os_free(key);
225                 return NULL;
226         }
227         key->len[key->idx] = key->default_len;
228
229         wpa_printf(MSG_DEBUG, "%s: Default WEP idx %d for dynamic VLAN\n",
230                    ifname, key->idx);
231         wpa_hexdump_key(MSG_DEBUG, "Default WEP key (dynamic VLAN)",
232                         key->key[key->idx], key->len[key->idx]);
233
234         if (hostapd_set_key(ifname, hapd, WPA_ALG_WEP, NULL, key->idx, 1,
235                             NULL, 0, key->key[key->idx], key->len[key->idx]))
236                 printf("Could not set dynamic VLAN WEP encryption key.\n");
237
238         hostapd_set_ieee8021x(ifname, hapd, 1);
239
240         return key;
241 }
242
243
244 static struct hostapd_wep_keys *
245 ieee802_1x_get_group(struct hostapd_data *hapd, struct hostapd_ssid *ssid,
246                      size_t vlan_id)
247 {
248         const char *ifname;
249
250         if (vlan_id == 0)
251                 return &ssid->wep;
252
253         if (vlan_id <= ssid->max_dyn_vlan_keys && ssid->dyn_vlan_keys &&
254             ssid->dyn_vlan_keys[vlan_id])
255                 return ssid->dyn_vlan_keys[vlan_id];
256
257         wpa_printf(MSG_DEBUG, "IEEE 802.1X: Creating new group "
258                    "state machine for VLAN ID %lu",
259                    (unsigned long) vlan_id);
260
261         ifname = hostapd_get_vlan_id_ifname(hapd->conf->vlan, vlan_id);
262         if (ifname == NULL) {
263                 wpa_printf(MSG_DEBUG, "IEEE 802.1X: Unknown VLAN ID %lu - "
264                            "cannot create group key state machine",
265                            (unsigned long) vlan_id);
266                 return NULL;
267         }
268
269         if (ssid->dyn_vlan_keys == NULL) {
270                 int size = (vlan_id + 1) * sizeof(ssid->dyn_vlan_keys[0]);
271                 ssid->dyn_vlan_keys = os_zalloc(size);
272                 if (ssid->dyn_vlan_keys == NULL)
273                         return NULL;
274                 ssid->max_dyn_vlan_keys = vlan_id;
275         }
276
277         if (ssid->max_dyn_vlan_keys < vlan_id) {
278                 struct hostapd_wep_keys **na;
279                 int size = (vlan_id + 1) * sizeof(ssid->dyn_vlan_keys[0]);
280                 na = os_realloc(ssid->dyn_vlan_keys, size);
281                 if (na == NULL)
282                         return NULL;
283                 ssid->dyn_vlan_keys = na;
284                 os_memset(&ssid->dyn_vlan_keys[ssid->max_dyn_vlan_keys + 1], 0,
285                           (vlan_id - ssid->max_dyn_vlan_keys) *
286                           sizeof(ssid->dyn_vlan_keys[0]));
287                 ssid->max_dyn_vlan_keys = vlan_id;
288         }
289
290         ssid->dyn_vlan_keys[vlan_id] = ieee802_1x_group_alloc(hapd, ifname);
291
292         return ssid->dyn_vlan_keys[vlan_id];
293 }
294 #endif /* CONFIG_NO_VLAN */
295
296
297 void ieee802_1x_tx_key(struct hostapd_data *hapd, struct sta_info *sta)
298 {
299         struct eapol_authenticator *eapol = hapd->eapol_auth;
300         struct eapol_state_machine *sm = sta->eapol_sm;
301 #ifndef CONFIG_NO_VLAN
302         struct hostapd_wep_keys *key = NULL;
303         int vlan_id;
304 #endif /* CONFIG_NO_VLAN */
305
306         if (sm == NULL || !sm->eap_if->eapKeyData)
307                 return;
308
309         wpa_printf(MSG_DEBUG, "IEEE 802.1X: Sending EAPOL-Key(s) to " MACSTR,
310                    MAC2STR(sta->addr));
311
312 #ifndef CONFIG_NO_VLAN
313         vlan_id = sta->vlan_id;
314         if (vlan_id < 0 || vlan_id > MAX_VLAN_ID)
315                 vlan_id = 0;
316
317         if (vlan_id) {
318                 key = ieee802_1x_get_group(hapd, sta->ssid, vlan_id);
319                 if (key && key->key[key->idx])
320                         ieee802_1x_tx_key_one(hapd, sta, key->idx, 1,
321                                               key->key[key->idx],
322                                               key->len[key->idx]);
323         } else
324 #endif /* CONFIG_NO_VLAN */
325         if (eapol->default_wep_key) {
326                 ieee802_1x_tx_key_one(hapd, sta, eapol->default_wep_key_idx, 1,
327                                       eapol->default_wep_key,
328                                       hapd->conf->default_wep_key_len);
329         }
330
331         if (hapd->conf->individual_wep_key_len > 0) {
332                 u8 *ikey;
333                 ikey = os_malloc(hapd->conf->individual_wep_key_len);
334                 if (ikey == NULL ||
335                     os_get_random(ikey, hapd->conf->individual_wep_key_len)) {
336                         wpa_printf(MSG_ERROR, "Could not generate random "
337                                    "individual WEP key.");
338                         os_free(ikey);
339                         return;
340                 }
341
342                 wpa_hexdump_key(MSG_DEBUG, "Individual WEP key",
343                                 ikey, hapd->conf->individual_wep_key_len);
344
345                 ieee802_1x_tx_key_one(hapd, sta, 0, 0, ikey,
346                                       hapd->conf->individual_wep_key_len);
347
348                 /* TODO: set encryption in TX callback, i.e., only after STA
349                  * has ACKed EAPOL-Key frame */
350                 if (hostapd_set_key(hapd->conf->iface, hapd, WPA_ALG_WEP,
351                                     sta->addr, 0, 1, NULL, 0, ikey,
352                                     hapd->conf->individual_wep_key_len)) {
353                         wpa_printf(MSG_ERROR, "Could not set individual WEP "
354                                    "encryption.");
355                 }
356
357                 os_free(ikey);
358         }
359 }
360
361
362 const char *radius_mode_txt(struct hostapd_data *hapd)
363 {
364         if (hapd->iface->current_mode == NULL)
365                 return "802.11";
366
367         switch (hapd->iface->current_mode->mode) {
368         case HOSTAPD_MODE_IEEE80211A:
369                 return "802.11a";
370         case HOSTAPD_MODE_IEEE80211G:
371                 return "802.11g";
372         case HOSTAPD_MODE_IEEE80211B:
373         default:
374                 return "802.11b";
375         }
376 }
377
378
379 int radius_sta_rate(struct hostapd_data *hapd, struct sta_info *sta)
380 {
381         int i;
382         u8 rate = 0;
383
384         for (i = 0; i < sta->supported_rates_len; i++)
385                 if ((sta->supported_rates[i] & 0x7f) > rate)
386                         rate = sta->supported_rates[i] & 0x7f;
387
388         return rate;
389 }
390
391
392 #ifndef CONFIG_NO_RADIUS
393 static void ieee802_1x_learn_identity(struct hostapd_data *hapd,
394                                       struct eapol_state_machine *sm,
395                                       const u8 *eap, size_t len)
396 {
397         const u8 *identity;
398         size_t identity_len;
399
400         if (len <= sizeof(struct eap_hdr) ||
401             eap[sizeof(struct eap_hdr)] != EAP_TYPE_IDENTITY)
402                 return;
403
404         identity = eap_get_identity(sm->eap, &identity_len);
405         if (identity == NULL)
406                 return;
407
408         /* Save station identity for future RADIUS packets */
409         os_free(sm->identity);
410         sm->identity = os_malloc(identity_len + 1);
411         if (sm->identity == NULL) {
412                 sm->identity_len = 0;
413                 return;
414         }
415
416         os_memcpy(sm->identity, identity, identity_len);
417         sm->identity_len = identity_len;
418         sm->identity[identity_len] = '\0';
419         hostapd_logger(hapd, sm->addr, HOSTAPD_MODULE_IEEE8021X,
420                        HOSTAPD_LEVEL_DEBUG, "STA identity '%s'", sm->identity);
421         sm->dot1xAuthEapolRespIdFramesRx++;
422 }
423
424
425 static void ieee802_1x_encapsulate_radius(struct hostapd_data *hapd,
426                                           struct sta_info *sta,
427                                           const u8 *eap, size_t len)
428 {
429         struct radius_msg *msg;
430         char buf[128];
431         struct eapol_state_machine *sm = sta->eapol_sm;
432
433         if (sm == NULL)
434                 return;
435
436         ieee802_1x_learn_identity(hapd, sm, eap, len);
437
438         wpa_printf(MSG_DEBUG, "Encapsulating EAP message into a RADIUS "
439                    "packet");
440
441         sm->radius_identifier = radius_client_get_id(hapd->radius);
442         msg = radius_msg_new(RADIUS_CODE_ACCESS_REQUEST,
443                              sm->radius_identifier);
444         if (msg == NULL) {
445                 printf("Could not create net RADIUS packet\n");
446                 return;
447         }
448
449         radius_msg_make_authenticator(msg, (u8 *) sta, sizeof(*sta));
450
451         if (sm->identity &&
452             !radius_msg_add_attr(msg, RADIUS_ATTR_USER_NAME,
453                                  sm->identity, sm->identity_len)) {
454                 printf("Could not add User-Name\n");
455                 goto fail;
456         }
457
458         if (hapd->conf->own_ip_addr.af == AF_INET &&
459             !radius_msg_add_attr(msg, RADIUS_ATTR_NAS_IP_ADDRESS,
460                                  (u8 *) &hapd->conf->own_ip_addr.u.v4, 4)) {
461                 printf("Could not add NAS-IP-Address\n");
462                 goto fail;
463         }
464
465 #ifdef CONFIG_IPV6
466         if (hapd->conf->own_ip_addr.af == AF_INET6 &&
467             !radius_msg_add_attr(msg, RADIUS_ATTR_NAS_IPV6_ADDRESS,
468                                  (u8 *) &hapd->conf->own_ip_addr.u.v6, 16)) {
469                 printf("Could not add NAS-IPv6-Address\n");
470                 goto fail;
471         }
472 #endif /* CONFIG_IPV6 */
473
474         if (hapd->conf->nas_identifier &&
475             !radius_msg_add_attr(msg, RADIUS_ATTR_NAS_IDENTIFIER,
476                                  (u8 *) hapd->conf->nas_identifier,
477                                  os_strlen(hapd->conf->nas_identifier))) {
478                 printf("Could not add NAS-Identifier\n");
479                 goto fail;
480         }
481
482         if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_NAS_PORT, sta->aid)) {
483                 printf("Could not add NAS-Port\n");
484                 goto fail;
485         }
486
487         os_snprintf(buf, sizeof(buf), RADIUS_802_1X_ADDR_FORMAT ":%s",
488                     MAC2STR(hapd->own_addr), hapd->conf->ssid.ssid);
489         buf[sizeof(buf) - 1] = '\0';
490         if (!radius_msg_add_attr(msg, RADIUS_ATTR_CALLED_STATION_ID,
491                                  (u8 *) buf, os_strlen(buf))) {
492                 printf("Could not add Called-Station-Id\n");
493                 goto fail;
494         }
495
496         os_snprintf(buf, sizeof(buf), RADIUS_802_1X_ADDR_FORMAT,
497                     MAC2STR(sta->addr));
498         buf[sizeof(buf) - 1] = '\0';
499         if (!radius_msg_add_attr(msg, RADIUS_ATTR_CALLING_STATION_ID,
500                                  (u8 *) buf, os_strlen(buf))) {
501                 printf("Could not add Calling-Station-Id\n");
502                 goto fail;
503         }
504
505         /* TODO: should probably check MTU from driver config; 2304 is max for
506          * IEEE 802.11, but use 1400 to avoid problems with too large packets
507          */
508         if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_FRAMED_MTU, 1400)) {
509                 printf("Could not add Framed-MTU\n");
510                 goto fail;
511         }
512
513         if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_NAS_PORT_TYPE,
514                                        RADIUS_NAS_PORT_TYPE_IEEE_802_11)) {
515                 printf("Could not add NAS-Port-Type\n");
516                 goto fail;
517         }
518
519         if (sta->flags & WLAN_STA_PREAUTH) {
520                 os_strlcpy(buf, "IEEE 802.11i Pre-Authentication",
521                            sizeof(buf));
522         } else {
523                 os_snprintf(buf, sizeof(buf), "CONNECT %d%sMbps %s",
524                             radius_sta_rate(hapd, sta) / 2,
525                             (radius_sta_rate(hapd, sta) & 1) ? ".5" : "",
526                             radius_mode_txt(hapd));
527                 buf[sizeof(buf) - 1] = '\0';
528         }
529         if (!radius_msg_add_attr(msg, RADIUS_ATTR_CONNECT_INFO,
530                                  (u8 *) buf, os_strlen(buf))) {
531                 printf("Could not add Connect-Info\n");
532                 goto fail;
533         }
534
535         if (eap && !radius_msg_add_eap(msg, eap, len)) {
536                 printf("Could not add EAP-Message\n");
537                 goto fail;
538         }
539
540         /* State attribute must be copied if and only if this packet is
541          * Access-Request reply to the previous Access-Challenge */
542         if (sm->last_recv_radius && sm->last_recv_radius->hdr->code ==
543             RADIUS_CODE_ACCESS_CHALLENGE) {
544                 int res = radius_msg_copy_attr(msg, sm->last_recv_radius,
545                                                RADIUS_ATTR_STATE);
546                 if (res < 0) {
547                         printf("Could not copy State attribute from previous "
548                                "Access-Challenge\n");
549                         goto fail;
550                 }
551                 if (res > 0) {
552                         wpa_printf(MSG_DEBUG, "Copied RADIUS State Attribute");
553                 }
554         }
555
556         radius_client_send(hapd->radius, msg, RADIUS_AUTH, sta->addr);
557         return;
558
559  fail:
560         radius_msg_free(msg);
561         os_free(msg);
562 }
563 #endif /* CONFIG_NO_RADIUS */
564
565
566 static void handle_eap_response(struct hostapd_data *hapd,
567                                 struct sta_info *sta, struct eap_hdr *eap,
568                                 size_t len)
569 {
570         u8 type, *data;
571         struct eapol_state_machine *sm = sta->eapol_sm;
572         if (sm == NULL)
573                 return;
574
575         data = (u8 *) (eap + 1);
576
577         if (len < sizeof(*eap) + 1) {
578                 printf("handle_eap_response: too short response data\n");
579                 return;
580         }
581
582         sm->eap_type_supp = type = data[0];
583
584         hostapd_logger(hapd, sm->addr, HOSTAPD_MODULE_IEEE8021X,
585                        HOSTAPD_LEVEL_DEBUG, "received EAP packet (code=%d "
586                        "id=%d len=%d) from STA: EAP Response-%s (%d)",
587                        eap->code, eap->identifier, be_to_host16(eap->length),
588                        eap_server_get_name(0, type), type);
589
590         sm->dot1xAuthEapolRespFramesRx++;
591
592         wpabuf_free(sm->eap_if->eapRespData);
593         sm->eap_if->eapRespData = wpabuf_alloc_copy(eap, len);
594         sm->eapolEap = TRUE;
595 }
596
597
598 /* Process incoming EAP packet from Supplicant */
599 static void handle_eap(struct hostapd_data *hapd, struct sta_info *sta,
600                        u8 *buf, size_t len)
601 {
602         struct eap_hdr *eap;
603         u16 eap_len;
604
605         if (len < sizeof(*eap)) {
606                 printf("   too short EAP packet\n");
607                 return;
608         }
609
610         eap = (struct eap_hdr *) buf;
611
612         eap_len = be_to_host16(eap->length);
613         wpa_printf(MSG_DEBUG, "EAP: code=%d identifier=%d length=%d",
614                    eap->code, eap->identifier, eap_len);
615         if (eap_len < sizeof(*eap)) {
616                 wpa_printf(MSG_DEBUG, "   Invalid EAP length");
617                 return;
618         } else if (eap_len > len) {
619                 wpa_printf(MSG_DEBUG, "   Too short frame to contain this EAP "
620                            "packet");
621                 return;
622         } else if (eap_len < len) {
623                 wpa_printf(MSG_DEBUG, "   Ignoring %lu extra bytes after EAP "
624                            "packet", (unsigned long) len - eap_len);
625         }
626
627         switch (eap->code) {
628         case EAP_CODE_REQUEST:
629                 wpa_printf(MSG_DEBUG, " (request)");
630                 return;
631         case EAP_CODE_RESPONSE:
632                 wpa_printf(MSG_DEBUG, " (response)");
633                 handle_eap_response(hapd, sta, eap, eap_len);
634                 break;
635         case EAP_CODE_SUCCESS:
636                 wpa_printf(MSG_DEBUG, " (success)");
637                 return;
638         case EAP_CODE_FAILURE:
639                 wpa_printf(MSG_DEBUG, " (failure)");
640                 return;
641         default:
642                 wpa_printf(MSG_DEBUG, " (unknown code)");
643                 return;
644         }
645 }
646
647
648 static struct eapol_state_machine *
649 ieee802_1x_alloc_eapol_sm(struct hostapd_data *hapd, struct sta_info *sta)
650 {
651         int flags = 0;
652         if (sta->flags & WLAN_STA_PREAUTH)
653                 flags |= EAPOL_SM_PREAUTH;
654         if (sta->wpa_sm) {
655                 if (wpa_auth_sta_get_pmksa(sta->wpa_sm))
656                         flags |= EAPOL_SM_USES_WPA;
657                 if (wpa_auth_sta_get_pmksa(sta->wpa_sm))
658                         flags |= EAPOL_SM_FROM_PMKSA_CACHE;
659         }
660         return eapol_auth_alloc(hapd->eapol_auth, sta->addr, flags, sta);
661 }
662
663
664 /**
665  * ieee802_1x_receive - Process the EAPOL frames from the Supplicant
666  * @hapd: hostapd BSS data
667  * @sa: Source address (sender of the EAPOL frame)
668  * @buf: EAPOL frame
669  * @len: Length of buf in octets
670  *
671  * This function is called for each incoming EAPOL frame from the interface
672  */
673 void ieee802_1x_receive(struct hostapd_data *hapd, const u8 *sa, const u8 *buf,
674                         size_t len)
675 {
676         struct sta_info *sta;
677         struct ieee802_1x_hdr *hdr;
678         struct ieee802_1x_eapol_key *key;
679         u16 datalen;
680         struct rsn_pmksa_cache_entry *pmksa;
681
682         if (!hapd->conf->ieee802_1x && !hapd->conf->wpa &&
683             !hapd->conf->wps_state)
684                 return;
685
686         wpa_printf(MSG_DEBUG, "IEEE 802.1X: %lu bytes from " MACSTR,
687                    (unsigned long) len, MAC2STR(sa));
688         sta = ap_get_sta(hapd, sa);
689         if (!sta || !(sta->flags & WLAN_STA_ASSOC)) {
690                 wpa_printf(MSG_DEBUG, "IEEE 802.1X data frame from not "
691                            "associated STA");
692                 return;
693         }
694
695         if (len < sizeof(*hdr)) {
696                 printf("   too short IEEE 802.1X packet\n");
697                 return;
698         }
699
700         hdr = (struct ieee802_1x_hdr *) buf;
701         datalen = be_to_host16(hdr->length);
702         wpa_printf(MSG_DEBUG, "   IEEE 802.1X: version=%d type=%d length=%d",
703                    hdr->version, hdr->type, datalen);
704
705         if (len - sizeof(*hdr) < datalen) {
706                 printf("   frame too short for this IEEE 802.1X packet\n");
707                 if (sta->eapol_sm)
708                         sta->eapol_sm->dot1xAuthEapLengthErrorFramesRx++;
709                 return;
710         }
711         if (len - sizeof(*hdr) > datalen) {
712                 wpa_printf(MSG_DEBUG, "   ignoring %lu extra octets after "
713                            "IEEE 802.1X packet",
714                            (unsigned long) len - sizeof(*hdr) - datalen);
715         }
716
717         if (sta->eapol_sm) {
718                 sta->eapol_sm->dot1xAuthLastEapolFrameVersion = hdr->version;
719                 sta->eapol_sm->dot1xAuthEapolFramesRx++;
720         }
721
722         key = (struct ieee802_1x_eapol_key *) (hdr + 1);
723         if (datalen >= sizeof(struct ieee802_1x_eapol_key) &&
724             hdr->type == IEEE802_1X_TYPE_EAPOL_KEY &&
725             (key->type == EAPOL_KEY_TYPE_WPA ||
726              key->type == EAPOL_KEY_TYPE_RSN)) {
727                 wpa_receive(hapd->wpa_auth, sta->wpa_sm, (u8 *) hdr,
728                             sizeof(*hdr) + datalen);
729                 return;
730         }
731
732         if ((!hapd->conf->ieee802_1x &&
733              !(sta->flags & (WLAN_STA_WPS | WLAN_STA_MAYBE_WPS))) ||
734             wpa_key_mgmt_wpa_psk(wpa_auth_sta_key_mgmt(sta->wpa_sm)))
735                 return;
736
737         if (!sta->eapol_sm) {
738                 sta->eapol_sm = ieee802_1x_alloc_eapol_sm(hapd, sta);
739                 if (!sta->eapol_sm)
740                         return;
741
742 #ifdef CONFIG_WPS
743                 if (!hapd->conf->ieee802_1x &&
744                     ((sta->flags & (WLAN_STA_WPS | WLAN_STA_MAYBE_WPS)) ==
745                      WLAN_STA_MAYBE_WPS)) {
746                         /*
747                          * Delay EAPOL frame transmission until a possible WPS
748                          * STA initiates the handshake with EAPOL-Start.
749                          */
750                         sta->eapol_sm->flags |= EAPOL_SM_WAIT_START;
751                 }
752 #endif /* CONFIG_WPS */
753
754                 sta->eapol_sm->eap_if->portEnabled = TRUE;
755         }
756
757         /* since we support version 1, we can ignore version field and proceed
758          * as specified in version 1 standard [IEEE Std 802.1X-2001, 7.5.5] */
759         /* TODO: actually, we are not version 1 anymore.. However, Version 2
760          * does not change frame contents, so should be ok to process frames
761          * more or less identically. Some changes might be needed for
762          * verification of fields. */
763
764         switch (hdr->type) {
765         case IEEE802_1X_TYPE_EAP_PACKET:
766                 handle_eap(hapd, sta, (u8 *) (hdr + 1), datalen);
767                 break;
768
769         case IEEE802_1X_TYPE_EAPOL_START:
770                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
771                                HOSTAPD_LEVEL_DEBUG, "received EAPOL-Start "
772                                "from STA");
773                 sta->eapol_sm->flags &= ~EAPOL_SM_WAIT_START;
774                 pmksa = wpa_auth_sta_get_pmksa(sta->wpa_sm);
775                 if (pmksa) {
776                         hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_WPA,
777                                        HOSTAPD_LEVEL_DEBUG, "cached PMKSA "
778                                        "available - ignore it since "
779                                        "STA sent EAPOL-Start");
780                         wpa_auth_sta_clear_pmksa(sta->wpa_sm, pmksa);
781                 }
782                 sta->eapol_sm->eapolStart = TRUE;
783                 sta->eapol_sm->dot1xAuthEapolStartFramesRx++;
784                 wpa_auth_sm_event(sta->wpa_sm, WPA_REAUTH_EAPOL);
785                 break;
786
787         case IEEE802_1X_TYPE_EAPOL_LOGOFF:
788                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
789                                HOSTAPD_LEVEL_DEBUG, "received EAPOL-Logoff "
790                                "from STA");
791                 sta->acct_terminate_cause =
792                         RADIUS_ACCT_TERMINATE_CAUSE_USER_REQUEST;
793                 accounting_sta_stop(hapd, sta);
794                 sta->eapol_sm->eapolLogoff = TRUE;
795                 sta->eapol_sm->dot1xAuthEapolLogoffFramesRx++;
796                 break;
797
798         case IEEE802_1X_TYPE_EAPOL_KEY:
799                 wpa_printf(MSG_DEBUG, "   EAPOL-Key");
800                 if (!(sta->flags & WLAN_STA_AUTHORIZED)) {
801                         wpa_printf(MSG_DEBUG, "   Dropped key data from "
802                                    "unauthorized Supplicant");
803                         break;
804                 }
805                 break;
806
807         case IEEE802_1X_TYPE_EAPOL_ENCAPSULATED_ASF_ALERT:
808                 wpa_printf(MSG_DEBUG, "   EAPOL-Encapsulated-ASF-Alert");
809                 /* TODO: implement support for this; show data */
810                 break;
811
812         default:
813                 wpa_printf(MSG_DEBUG, "   unknown IEEE 802.1X packet type");
814                 sta->eapol_sm->dot1xAuthInvalidEapolFramesRx++;
815                 break;
816         }
817
818         eapol_auth_step(sta->eapol_sm);
819 }
820
821
822 /**
823  * ieee802_1x_new_station - Start IEEE 802.1X authentication
824  * @hapd: hostapd BSS data
825  * @sta: The station
826  *
827  * This function is called to start IEEE 802.1X authentication when a new
828  * station completes IEEE 802.11 association.
829  */
830 void ieee802_1x_new_station(struct hostapd_data *hapd, struct sta_info *sta)
831 {
832         struct rsn_pmksa_cache_entry *pmksa;
833         int reassoc = 1;
834         int force_1x = 0;
835
836 #ifdef CONFIG_WPS
837         if (hapd->conf->wps_state && hapd->conf->wpa &&
838             (sta->flags & (WLAN_STA_WPS | WLAN_STA_MAYBE_WPS))) {
839                 /*
840                  * Need to enable IEEE 802.1X/EAPOL state machines for possible
841                  * WPS handshake even if IEEE 802.1X/EAPOL is not used for
842                  * authentication in this BSS.
843                  */
844                 force_1x = 1;
845         }
846 #endif /* CONFIG_WPS */
847
848         if ((!force_1x && !hapd->conf->ieee802_1x) ||
849             wpa_key_mgmt_wpa_psk(wpa_auth_sta_key_mgmt(sta->wpa_sm)))
850                 return;
851
852         if (sta->eapol_sm == NULL) {
853                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
854                                HOSTAPD_LEVEL_DEBUG, "start authentication");
855                 sta->eapol_sm = ieee802_1x_alloc_eapol_sm(hapd, sta);
856                 if (sta->eapol_sm == NULL) {
857                         hostapd_logger(hapd, sta->addr,
858                                        HOSTAPD_MODULE_IEEE8021X,
859                                        HOSTAPD_LEVEL_INFO,
860                                        "failed to allocate state machine");
861                         return;
862                 }
863                 reassoc = 0;
864         }
865
866 #ifdef CONFIG_WPS
867         sta->eapol_sm->flags &= ~EAPOL_SM_WAIT_START;
868         if (!hapd->conf->ieee802_1x && !(sta->flags & WLAN_STA_WPS)) {
869                 /*
870                  * Delay EAPOL frame transmission until a possible WPS
871                  * initiates the handshake with EAPOL-Start.
872                  */
873                 sta->eapol_sm->flags |= EAPOL_SM_WAIT_START;
874         }
875 #endif /* CONFIG_WPS */
876
877         sta->eapol_sm->eap_if->portEnabled = TRUE;
878
879         pmksa = wpa_auth_sta_get_pmksa(sta->wpa_sm);
880         if (pmksa) {
881                 int old_vlanid;
882
883                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
884                                HOSTAPD_LEVEL_DEBUG,
885                                "PMK from PMKSA cache - skip IEEE 802.1X/EAP");
886                 /* Setup EAPOL state machines to already authenticated state
887                  * because of existing PMKSA information in the cache. */
888                 sta->eapol_sm->keyRun = TRUE;
889                 sta->eapol_sm->eap_if->eapKeyAvailable = TRUE;
890                 sta->eapol_sm->auth_pae_state = AUTH_PAE_AUTHENTICATING;
891                 sta->eapol_sm->be_auth_state = BE_AUTH_SUCCESS;
892                 sta->eapol_sm->authSuccess = TRUE;
893                 if (sta->eapol_sm->eap)
894                         eap_sm_notify_cached(sta->eapol_sm->eap);
895                 old_vlanid = sta->vlan_id;
896                 pmksa_cache_to_eapol_data(pmksa, sta->eapol_sm);
897                 if (sta->ssid->dynamic_vlan == DYNAMIC_VLAN_DISABLED)
898                         sta->vlan_id = 0;
899                 ap_sta_bind_vlan(hapd, sta, old_vlanid);
900         } else {
901                 if (reassoc) {
902                         /*
903                          * Force EAPOL state machines to start
904                          * re-authentication without having to wait for the
905                          * Supplicant to send EAPOL-Start.
906                          */
907                         sta->eapol_sm->reAuthenticate = TRUE;
908                 }
909                 eapol_auth_step(sta->eapol_sm);
910         }
911 }
912
913
914 void ieee802_1x_free_station(struct sta_info *sta)
915 {
916         struct eapol_state_machine *sm = sta->eapol_sm;
917
918         if (sm == NULL)
919                 return;
920
921         sta->eapol_sm = NULL;
922
923 #ifndef CONFIG_NO_RADIUS
924         if (sm->last_recv_radius) {
925                 radius_msg_free(sm->last_recv_radius);
926                 os_free(sm->last_recv_radius);
927         }
928         radius_free_class(&sm->radius_class);
929 #endif /* CONFIG_NO_RADIUS */
930
931         os_free(sm->identity);
932         eapol_auth_free(sm);
933 }
934
935
936 #ifndef CONFIG_NO_RADIUS
937 static void ieee802_1x_decapsulate_radius(struct hostapd_data *hapd,
938                                           struct sta_info *sta)
939 {
940         u8 *eap;
941         size_t len;
942         struct eap_hdr *hdr;
943         int eap_type = -1;
944         char buf[64];
945         struct radius_msg *msg;
946         struct eapol_state_machine *sm = sta->eapol_sm;
947
948         if (sm == NULL || sm->last_recv_radius == NULL) {
949                 if (sm)
950                         sm->eap_if->aaaEapNoReq = TRUE;
951                 return;
952         }
953
954         msg = sm->last_recv_radius;
955
956         eap = radius_msg_get_eap(msg, &len);
957         if (eap == NULL) {
958                 /* RFC 3579, Chap. 2.6.3:
959                  * RADIUS server SHOULD NOT send Access-Reject/no EAP-Message
960                  * attribute */
961                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
962                                HOSTAPD_LEVEL_WARNING, "could not extract "
963                                "EAP-Message from RADIUS message");
964                 sm->eap_if->aaaEapNoReq = TRUE;
965                 return;
966         }
967
968         if (len < sizeof(*hdr)) {
969                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
970                                HOSTAPD_LEVEL_WARNING, "too short EAP packet "
971                                "received from authentication server");
972                 os_free(eap);
973                 sm->eap_if->aaaEapNoReq = TRUE;
974                 return;
975         }
976
977         if (len > sizeof(*hdr))
978                 eap_type = eap[sizeof(*hdr)];
979
980         hdr = (struct eap_hdr *) eap;
981         switch (hdr->code) {
982         case EAP_CODE_REQUEST:
983                 if (eap_type >= 0)
984                         sm->eap_type_authsrv = eap_type;
985                 os_snprintf(buf, sizeof(buf), "EAP-Request-%s (%d)",
986                             eap_type >= 0 ? eap_server_get_name(0, eap_type) :
987                             "??",
988                             eap_type);
989                 break;
990         case EAP_CODE_RESPONSE:
991                 os_snprintf(buf, sizeof(buf), "EAP Response-%s (%d)",
992                             eap_type >= 0 ? eap_server_get_name(0, eap_type) :
993                             "??",
994                             eap_type);
995                 break;
996         case EAP_CODE_SUCCESS:
997                 os_strlcpy(buf, "EAP Success", sizeof(buf));
998                 break;
999         case EAP_CODE_FAILURE:
1000                 os_strlcpy(buf, "EAP Failure", sizeof(buf));
1001                 break;
1002         default:
1003                 os_strlcpy(buf, "unknown EAP code", sizeof(buf));
1004                 break;
1005         }
1006         buf[sizeof(buf) - 1] = '\0';
1007         hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
1008                        HOSTAPD_LEVEL_DEBUG, "decapsulated EAP packet (code=%d "
1009                        "id=%d len=%d) from RADIUS server: %s",
1010                        hdr->code, hdr->identifier, be_to_host16(hdr->length),
1011                        buf);
1012         sm->eap_if->aaaEapReq = TRUE;
1013
1014         wpabuf_free(sm->eap_if->aaaEapReqData);
1015         sm->eap_if->aaaEapReqData = wpabuf_alloc_ext_data(eap, len);
1016 }
1017
1018
1019 static void ieee802_1x_get_keys(struct hostapd_data *hapd,
1020                                 struct sta_info *sta, struct radius_msg *msg,
1021                                 struct radius_msg *req,
1022                                 const u8 *shared_secret,
1023                                 size_t shared_secret_len)
1024 {
1025         struct radius_ms_mppe_keys *keys;
1026         struct eapol_state_machine *sm = sta->eapol_sm;
1027         if (sm == NULL)
1028                 return;
1029
1030         keys = radius_msg_get_ms_keys(msg, req, shared_secret,
1031                                       shared_secret_len);
1032
1033         if (keys && keys->send && keys->recv) {
1034                 size_t len = keys->send_len + keys->recv_len;
1035                 wpa_hexdump_key(MSG_DEBUG, "MS-MPPE-Send-Key",
1036                                 keys->send, keys->send_len);
1037                 wpa_hexdump_key(MSG_DEBUG, "MS-MPPE-Recv-Key",
1038                                 keys->recv, keys->recv_len);
1039
1040                 os_free(sm->eap_if->aaaEapKeyData);
1041                 sm->eap_if->aaaEapKeyData = os_malloc(len);
1042                 if (sm->eap_if->aaaEapKeyData) {
1043                         os_memcpy(sm->eap_if->aaaEapKeyData, keys->recv,
1044                                   keys->recv_len);
1045                         os_memcpy(sm->eap_if->aaaEapKeyData + keys->recv_len,
1046                                   keys->send, keys->send_len);
1047                         sm->eap_if->aaaEapKeyDataLen = len;
1048                         sm->eap_if->aaaEapKeyAvailable = TRUE;
1049                 }
1050         }
1051
1052         if (keys) {
1053                 os_free(keys->send);
1054                 os_free(keys->recv);
1055                 os_free(keys);
1056         }
1057 }
1058
1059
1060 static void ieee802_1x_store_radius_class(struct hostapd_data *hapd,
1061                                           struct sta_info *sta,
1062                                           struct radius_msg *msg)
1063 {
1064         u8 *class;
1065         size_t class_len;
1066         struct eapol_state_machine *sm = sta->eapol_sm;
1067         int count, i;
1068         struct radius_attr_data *nclass;
1069         size_t nclass_count;
1070
1071         if (!hapd->conf->radius->acct_server || hapd->radius == NULL ||
1072             sm == NULL)
1073                 return;
1074
1075         radius_free_class(&sm->radius_class);
1076         count = radius_msg_count_attr(msg, RADIUS_ATTR_CLASS, 1);
1077         if (count <= 0)
1078                 return;
1079
1080         nclass = os_zalloc(count * sizeof(struct radius_attr_data));
1081         if (nclass == NULL)
1082                 return;
1083
1084         nclass_count = 0;
1085
1086         class = NULL;
1087         for (i = 0; i < count; i++) {
1088                 do {
1089                         if (radius_msg_get_attr_ptr(msg, RADIUS_ATTR_CLASS,
1090                                                     &class, &class_len,
1091                                                     class) < 0) {
1092                                 i = count;
1093                                 break;
1094                         }
1095                 } while (class_len < 1);
1096
1097                 nclass[nclass_count].data = os_malloc(class_len);
1098                 if (nclass[nclass_count].data == NULL)
1099                         break;
1100
1101                 os_memcpy(nclass[nclass_count].data, class, class_len);
1102                 nclass[nclass_count].len = class_len;
1103                 nclass_count++;
1104         }
1105
1106         sm->radius_class.attr = nclass;
1107         sm->radius_class.count = nclass_count;
1108         wpa_printf(MSG_DEBUG, "IEEE 802.1X: Stored %lu RADIUS Class "
1109                    "attributes for " MACSTR,
1110                    (unsigned long) sm->radius_class.count,
1111                    MAC2STR(sta->addr));
1112 }
1113
1114
1115 /* Update sta->identity based on User-Name attribute in Access-Accept */
1116 static void ieee802_1x_update_sta_identity(struct hostapd_data *hapd,
1117                                            struct sta_info *sta,
1118                                            struct radius_msg *msg)
1119 {
1120         u8 *buf, *identity;
1121         size_t len;
1122         struct eapol_state_machine *sm = sta->eapol_sm;
1123
1124         if (sm == NULL)
1125                 return;
1126
1127         if (radius_msg_get_attr_ptr(msg, RADIUS_ATTR_USER_NAME, &buf, &len,
1128                                     NULL) < 0)
1129                 return;
1130
1131         identity = os_malloc(len + 1);
1132         if (identity == NULL)
1133                 return;
1134
1135         os_memcpy(identity, buf, len);
1136         identity[len] = '\0';
1137
1138         hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
1139                        HOSTAPD_LEVEL_DEBUG, "old identity '%s' updated with "
1140                        "User-Name from Access-Accept '%s'",
1141                        sm->identity ? (char *) sm->identity : "N/A",
1142                        (char *) identity);
1143
1144         os_free(sm->identity);
1145         sm->identity = identity;
1146         sm->identity_len = len;
1147 }
1148
1149
1150 struct sta_id_search {
1151         u8 identifier;
1152         struct eapol_state_machine *sm;
1153 };
1154
1155
1156 static int ieee802_1x_select_radius_identifier(struct hostapd_data *hapd,
1157                                                struct sta_info *sta,
1158                                                void *ctx)
1159 {
1160         struct sta_id_search *id_search = ctx;
1161         struct eapol_state_machine *sm = sta->eapol_sm;
1162
1163         if (sm && sm->radius_identifier >= 0 &&
1164             sm->radius_identifier == id_search->identifier) {
1165                 id_search->sm = sm;
1166                 return 1;
1167         }
1168         return 0;
1169 }
1170
1171
1172 static struct eapol_state_machine *
1173 ieee802_1x_search_radius_identifier(struct hostapd_data *hapd, u8 identifier)
1174 {
1175         struct sta_id_search id_search;
1176         id_search.identifier = identifier;
1177         id_search.sm = NULL;
1178         ap_for_each_sta(hapd, ieee802_1x_select_radius_identifier, &id_search);
1179         return id_search.sm;
1180 }
1181
1182
1183 /**
1184  * ieee802_1x_receive_auth - Process RADIUS frames from Authentication Server
1185  * @msg: RADIUS response message
1186  * @req: RADIUS request message
1187  * @shared_secret: RADIUS shared secret
1188  * @shared_secret_len: Length of shared_secret in octets
1189  * @data: Context data (struct hostapd_data *)
1190  * Returns: Processing status
1191  */
1192 static RadiusRxResult
1193 ieee802_1x_receive_auth(struct radius_msg *msg, struct radius_msg *req,
1194                         const u8 *shared_secret, size_t shared_secret_len,
1195                         void *data)
1196 {
1197         struct hostapd_data *hapd = data;
1198         struct sta_info *sta;
1199         u32 session_timeout = 0, termination_action, acct_interim_interval;
1200         int session_timeout_set, old_vlanid = 0;
1201         struct eapol_state_machine *sm;
1202         int override_eapReq = 0;
1203
1204         sm = ieee802_1x_search_radius_identifier(hapd, msg->hdr->identifier);
1205         if (sm == NULL) {
1206                 wpa_printf(MSG_DEBUG, "IEEE 802.1X: Could not find matching "
1207                            "station for this RADIUS message");
1208                 return RADIUS_RX_UNKNOWN;
1209         }
1210         sta = sm->sta;
1211
1212         /* RFC 2869, Ch. 5.13: valid Message-Authenticator attribute MUST be
1213          * present when packet contains an EAP-Message attribute */
1214         if (msg->hdr->code == RADIUS_CODE_ACCESS_REJECT &&
1215             radius_msg_get_attr(msg, RADIUS_ATTR_MESSAGE_AUTHENTICATOR, NULL,
1216                                 0) < 0 &&
1217             radius_msg_get_attr(msg, RADIUS_ATTR_EAP_MESSAGE, NULL, 0) < 0) {
1218                 wpa_printf(MSG_DEBUG, "Allowing RADIUS Access-Reject without "
1219                            "Message-Authenticator since it does not include "
1220                            "EAP-Message");
1221         } else if (radius_msg_verify(msg, shared_secret, shared_secret_len,
1222                                      req, 1)) {
1223                 printf("Incoming RADIUS packet did not have correct "
1224                        "Message-Authenticator - dropped\n");
1225                 return RADIUS_RX_INVALID_AUTHENTICATOR;
1226         }
1227
1228         if (msg->hdr->code != RADIUS_CODE_ACCESS_ACCEPT &&
1229             msg->hdr->code != RADIUS_CODE_ACCESS_REJECT &&
1230             msg->hdr->code != RADIUS_CODE_ACCESS_CHALLENGE) {
1231                 printf("Unknown RADIUS message code\n");
1232                 return RADIUS_RX_UNKNOWN;
1233         }
1234
1235         sm->radius_identifier = -1;
1236         wpa_printf(MSG_DEBUG, "RADIUS packet matching with station " MACSTR,
1237                    MAC2STR(sta->addr));
1238
1239         if (sm->last_recv_radius) {
1240                 radius_msg_free(sm->last_recv_radius);
1241                 os_free(sm->last_recv_radius);
1242         }
1243
1244         sm->last_recv_radius = msg;
1245
1246         session_timeout_set =
1247                 !radius_msg_get_attr_int32(msg, RADIUS_ATTR_SESSION_TIMEOUT,
1248                                            &session_timeout);
1249         if (radius_msg_get_attr_int32(msg, RADIUS_ATTR_TERMINATION_ACTION,
1250                                       &termination_action))
1251                 termination_action = RADIUS_TERMINATION_ACTION_DEFAULT;
1252
1253         if (hapd->conf->acct_interim_interval == 0 &&
1254             msg->hdr->code == RADIUS_CODE_ACCESS_ACCEPT &&
1255             radius_msg_get_attr_int32(msg, RADIUS_ATTR_ACCT_INTERIM_INTERVAL,
1256                                       &acct_interim_interval) == 0) {
1257                 if (acct_interim_interval < 60) {
1258                         hostapd_logger(hapd, sta->addr,
1259                                        HOSTAPD_MODULE_IEEE8021X,
1260                                        HOSTAPD_LEVEL_INFO,
1261                                        "ignored too small "
1262                                        "Acct-Interim-Interval %d",
1263                                        acct_interim_interval);
1264                 } else
1265                         sta->acct_interim_interval = acct_interim_interval;
1266         }
1267
1268
1269         switch (msg->hdr->code) {
1270         case RADIUS_CODE_ACCESS_ACCEPT:
1271                 if (sta->ssid->dynamic_vlan == DYNAMIC_VLAN_DISABLED)
1272                         sta->vlan_id = 0;
1273 #ifndef CONFIG_NO_VLAN
1274                 else {
1275                         old_vlanid = sta->vlan_id;
1276                         sta->vlan_id = radius_msg_get_vlanid(msg);
1277                 }
1278                 if (sta->vlan_id > 0 &&
1279                     hostapd_get_vlan_id_ifname(hapd->conf->vlan,
1280                                                sta->vlan_id)) {
1281                         hostapd_logger(hapd, sta->addr,
1282                                        HOSTAPD_MODULE_RADIUS,
1283                                        HOSTAPD_LEVEL_INFO,
1284                                        "VLAN ID %d", sta->vlan_id);
1285                 } else if (sta->ssid->dynamic_vlan == DYNAMIC_VLAN_REQUIRED) {
1286                         sta->eapol_sm->authFail = TRUE;
1287                         hostapd_logger(hapd, sta->addr,
1288                                        HOSTAPD_MODULE_IEEE8021X,
1289                                        HOSTAPD_LEVEL_INFO, "authentication "
1290                                        "server did not include required VLAN "
1291                                        "ID in Access-Accept");
1292                         break;
1293                 }
1294 #endif /* CONFIG_NO_VLAN */
1295
1296                 ap_sta_bind_vlan(hapd, sta, old_vlanid);
1297
1298                 /* RFC 3580, Ch. 3.17 */
1299                 if (session_timeout_set && termination_action ==
1300                     RADIUS_TERMINATION_ACTION_RADIUS_REQUEST) {
1301                         sm->reAuthPeriod = session_timeout;
1302                 } else if (session_timeout_set)
1303                         ap_sta_session_timeout(hapd, sta, session_timeout);
1304
1305                 sm->eap_if->aaaSuccess = TRUE;
1306                 override_eapReq = 1;
1307                 ieee802_1x_get_keys(hapd, sta, msg, req, shared_secret,
1308                                     shared_secret_len);
1309                 ieee802_1x_store_radius_class(hapd, sta, msg);
1310                 ieee802_1x_update_sta_identity(hapd, sta, msg);
1311                 if (sm->eap_if->eapKeyAvailable &&
1312                     wpa_auth_pmksa_add(sta->wpa_sm, sm->eapol_key_crypt,
1313                                        session_timeout_set ?
1314                                        (int) session_timeout : -1, sm) == 0) {
1315                         hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_WPA,
1316                                        HOSTAPD_LEVEL_DEBUG,
1317                                        "Added PMKSA cache entry");
1318                 }
1319                 break;
1320         case RADIUS_CODE_ACCESS_REJECT:
1321                 sm->eap_if->aaaFail = TRUE;
1322                 override_eapReq = 1;
1323                 break;
1324         case RADIUS_CODE_ACCESS_CHALLENGE:
1325                 sm->eap_if->aaaEapReq = TRUE;
1326                 if (session_timeout_set) {
1327                         /* RFC 2869, Ch. 2.3.2; RFC 3580, Ch. 3.17 */
1328                         sm->eap_if->aaaMethodTimeout = session_timeout;
1329                         hostapd_logger(hapd, sm->addr,
1330                                        HOSTAPD_MODULE_IEEE8021X,
1331                                        HOSTAPD_LEVEL_DEBUG,
1332                                        "using EAP timeout of %d seconds (from "
1333                                        "RADIUS)",
1334                                        sm->eap_if->aaaMethodTimeout);
1335                 } else {
1336                         /*
1337                          * Use dynamic retransmission behavior per EAP
1338                          * specification.
1339                          */
1340                         sm->eap_if->aaaMethodTimeout = 0;
1341                 }
1342                 break;
1343         }
1344
1345         ieee802_1x_decapsulate_radius(hapd, sta);
1346         if (override_eapReq)
1347                 sm->eap_if->aaaEapReq = FALSE;
1348
1349         eapol_auth_step(sm);
1350
1351         return RADIUS_RX_QUEUED;
1352 }
1353 #endif /* CONFIG_NO_RADIUS */
1354
1355
1356 void ieee802_1x_abort_auth(struct hostapd_data *hapd, struct sta_info *sta)
1357 {
1358         struct eapol_state_machine *sm = sta->eapol_sm;
1359         if (sm == NULL)
1360                 return;
1361
1362         hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
1363                        HOSTAPD_LEVEL_DEBUG, "aborting authentication");
1364
1365 #ifndef CONFIG_NO_RADIUS
1366         if (sm->last_recv_radius) {
1367                 radius_msg_free(sm->last_recv_radius);
1368                 os_free(sm->last_recv_radius);
1369                 sm->last_recv_radius = NULL;
1370         }
1371 #endif /* CONFIG_NO_RADIUS */
1372
1373         if (sm->eap_if->eapTimeout) {
1374                 /*
1375                  * Disconnect the STA since it did not reply to the last EAP
1376                  * request and we cannot continue EAP processing (EAP-Failure
1377                  * could only be sent if the EAP peer actually replied).
1378                  */
1379                 sm->eap_if->portEnabled = FALSE;
1380                 hostapd_sta_deauth(hapd, sta->addr,
1381                                    WLAN_REASON_PREV_AUTH_NOT_VALID);
1382                 sta->flags &= ~(WLAN_STA_AUTH | WLAN_STA_ASSOC |
1383                                 WLAN_STA_AUTHORIZED);
1384                 eloop_cancel_timeout(ap_handle_timer, hapd, sta);
1385                 eloop_register_timeout(0, 0, ap_handle_timer, hapd, sta);
1386                 sta->timeout_next = STA_REMOVE;
1387         }
1388 }
1389
1390
1391 #ifdef HOSTAPD_DUMP_STATE
1392 static void fprint_char(FILE *f, char c)
1393 {
1394         if (c >= 32 && c < 127)
1395                 fprintf(f, "%c", c);
1396         else
1397                 fprintf(f, "<%02x>", c);
1398 }
1399
1400
1401 void ieee802_1x_dump_state(FILE *f, const char *prefix, struct sta_info *sta)
1402 {
1403         struct eapol_state_machine *sm = sta->eapol_sm;
1404         if (sm == NULL)
1405                 return;
1406
1407         fprintf(f, "%sIEEE 802.1X:\n", prefix);
1408
1409         if (sm->identity) {
1410                 size_t i;
1411                 fprintf(f, "%sidentity=", prefix);
1412                 for (i = 0; i < sm->identity_len; i++)
1413                         fprint_char(f, sm->identity[i]);
1414                 fprintf(f, "\n");
1415         }
1416
1417         fprintf(f, "%slast EAP type: Authentication Server: %d (%s) "
1418                 "Supplicant: %d (%s)\n", prefix,
1419                 sm->eap_type_authsrv,
1420                 eap_server_get_name(0, sm->eap_type_authsrv),
1421                 sm->eap_type_supp, eap_server_get_name(0, sm->eap_type_supp));
1422
1423         fprintf(f, "%scached_packets=%s\n", prefix,
1424                 sm->last_recv_radius ? "[RX RADIUS]" : "");
1425
1426         eapol_auth_dump_state(f, prefix, sm);
1427 }
1428 #endif /* HOSTAPD_DUMP_STATE */
1429
1430
1431 static int ieee802_1x_rekey_broadcast(struct hostapd_data *hapd)
1432 {
1433         struct eapol_authenticator *eapol = hapd->eapol_auth;
1434
1435         if (hapd->conf->default_wep_key_len < 1)
1436                 return 0;
1437
1438         os_free(eapol->default_wep_key);
1439         eapol->default_wep_key = os_malloc(hapd->conf->default_wep_key_len);
1440         if (eapol->default_wep_key == NULL ||
1441             os_get_random(eapol->default_wep_key,
1442                           hapd->conf->default_wep_key_len)) {
1443                 printf("Could not generate random WEP key.\n");
1444                 os_free(eapol->default_wep_key);
1445                 eapol->default_wep_key = NULL;
1446                 return -1;
1447         }
1448
1449         wpa_hexdump_key(MSG_DEBUG, "IEEE 802.1X: New default WEP key",
1450                         eapol->default_wep_key,
1451                         hapd->conf->default_wep_key_len);
1452
1453         return 0;
1454 }
1455
1456
1457 static int ieee802_1x_sta_key_available(struct hostapd_data *hapd,
1458                                         struct sta_info *sta, void *ctx)
1459 {
1460         if (sta->eapol_sm) {
1461                 sta->eapol_sm->eap_if->eapKeyAvailable = TRUE;
1462                 eapol_auth_step(sta->eapol_sm);
1463         }
1464         return 0;
1465 }
1466
1467
1468 static void ieee802_1x_rekey(void *eloop_ctx, void *timeout_ctx)
1469 {
1470         struct hostapd_data *hapd = eloop_ctx;
1471         struct eapol_authenticator *eapol = hapd->eapol_auth;
1472
1473         if (eapol->default_wep_key_idx >= 3)
1474                 eapol->default_wep_key_idx =
1475                         hapd->conf->individual_wep_key_len > 0 ? 1 : 0;
1476         else
1477                 eapol->default_wep_key_idx++;
1478
1479         wpa_printf(MSG_DEBUG, "IEEE 802.1X: New default WEP key index %d",
1480                    eapol->default_wep_key_idx);
1481                       
1482         if (ieee802_1x_rekey_broadcast(hapd)) {
1483                 hostapd_logger(hapd, NULL, HOSTAPD_MODULE_IEEE8021X,
1484                                HOSTAPD_LEVEL_WARNING, "failed to generate a "
1485                                "new broadcast key");
1486                 os_free(eapol->default_wep_key);
1487                 eapol->default_wep_key = NULL;
1488                 return;
1489         }
1490
1491         /* TODO: Could setup key for RX here, but change default TX keyid only
1492          * after new broadcast key has been sent to all stations. */
1493         if (hostapd_set_key(hapd->conf->iface, hapd, WPA_ALG_WEP, NULL,
1494                             eapol->default_wep_key_idx, 1, NULL, 0,
1495                             eapol->default_wep_key,
1496                             hapd->conf->default_wep_key_len)) {
1497                 hostapd_logger(hapd, NULL, HOSTAPD_MODULE_IEEE8021X,
1498                                HOSTAPD_LEVEL_WARNING, "failed to configure a "
1499                                "new broadcast key");
1500                 os_free(eapol->default_wep_key);
1501                 eapol->default_wep_key = NULL;
1502                 return;
1503         }
1504
1505         ap_for_each_sta(hapd, ieee802_1x_sta_key_available, NULL);
1506
1507         if (hapd->conf->wep_rekeying_period > 0) {
1508                 eloop_register_timeout(hapd->conf->wep_rekeying_period, 0,
1509                                        ieee802_1x_rekey, hapd, NULL);
1510         }
1511 }
1512
1513
1514 static void ieee802_1x_eapol_send(void *ctx, void *sta_ctx, u8 type,
1515                                   const u8 *data, size_t datalen)
1516 {
1517         ieee802_1x_send(ctx, sta_ctx, type, data, datalen);
1518 }
1519
1520
1521 static void ieee802_1x_aaa_send(void *ctx, void *sta_ctx,
1522                                 const u8 *data, size_t datalen)
1523 {
1524 #ifndef CONFIG_NO_RADIUS
1525         struct hostapd_data *hapd = ctx;
1526         struct sta_info *sta = sta_ctx;
1527
1528         ieee802_1x_encapsulate_radius(hapd, sta, data, datalen);
1529 #endif /* CONFIG_NO_RADIUS */
1530 }
1531
1532
1533 static void _ieee802_1x_finished(void *ctx, void *sta_ctx, int success,
1534                                  int preauth)
1535 {
1536         struct hostapd_data *hapd = ctx;
1537         struct sta_info *sta = sta_ctx;
1538         if (preauth)
1539                 rsn_preauth_finished(hapd, sta, success);
1540         else
1541                 ieee802_1x_finished(hapd, sta, success);
1542 }
1543
1544
1545 static int ieee802_1x_get_eap_user(void *ctx, const u8 *identity,
1546                                    size_t identity_len, int phase2,
1547                                    struct eap_user *user)
1548 {
1549         struct hostapd_data *hapd = ctx;
1550         const struct hostapd_eap_user *eap_user;
1551         int i, count;
1552
1553         eap_user = hostapd_get_eap_user(hapd->conf, identity,
1554                                         identity_len, phase2);
1555         if (eap_user == NULL)
1556                 return -1;
1557
1558         os_memset(user, 0, sizeof(*user));
1559         user->phase2 = phase2;
1560         count = EAP_USER_MAX_METHODS;
1561         if (count > EAP_MAX_METHODS)
1562                 count = EAP_MAX_METHODS;
1563         for (i = 0; i < count; i++) {
1564                 user->methods[i].vendor = eap_user->methods[i].vendor;
1565                 user->methods[i].method = eap_user->methods[i].method;
1566         }
1567
1568         if (eap_user->password) {
1569                 user->password = os_malloc(eap_user->password_len);
1570                 if (user->password == NULL)
1571                         return -1;
1572                 os_memcpy(user->password, eap_user->password,
1573                           eap_user->password_len);
1574                 user->password_len = eap_user->password_len;
1575         }
1576         user->force_version = eap_user->force_version;
1577         user->ttls_auth = eap_user->ttls_auth;
1578
1579         return 0;
1580 }
1581
1582
1583 static int ieee802_1x_sta_entry_alive(void *ctx, const u8 *addr)
1584 {
1585         struct hostapd_data *hapd = ctx;
1586         struct sta_info *sta;
1587         sta = ap_get_sta(hapd, addr);
1588         if (sta == NULL || sta->eapol_sm == NULL)
1589                 return 0;
1590         return 1;
1591 }
1592
1593
1594 static void ieee802_1x_logger(void *ctx, const u8 *addr,
1595                               eapol_logger_level level, const char *txt)
1596 {
1597 #ifndef CONFIG_NO_HOSTAPD_LOGGER
1598         struct hostapd_data *hapd = ctx;
1599         int hlevel;
1600
1601         switch (level) {
1602         case EAPOL_LOGGER_WARNING:
1603                 hlevel = HOSTAPD_LEVEL_WARNING;
1604                 break;
1605         case EAPOL_LOGGER_INFO:
1606                 hlevel = HOSTAPD_LEVEL_INFO;
1607                 break;
1608         case EAPOL_LOGGER_DEBUG:
1609         default:
1610                 hlevel = HOSTAPD_LEVEL_DEBUG;
1611                 break;
1612         }
1613
1614         hostapd_logger(hapd, addr, HOSTAPD_MODULE_IEEE8021X, hlevel, "%s",
1615                        txt);
1616 #endif /* CONFIG_NO_HOSTAPD_LOGGER */
1617 }
1618
1619
1620 static void ieee802_1x_set_port_authorized(void *ctx, void *sta_ctx,
1621                                            int authorized)
1622 {
1623         struct hostapd_data *hapd = ctx;
1624         struct sta_info *sta = sta_ctx;
1625         ieee802_1x_set_sta_authorized(hapd, sta, authorized);
1626 }
1627
1628
1629 static void _ieee802_1x_abort_auth(void *ctx, void *sta_ctx)
1630 {
1631         struct hostapd_data *hapd = ctx;
1632         struct sta_info *sta = sta_ctx;
1633         ieee802_1x_abort_auth(hapd, sta);
1634 }
1635
1636
1637 static void _ieee802_1x_tx_key(void *ctx, void *sta_ctx)
1638 {
1639         struct hostapd_data *hapd = ctx;
1640         struct sta_info *sta = sta_ctx;
1641         ieee802_1x_tx_key(hapd, sta);
1642 }
1643
1644
1645 static void ieee802_1x_eapol_event(void *ctx, void *sta_ctx,
1646                                    enum eapol_event type)
1647 {
1648         /* struct hostapd_data *hapd = ctx; */
1649         struct sta_info *sta = sta_ctx;
1650         switch (type) {
1651         case EAPOL_AUTH_SM_CHANGE:
1652                 wpa_auth_sm_notify(sta->wpa_sm);
1653                 break;
1654         case EAPOL_AUTH_REAUTHENTICATE:
1655                 wpa_auth_sm_event(sta->wpa_sm, WPA_REAUTH_EAPOL);
1656                 break;
1657         }
1658 }
1659
1660
1661 int ieee802_1x_init(struct hostapd_data *hapd)
1662 {
1663         int i;
1664         struct eapol_auth_config conf;
1665         struct eapol_auth_cb cb;
1666
1667         os_memset(&conf, 0, sizeof(conf));
1668         conf.hapd = hapd;
1669         conf.eap_reauth_period = hapd->conf->eap_reauth_period;
1670         conf.wpa = hapd->conf->wpa;
1671         conf.individual_wep_key_len = hapd->conf->individual_wep_key_len;
1672         conf.eap_server = hapd->conf->eap_server;
1673         conf.ssl_ctx = hapd->ssl_ctx;
1674         conf.eap_sim_db_priv = hapd->eap_sim_db_priv;
1675         conf.eap_req_id_text = hapd->conf->eap_req_id_text;
1676         conf.eap_req_id_text_len = hapd->conf->eap_req_id_text_len;
1677         conf.pac_opaque_encr_key = hapd->conf->pac_opaque_encr_key;
1678         conf.eap_fast_a_id = hapd->conf->eap_fast_a_id;
1679         conf.eap_fast_a_id_len = hapd->conf->eap_fast_a_id_len;
1680         conf.eap_fast_a_id_info = hapd->conf->eap_fast_a_id_info;
1681         conf.eap_fast_prov = hapd->conf->eap_fast_prov;
1682         conf.pac_key_lifetime = hapd->conf->pac_key_lifetime;
1683         conf.pac_key_refresh_time = hapd->conf->pac_key_refresh_time;
1684         conf.eap_sim_aka_result_ind = hapd->conf->eap_sim_aka_result_ind;
1685         conf.tnc = hapd->conf->tnc;
1686         conf.wps = hapd->wps;
1687
1688         os_memset(&cb, 0, sizeof(cb));
1689         cb.eapol_send = ieee802_1x_eapol_send;
1690         cb.aaa_send = ieee802_1x_aaa_send;
1691         cb.finished = _ieee802_1x_finished;
1692         cb.get_eap_user = ieee802_1x_get_eap_user;
1693         cb.sta_entry_alive = ieee802_1x_sta_entry_alive;
1694         cb.logger = ieee802_1x_logger;
1695         cb.set_port_authorized = ieee802_1x_set_port_authorized;
1696         cb.abort_auth = _ieee802_1x_abort_auth;
1697         cb.tx_key = _ieee802_1x_tx_key;
1698         cb.eapol_event = ieee802_1x_eapol_event;
1699
1700         hapd->eapol_auth = eapol_auth_init(&conf, &cb);
1701         if (hapd->eapol_auth == NULL)
1702                 return -1;
1703
1704         if ((hapd->conf->ieee802_1x || hapd->conf->wpa) &&
1705             hostapd_set_ieee8021x(hapd->conf->iface, hapd, 1))
1706                 return -1;
1707
1708 #ifndef CONFIG_NO_RADIUS
1709         if (radius_client_register(hapd->radius, RADIUS_AUTH,
1710                                    ieee802_1x_receive_auth, hapd))
1711                 return -1;
1712 #endif /* CONFIG_NO_RADIUS */
1713
1714         if (hapd->conf->default_wep_key_len) {
1715                 hostapd_set_privacy(hapd, 1);
1716
1717                 for (i = 0; i < 4; i++)
1718                         hostapd_set_key(hapd->conf->iface, hapd, WPA_ALG_NONE,
1719                                         NULL, i, 0, NULL, 0, NULL, 0);
1720
1721                 ieee802_1x_rekey(hapd, NULL);
1722
1723                 if (hapd->eapol_auth->default_wep_key == NULL)
1724                         return -1;
1725         }
1726
1727         return 0;
1728 }
1729
1730
1731 void ieee802_1x_deinit(struct hostapd_data *hapd)
1732 {
1733         eloop_cancel_timeout(ieee802_1x_rekey, hapd, NULL);
1734
1735         if (hapd->driver != NULL &&
1736             (hapd->conf->ieee802_1x || hapd->conf->wpa))
1737                 hostapd_set_ieee8021x(hapd->conf->iface, hapd, 0);
1738
1739         eapol_auth_deinit(hapd->eapol_auth);
1740         hapd->eapol_auth = NULL;
1741 }
1742
1743
1744 int ieee802_1x_reconfig(struct hostapd_data *hapd, 
1745                         struct hostapd_config *oldconf,
1746                         struct hostapd_bss_config *oldbss)
1747 {
1748         ieee802_1x_deinit(hapd);
1749         return ieee802_1x_init(hapd);
1750 }
1751
1752
1753 int ieee802_1x_tx_status(struct hostapd_data *hapd, struct sta_info *sta,
1754                          const u8 *buf, size_t len, int ack)
1755 {
1756         struct ieee80211_hdr *hdr;
1757         struct ieee802_1x_hdr *xhdr;
1758         struct ieee802_1x_eapol_key *key;
1759         u8 *pos;
1760         const unsigned char rfc1042_hdr[ETH_ALEN] =
1761                 { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
1762
1763         if (sta == NULL)
1764                 return -1;
1765         if (len < sizeof(*hdr) + sizeof(rfc1042_hdr) + 2 + sizeof(*xhdr))
1766                 return 0;
1767
1768         hdr = (struct ieee80211_hdr *) buf;
1769         pos = (u8 *) (hdr + 1);
1770         if (os_memcmp(pos, rfc1042_hdr, sizeof(rfc1042_hdr)) != 0)
1771                 return 0;
1772         pos += sizeof(rfc1042_hdr);
1773         if (WPA_GET_BE16(pos) != ETH_P_PAE)
1774                 return 0;
1775         pos += 2;
1776
1777         xhdr = (struct ieee802_1x_hdr *) pos;
1778         pos += sizeof(*xhdr);
1779
1780         wpa_printf(MSG_DEBUG, "IEEE 802.1X: " MACSTR " TX status - version=%d "
1781                    "type=%d length=%d - ack=%d",
1782                    MAC2STR(sta->addr), xhdr->version, xhdr->type,
1783                    be_to_host16(xhdr->length), ack);
1784
1785         /* EAPOL EAP-Packet packets are eventually re-sent by either Supplicant
1786          * or Authenticator state machines, but EAPOL-Key packets are not
1787          * retransmitted in case of failure. Try to re-sent failed EAPOL-Key
1788          * packets couple of times because otherwise STA keys become
1789          * unsynchronized with AP. */
1790         if (xhdr->type == IEEE802_1X_TYPE_EAPOL_KEY && !ack &&
1791             pos + sizeof(*key) <= buf + len) {
1792                 key = (struct ieee802_1x_eapol_key *) pos;
1793                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_IEEE8021X,
1794                                HOSTAPD_LEVEL_DEBUG, "did not Ack EAPOL-Key "
1795                                "frame (%scast index=%d)",
1796                                key->key_index & BIT(7) ? "uni" : "broad",
1797                                key->key_index & ~BIT(7));
1798                 /* TODO: re-send EAPOL-Key couple of times (with short delay
1799                  * between them?). If all attempt fail, report error and
1800                  * deauthenticate STA so that it will get new keys when
1801                  * authenticating again (e.g., after returning in range).
1802                  * Separate limit/transmit state needed both for unicast and
1803                  * broadcast keys(?) */
1804         }
1805         /* TODO: could move unicast key configuration from ieee802_1x_tx_key()
1806          * to here and change the key only if the EAPOL-Key packet was Acked.
1807          */
1808
1809         return 1;
1810 }
1811
1812
1813 u8 * ieee802_1x_get_identity(struct eapol_state_machine *sm, size_t *len)
1814 {
1815         if (sm == NULL || sm->identity == NULL)
1816                 return NULL;
1817
1818         *len = sm->identity_len;
1819         return sm->identity;
1820 }
1821
1822
1823 u8 * ieee802_1x_get_radius_class(struct eapol_state_machine *sm, size_t *len,
1824                                  int idx)
1825 {
1826         if (sm == NULL || sm->radius_class.attr == NULL ||
1827             idx >= (int) sm->radius_class.count)
1828                 return NULL;
1829
1830         *len = sm->radius_class.attr[idx].len;
1831         return sm->radius_class.attr[idx].data;
1832 }
1833
1834
1835 const u8 * ieee802_1x_get_key(struct eapol_state_machine *sm, size_t *len)
1836 {
1837         if (sm == NULL)
1838                 return NULL;
1839
1840         *len = sm->eap_if->eapKeyDataLen;
1841         return sm->eap_if->eapKeyData;
1842 }
1843
1844
1845 void ieee802_1x_notify_port_enabled(struct eapol_state_machine *sm,
1846                                     int enabled)
1847 {
1848         if (sm == NULL)
1849                 return;
1850         sm->eap_if->portEnabled = enabled ? TRUE : FALSE;
1851         eapol_auth_step(sm);
1852 }
1853
1854
1855 void ieee802_1x_notify_port_valid(struct eapol_state_machine *sm,
1856                                   int valid)
1857 {
1858         if (sm == NULL)
1859                 return;
1860         sm->portValid = valid ? TRUE : FALSE;
1861         eapol_auth_step(sm);
1862 }
1863
1864
1865 void ieee802_1x_notify_pre_auth(struct eapol_state_machine *sm, int pre_auth)
1866 {
1867         if (sm == NULL)
1868                 return;
1869         if (pre_auth)
1870                 sm->flags |= EAPOL_SM_PREAUTH;
1871         else
1872                 sm->flags &= ~EAPOL_SM_PREAUTH;
1873 }
1874
1875
1876 static const char * bool_txt(Boolean bool)
1877 {
1878         return bool ? "TRUE" : "FALSE";
1879 }
1880
1881
1882 int ieee802_1x_get_mib(struct hostapd_data *hapd, char *buf, size_t buflen)
1883 {
1884         /* TODO */
1885         return 0;
1886 }
1887
1888
1889 int ieee802_1x_get_mib_sta(struct hostapd_data *hapd, struct sta_info *sta,
1890                            char *buf, size_t buflen)
1891 {
1892         int len = 0, ret;
1893         struct eapol_state_machine *sm = sta->eapol_sm;
1894
1895         if (sm == NULL)
1896                 return 0;
1897
1898         ret = os_snprintf(buf + len, buflen - len,
1899                           "dot1xPaePortNumber=%d\n"
1900                           "dot1xPaePortProtocolVersion=%d\n"
1901                           "dot1xPaePortCapabilities=1\n"
1902                           "dot1xPaePortInitialize=%d\n"
1903                           "dot1xPaePortReauthenticate=FALSE\n",
1904                           sta->aid,
1905                           EAPOL_VERSION,
1906                           sm->initialize);
1907         if (ret < 0 || (size_t) ret >= buflen - len)
1908                 return len;
1909         len += ret;
1910
1911         /* dot1xAuthConfigTable */
1912         ret = os_snprintf(buf + len, buflen - len,
1913                           "dot1xAuthPaeState=%d\n"
1914                           "dot1xAuthBackendAuthState=%d\n"
1915                           "dot1xAuthAdminControlledDirections=%d\n"
1916                           "dot1xAuthOperControlledDirections=%d\n"
1917                           "dot1xAuthAuthControlledPortStatus=%d\n"
1918                           "dot1xAuthAuthControlledPortControl=%d\n"
1919                           "dot1xAuthQuietPeriod=%u\n"
1920                           "dot1xAuthServerTimeout=%u\n"
1921                           "dot1xAuthReAuthPeriod=%u\n"
1922                           "dot1xAuthReAuthEnabled=%s\n"
1923                           "dot1xAuthKeyTxEnabled=%s\n",
1924                           sm->auth_pae_state + 1,
1925                           sm->be_auth_state + 1,
1926                           sm->adminControlledDirections,
1927                           sm->operControlledDirections,
1928                           sm->authPortStatus,
1929                           sm->portControl,
1930                           sm->quietPeriod,
1931                           sm->serverTimeout,
1932                           sm->reAuthPeriod,
1933                           bool_txt(sm->reAuthEnabled),
1934                           bool_txt(sm->keyTxEnabled));
1935         if (ret < 0 || (size_t) ret >= buflen - len)
1936                 return len;
1937         len += ret;
1938
1939         /* dot1xAuthStatsTable */
1940         ret = os_snprintf(buf + len, buflen - len,
1941                           "dot1xAuthEapolFramesRx=%u\n"
1942                           "dot1xAuthEapolFramesTx=%u\n"
1943                           "dot1xAuthEapolStartFramesRx=%u\n"
1944                           "dot1xAuthEapolLogoffFramesRx=%u\n"
1945                           "dot1xAuthEapolRespIdFramesRx=%u\n"
1946                           "dot1xAuthEapolRespFramesRx=%u\n"
1947                           "dot1xAuthEapolReqIdFramesTx=%u\n"
1948                           "dot1xAuthEapolReqFramesTx=%u\n"
1949                           "dot1xAuthInvalidEapolFramesRx=%u\n"
1950                           "dot1xAuthEapLengthErrorFramesRx=%u\n"
1951                           "dot1xAuthLastEapolFrameVersion=%u\n"
1952                           "dot1xAuthLastEapolFrameSource=" MACSTR "\n",
1953                           sm->dot1xAuthEapolFramesRx,
1954                           sm->dot1xAuthEapolFramesTx,
1955                           sm->dot1xAuthEapolStartFramesRx,
1956                           sm->dot1xAuthEapolLogoffFramesRx,
1957                           sm->dot1xAuthEapolRespIdFramesRx,
1958                           sm->dot1xAuthEapolRespFramesRx,
1959                           sm->dot1xAuthEapolReqIdFramesTx,
1960                           sm->dot1xAuthEapolReqFramesTx,
1961                           sm->dot1xAuthInvalidEapolFramesRx,
1962                           sm->dot1xAuthEapLengthErrorFramesRx,
1963                           sm->dot1xAuthLastEapolFrameVersion,
1964                           MAC2STR(sm->addr));
1965         if (ret < 0 || (size_t) ret >= buflen - len)
1966                 return len;
1967         len += ret;
1968
1969         /* dot1xAuthDiagTable */
1970         ret = os_snprintf(buf + len, buflen - len,
1971                           "dot1xAuthEntersConnecting=%u\n"
1972                           "dot1xAuthEapLogoffsWhileConnecting=%u\n"
1973                           "dot1xAuthEntersAuthenticating=%u\n"
1974                           "dot1xAuthAuthSuccessesWhileAuthenticating=%u\n"
1975                           "dot1xAuthAuthTimeoutsWhileAuthenticating=%u\n"
1976                           "dot1xAuthAuthFailWhileAuthenticating=%u\n"
1977                           "dot1xAuthAuthEapStartsWhileAuthenticating=%u\n"
1978                           "dot1xAuthAuthEapLogoffWhileAuthenticating=%u\n"
1979                           "dot1xAuthAuthReauthsWhileAuthenticated=%u\n"
1980                           "dot1xAuthAuthEapStartsWhileAuthenticated=%u\n"
1981                           "dot1xAuthAuthEapLogoffWhileAuthenticated=%u\n"
1982                           "dot1xAuthBackendResponses=%u\n"
1983                           "dot1xAuthBackendAccessChallenges=%u\n"
1984                           "dot1xAuthBackendOtherRequestsToSupplicant=%u\n"
1985                           "dot1xAuthBackendAuthSuccesses=%u\n"
1986                           "dot1xAuthBackendAuthFails=%u\n",
1987                           sm->authEntersConnecting,
1988                           sm->authEapLogoffsWhileConnecting,
1989                           sm->authEntersAuthenticating,
1990                           sm->authAuthSuccessesWhileAuthenticating,
1991                           sm->authAuthTimeoutsWhileAuthenticating,
1992                           sm->authAuthFailWhileAuthenticating,
1993                           sm->authAuthEapStartsWhileAuthenticating,
1994                           sm->authAuthEapLogoffWhileAuthenticating,
1995                           sm->authAuthReauthsWhileAuthenticated,
1996                           sm->authAuthEapStartsWhileAuthenticated,
1997                           sm->authAuthEapLogoffWhileAuthenticated,
1998                           sm->backendResponses,
1999                           sm->backendAccessChallenges,
2000                           sm->backendOtherRequestsToSupplicant,
2001                           sm->backendAuthSuccesses,
2002                           sm->backendAuthFails);
2003         if (ret < 0 || (size_t) ret >= buflen - len)
2004                 return len;
2005         len += ret;
2006
2007         /* dot1xAuthSessionStatsTable */
2008         ret = os_snprintf(buf + len, buflen - len,
2009                           /* TODO: dot1xAuthSessionOctetsRx */
2010                           /* TODO: dot1xAuthSessionOctetsTx */
2011                           /* TODO: dot1xAuthSessionFramesRx */
2012                           /* TODO: dot1xAuthSessionFramesTx */
2013                           "dot1xAuthSessionId=%08X-%08X\n"
2014                           "dot1xAuthSessionAuthenticMethod=%d\n"
2015                           "dot1xAuthSessionTime=%u\n"
2016                           "dot1xAuthSessionTerminateCause=999\n"
2017                           "dot1xAuthSessionUserName=%s\n",
2018                           sta->acct_session_id_hi, sta->acct_session_id_lo,
2019                           (wpa_key_mgmt_wpa_ieee8021x(
2020                                    wpa_auth_sta_key_mgmt(sta->wpa_sm))) ?
2021                           1 : 2,
2022                           (unsigned int) (time(NULL) -
2023                                           sta->acct_session_start),
2024                           sm->identity);
2025         if (ret < 0 || (size_t) ret >= buflen - len)
2026                 return len;
2027         len += ret;
2028
2029         return len;
2030 }
2031
2032
2033 static void ieee802_1x_finished(struct hostapd_data *hapd,
2034                                 struct sta_info *sta, int success)
2035 {
2036         const u8 *key;
2037         size_t len;
2038         /* TODO: get PMKLifetime from WPA parameters */
2039         static const int dot11RSNAConfigPMKLifetime = 43200;
2040
2041         key = ieee802_1x_get_key(sta->eapol_sm, &len);
2042         if (success && key && len >= PMK_LEN &&
2043             wpa_auth_pmksa_add(sta->wpa_sm, key, dot11RSNAConfigPMKLifetime,
2044                                sta->eapol_sm) == 0) {
2045                 hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_WPA,
2046                                HOSTAPD_LEVEL_DEBUG,
2047                                "Added PMKSA cache entry (IEEE 802.1X)");
2048         }
2049 }