OSDN Git Service

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