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