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