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