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