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