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