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