]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/hostapd/wpa.c
This commit was generated by cvs2svn to compensate for changes in r171827,
[FreeBSD/FreeBSD.git] / contrib / hostapd / wpa.c
1 /*
2  * hostapd - IEEE 802.11i-2004 / WPA Authenticator
3  * Copyright (c) 2004-2007, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  *
14  * $FreeBSD$
15  */
16
17 #include "includes.h"
18
19 #ifndef CONFIG_NATIVE_WINDOWS
20
21 #include "hostapd.h"
22 #include "eapol_sm.h"
23 #include "wpa.h"
24 #include "wme.h"
25 #include "sha1.h"
26 #include "md5.h"
27 #include "rc4.h"
28 #include "aes_wrap.h"
29 #include "crypto.h"
30 #include "eloop.h"
31 #include "ieee802_11.h"
32 #include "pmksa_cache.h"
33 #include "state_machine.h"
34
35 #define STATE_MACHINE_DATA struct wpa_state_machine
36 #define STATE_MACHINE_DEBUG_PREFIX "WPA"
37 #define STATE_MACHINE_ADDR sm->addr
38
39
40 #define RSN_NUM_REPLAY_COUNTERS_1 0
41 #define RSN_NUM_REPLAY_COUNTERS_2 1
42 #define RSN_NUM_REPLAY_COUNTERS_4 2
43 #define RSN_NUM_REPLAY_COUNTERS_16 3
44
45
46 struct wpa_group;
47
48 struct wpa_stsl_negotiation {
49         struct wpa_stsl_negotiation *next;
50         u8 initiator[ETH_ALEN];
51         u8 peer[ETH_ALEN];
52 };
53
54
55 struct wpa_state_machine {
56         struct wpa_authenticator *wpa_auth;
57         struct wpa_group *group;
58
59         u8 addr[ETH_ALEN];
60
61         enum {
62                 WPA_PTK_INITIALIZE, WPA_PTK_DISCONNECT, WPA_PTK_DISCONNECTED,
63                 WPA_PTK_AUTHENTICATION, WPA_PTK_AUTHENTICATION2,
64                 WPA_PTK_INITPMK, WPA_PTK_INITPSK, WPA_PTK_PTKSTART,
65                 WPA_PTK_PTKCALCNEGOTIATING, WPA_PTK_PTKCALCNEGOTIATING2,
66                 WPA_PTK_PTKINITNEGOTIATING, WPA_PTK_PTKINITDONE
67         } wpa_ptk_state;
68
69         enum {
70                 WPA_PTK_GROUP_IDLE = 0,
71                 WPA_PTK_GROUP_REKEYNEGOTIATING,
72                 WPA_PTK_GROUP_REKEYESTABLISHED,
73                 WPA_PTK_GROUP_KEYERROR
74         } wpa_ptk_group_state;
75
76         Boolean Init;
77         Boolean DeauthenticationRequest;
78         Boolean AuthenticationRequest;
79         Boolean ReAuthenticationRequest;
80         Boolean Disconnect;
81         int TimeoutCtr;
82         int GTimeoutCtr;
83         Boolean TimeoutEvt;
84         Boolean EAPOLKeyReceived;
85         Boolean EAPOLKeyPairwise;
86         Boolean EAPOLKeyRequest;
87         Boolean MICVerified;
88         Boolean GUpdateStationKeys;
89         u8 ANonce[WPA_NONCE_LEN];
90         u8 SNonce[WPA_NONCE_LEN];
91         u8 PMK[WPA_PMK_LEN];
92         struct wpa_ptk PTK;
93         Boolean PTK_valid;
94         Boolean pairwise_set;
95         int keycount;
96         Boolean Pair;
97         u8 key_replay_counter[WPA_REPLAY_COUNTER_LEN];
98         Boolean key_replay_counter_valid;
99         Boolean PInitAKeys; /* WPA only, not in IEEE 802.11i */
100         Boolean PTKRequest; /* not in IEEE 802.11i state machine */
101         Boolean has_GTK;
102
103         u8 *last_rx_eapol_key; /* starting from IEEE 802.1X header */
104         size_t last_rx_eapol_key_len;
105
106         unsigned int changed:1;
107         unsigned int in_step_loop:1;
108         unsigned int pending_deinit:1;
109         unsigned int started:1;
110         unsigned int sta_counted:1;
111         unsigned int mgmt_frame_prot:1;
112
113         u8 req_replay_counter[WPA_REPLAY_COUNTER_LEN];
114         int req_replay_counter_used;
115
116         u8 *wpa_ie;
117         size_t wpa_ie_len;
118
119         enum {
120                 WPA_VERSION_NO_WPA = 0 /* WPA not used */,
121                 WPA_VERSION_WPA = 1 /* WPA / IEEE 802.11i/D3.0 */,
122                 WPA_VERSION_WPA2 = 2 /* WPA2 / IEEE 802.11i */
123         } wpa;
124         int pairwise; /* Pairwise cipher suite, WPA_CIPHER_* */
125         int wpa_key_mgmt; /* the selected WPA_KEY_MGMT_* */
126         struct rsn_pmksa_cache_entry *pmksa;
127
128         u32 dot11RSNAStatsTKIPLocalMICFailures;
129         u32 dot11RSNAStatsTKIPRemoteMICFailures;
130 };
131
132
133 /* per group key state machine data */
134 struct wpa_group {
135         struct wpa_group *next;
136         int vlan_id;
137
138         Boolean GInit;
139         int GNoStations;
140         int GKeyDoneStations;
141         Boolean GTKReKey;
142         int GTK_len;
143         int GN, GM;
144         Boolean GTKAuthenticator;
145         u8 Counter[WPA_NONCE_LEN];
146
147         enum {
148                 WPA_GROUP_GTK_INIT = 0,
149                 WPA_GROUP_SETKEYS, WPA_GROUP_SETKEYSDONE
150         } wpa_group_state;
151
152         u8 GMK[WPA_GMK_LEN];
153         u8 GTK[2][WPA_GTK_MAX_LEN];
154         u8 GNonce[WPA_NONCE_LEN];
155         Boolean changed;
156 #ifdef CONFIG_IEEE80211W
157         u8 DGTK[WPA_DGTK_LEN];
158         u8 IGTK[2][WPA_IGTK_LEN];
159 #endif /* CONFIG_IEEE80211W */
160 };
161
162
163 /* per authenticator data */
164 struct wpa_authenticator {
165         struct wpa_group *group;
166
167         unsigned int dot11RSNAStatsTKIPRemoteMICFailures;
168         u8 dot11RSNAAuthenticationSuiteSelected[4];
169         u8 dot11RSNAPairwiseCipherSelected[4];
170         u8 dot11RSNAGroupCipherSelected[4];
171         u8 dot11RSNAPMKIDUsed[PMKID_LEN];
172         u8 dot11RSNAAuthenticationSuiteRequested[4]; /* FIX: update */
173         u8 dot11RSNAPairwiseCipherRequested[4]; /* FIX: update */
174         u8 dot11RSNAGroupCipherRequested[4]; /* FIX: update */
175         unsigned int dot11RSNATKIPCounterMeasuresInvoked;
176         unsigned int dot11RSNA4WayHandshakeFailures;
177
178         struct wpa_stsl_negotiation *stsl_negotiations;
179
180         struct wpa_auth_config conf;
181         struct wpa_auth_callbacks cb;
182
183         u8 *wpa_ie;
184         size_t wpa_ie_len;
185
186         u8 addr[ETH_ALEN];
187
188         struct rsn_pmksa_cache *pmksa;
189 };
190
191
192 static void wpa_send_eapol_timeout(void *eloop_ctx, void *timeout_ctx);
193 static void wpa_sm_step(struct wpa_state_machine *sm);
194 static int wpa_verify_key_mic(struct wpa_ptk *PTK, u8 *data, size_t data_len);
195 static void wpa_sm_call_step(void *eloop_ctx, void *timeout_ctx);
196 static void wpa_group_sm_step(struct wpa_authenticator *wpa_auth,
197                               struct wpa_group *group);
198 static int wpa_stsl_remove(struct wpa_authenticator *wpa_auth,
199                            struct wpa_stsl_negotiation *neg);
200 static void __wpa_send_eapol(struct wpa_authenticator *wpa_auth,
201                              struct wpa_state_machine *sm, int key_info,
202                              const u8 *key_rsc, const u8 *nonce,
203                              const u8 *kde, size_t kde_len,
204                              int keyidx, int encr, int force_version);
205
206 /* Default timeouts are 100 ms, but this seems to be a bit too fast for most
207  * WPA Supplicants, so use a bit longer timeout. */
208 static const u32 dot11RSNAConfigGroupUpdateTimeOut = 1000; /* ms */
209 static const u32 dot11RSNAConfigGroupUpdateCount = 3;
210 static const u32 dot11RSNAConfigPairwiseUpdateTimeOut = 1000; /* ms */
211 static const u32 dot11RSNAConfigPairwiseUpdateCount = 3;
212
213 /* TODO: make these configurable */
214 static const int dot11RSNAConfigPMKLifetime = 43200;
215 static const int dot11RSNAConfigPMKReauthThreshold = 70;
216 static const int dot11RSNAConfigSATimeout = 60;
217
218
219 static const int WPA_SELECTOR_LEN = 4;
220 static const u8 WPA_OUI_TYPE[] = { 0x00, 0x50, 0xf2, 1 };
221 static const u16 WPA_VERSION = 1;
222 static const u8 WPA_AUTH_KEY_MGMT_UNSPEC_802_1X[] = { 0x00, 0x50, 0xf2, 1 };
223 static const u8 WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X[] = { 0x00, 0x50, 0xf2, 2 };
224 static const u8 WPA_CIPHER_SUITE_NONE[] = { 0x00, 0x50, 0xf2, 0 };
225 static const u8 WPA_CIPHER_SUITE_WEP40[] = { 0x00, 0x50, 0xf2, 1 };
226 static const u8 WPA_CIPHER_SUITE_TKIP[] = { 0x00, 0x50, 0xf2, 2 };
227 static const u8 WPA_CIPHER_SUITE_WRAP[] = { 0x00, 0x50, 0xf2, 3 };
228 static const u8 WPA_CIPHER_SUITE_CCMP[] = { 0x00, 0x50, 0xf2, 4 };
229 static const u8 WPA_CIPHER_SUITE_WEP104[] = { 0x00, 0x50, 0xf2, 5 };
230 #ifdef CONFIG_IEEE80211W
231 static const u8 RSN_CIPHER_SUITE_AES_128_CMAC[] = { 0x00, 0x0f, 0xac, 6 };
232 #endif /* CONFIG_IEEE80211W */
233
234 static const int RSN_SELECTOR_LEN = 4;
235 static const u16 RSN_VERSION = 1;
236 static const u8 RSN_AUTH_KEY_MGMT_UNSPEC_802_1X[] = { 0x00, 0x0f, 0xac, 1 };
237 static const u8 RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X[] = { 0x00, 0x0f, 0xac, 2 };
238 static const u8 RSN_CIPHER_SUITE_NONE[] = { 0x00, 0x0f, 0xac, 0 };
239 static const u8 RSN_CIPHER_SUITE_WEP40[] = { 0x00, 0x0f, 0xac, 1 };
240 static const u8 RSN_CIPHER_SUITE_TKIP[] = { 0x00, 0x0f, 0xac, 2 };
241 static const u8 RSN_CIPHER_SUITE_WRAP[] = { 0x00, 0x0f, 0xac, 3 };
242 static const u8 RSN_CIPHER_SUITE_CCMP[] = { 0x00, 0x0f, 0xac, 4 };
243 static const u8 RSN_CIPHER_SUITE_WEP104[] = { 0x00, 0x0f, 0xac, 5 };
244
245 /* EAPOL-Key Key Data Encapsulation
246  * GroupKey and PeerKey require encryption, otherwise, encryption is optional.
247  */
248 static const u8 RSN_KEY_DATA_GROUPKEY[] = { 0x00, 0x0f, 0xac, 1 };
249 #if 0
250 static const u8 RSN_KEY_DATA_STAKEY[] = { 0x00, 0x0f, 0xac, 2 };
251 #endif
252 static const u8 RSN_KEY_DATA_MAC_ADDR[] = { 0x00, 0x0f, 0xac, 3 };
253 static const u8 RSN_KEY_DATA_PMKID[] = { 0x00, 0x0f, 0xac, 4 };
254 #ifdef CONFIG_PEERKEY
255 static const u8 RSN_KEY_DATA_SMK[] = { 0x00, 0x0f, 0xac, 5 };
256 static const u8 RSN_KEY_DATA_NONCE[] = { 0x00, 0x0f, 0xac, 6 };
257 static const u8 RSN_KEY_DATA_LIFETIME[] = { 0x00, 0x0f, 0xac, 7 };
258 static const u8 RSN_KEY_DATA_ERROR[] = { 0x00, 0x0f, 0xac, 8 };
259 #endif /* CONFIG_PEERKEY */
260 #ifdef CONFIG_IEEE80211W
261 /* FIX: IEEE 802.11w/D1.0 is using subtypes 5 and 6 for these, but they were
262  * already taken by 802.11ma (PeerKey). Need to update the values here once
263  * IEEE 802.11w fixes these. */
264 static const u8 RSN_KEY_DATA_DHV[] = { 0x00, 0x0f, 0xac, 9 };
265 static const u8 RSN_KEY_DATA_IGTK[] = { 0x00, 0x0f, 0xac, 10 };
266 #endif /* CONFIG_IEEE80211W */
267
268 #ifdef CONFIG_PEERKEY
269 enum {
270         STK_MUI_4WAY_STA_AP = 1,
271         STK_MUI_4WAY_STAT_STA = 2,
272         STK_MUI_GTK = 3,
273         STK_MUI_SMK = 4
274 };
275
276 enum {
277         STK_ERR_STA_NR = 1,
278         STK_ERR_STA_NRSN = 2,
279         STK_ERR_CPHR_NS = 3,
280         STK_ERR_NO_STSL = 4
281 };
282 #endif /* CONFIG_PEERKEY */
283
284 #define GENERIC_INFO_ELEM 0xdd
285 #define RSN_INFO_ELEM 0x30
286
287 #ifdef _MSC_VER
288 #pragma pack(push, 1)
289 #endif /* _MSC_VER */
290
291 /* WPA IE version 1
292  * 00-50-f2:1 (OUI:OUI type)
293  * 0x01 0x00 (version; little endian)
294  * (all following fields are optional:)
295  * Group Suite Selector (4 octets) (default: TKIP)
296  * Pairwise Suite Count (2 octets, little endian) (default: 1)
297  * Pairwise Suite List (4 * n octets) (default: TKIP)
298  * Authenticated Key Management Suite Count (2 octets, little endian)
299  *    (default: 1)
300  * Authenticated Key Management Suite List (4 * n octets)
301  *    (default: unspec 802.1X)
302  * WPA Capabilities (2 octets, little endian) (default: 0)
303  */
304
305 struct wpa_ie_hdr {
306         u8 elem_id;
307         u8 len;
308         u8 oui[3];
309         u8 oui_type;
310         u16 version;
311 } STRUCT_PACKED;
312
313
314 /* RSN IE version 1
315  * 0x01 0x00 (version; little endian)
316  * (all following fields are optional:)
317  * Group Suite Selector (4 octets) (default: CCMP)
318  * Pairwise Suite Count (2 octets, little endian) (default: 1)
319  * Pairwise Suite List (4 * n octets) (default: CCMP)
320  * Authenticated Key Management Suite Count (2 octets, little endian)
321  *    (default: 1)
322  * Authenticated Key Management Suite List (4 * n octets)
323  *    (default: unspec 802.1X)
324  * RSN Capabilities (2 octets, little endian) (default: 0)
325  * PMKID Count (2 octets) (default: 0)
326  * PMKID List (16 * n octets)
327  * Management Group Cipher Suite (4 octets) (default: AES-128-CMAC)
328  */
329
330 struct rsn_ie_hdr {
331         u8 elem_id; /* WLAN_EID_RSN */
332         u8 len;
333         u16 version;
334 } STRUCT_PACKED;
335
336
337 struct rsn_error_kde {
338         u16 mui;
339         u16 error_type;
340 } STRUCT_PACKED;
341
342
343 #ifdef CONFIG_IEEE80211W
344 struct wpa_dhv_kde {
345         u8 dhv[WPA_DHV_LEN];
346 } STRUCT_PACKED;
347
348 struct wpa_igtk_kde {
349         u8 keyid[2];
350         u8 pn[6];
351         u8 igtk[WPA_IGTK_LEN];
352 } STRUCT_PACKED;
353 #endif /* CONFIG_IEEE80211W */
354
355 #ifdef _MSC_VER
356 #pragma pack(pop)
357 #endif /* _MSC_VER */
358
359
360 static inline void wpa_auth_mic_failure_report(
361         struct wpa_authenticator *wpa_auth, const u8 *addr)
362 {
363         if (wpa_auth->cb.mic_failure_report)
364                 wpa_auth->cb.mic_failure_report(wpa_auth->cb.ctx, addr);
365 }
366
367
368 static inline void wpa_auth_set_eapol(struct wpa_authenticator *wpa_auth,
369                                       const u8 *addr, wpa_eapol_variable var,
370                                       int value)
371 {
372         if (wpa_auth->cb.set_eapol)
373                 wpa_auth->cb.set_eapol(wpa_auth->cb.ctx, addr, var, value);
374 }
375
376
377 static inline int wpa_auth_get_eapol(struct wpa_authenticator *wpa_auth,
378                                      const u8 *addr, wpa_eapol_variable var)
379 {
380         if (wpa_auth->cb.get_eapol == NULL)
381                 return -1;
382         return wpa_auth->cb.get_eapol(wpa_auth->cb.ctx, addr, var);
383 }
384
385
386 static inline const u8 * wpa_auth_get_psk(struct wpa_authenticator *wpa_auth,
387                                           const u8 *addr, const u8 *prev_psk)
388 {
389         if (wpa_auth->cb.get_psk == NULL)
390                 return NULL;
391         return wpa_auth->cb.get_psk(wpa_auth->cb.ctx, addr, prev_psk);
392 }
393
394
395 static inline int wpa_auth_get_pmk(struct wpa_authenticator *wpa_auth,
396                                    const u8 *addr, u8 *pmk, size_t *len)
397 {
398         if (wpa_auth->cb.get_pmk == NULL)
399                 return -1;
400         return wpa_auth->cb.get_pmk(wpa_auth->cb.ctx, addr, pmk, len);
401 }
402
403
404 static inline int wpa_auth_set_key(struct wpa_authenticator *wpa_auth,
405                                    int vlan_id,
406                                    const char *alg, const u8 *addr, int idx,
407                                    u8 *key, size_t key_len)
408 {
409         if (wpa_auth->cb.set_key == NULL)
410                 return -1;
411         return wpa_auth->cb.set_key(wpa_auth->cb.ctx, vlan_id, alg, addr, idx,
412                                     key, key_len);
413 }
414
415
416 static inline int wpa_auth_get_seqnum(struct wpa_authenticator *wpa_auth,
417                                       const u8 *addr, int idx, u8 *seq)
418 {
419         if (wpa_auth->cb.get_seqnum == NULL)
420                 return -1;
421         return wpa_auth->cb.get_seqnum(wpa_auth->cb.ctx, addr, idx, seq);
422 }
423
424
425 static inline int wpa_auth_get_seqnum_igtk(struct wpa_authenticator *wpa_auth,
426                                            const u8 *addr, int idx, u8 *seq)
427 {
428         if (wpa_auth->cb.get_seqnum_igtk == NULL)
429                 return -1;
430         return wpa_auth->cb.get_seqnum_igtk(wpa_auth->cb.ctx, addr, idx, seq);
431 }
432
433
434 static inline int
435 wpa_auth_send_eapol(struct wpa_authenticator *wpa_auth, const u8 *addr,
436                     const u8 *data, size_t data_len, int encrypt)
437 {
438         if (wpa_auth->cb.send_eapol == NULL)
439                 return -1;
440         return wpa_auth->cb.send_eapol(wpa_auth->cb.ctx, addr, data, data_len,
441                                        encrypt);
442 }
443
444
445 static inline int wpa_auth_for_each_sta(struct wpa_authenticator *wpa_auth,
446                                         int (*cb)(struct wpa_state_machine *sm,
447                                                   void *ctx),
448                                         void *cb_ctx)
449 {
450         if (wpa_auth->cb.for_each_sta == NULL)
451                 return 0;
452         return wpa_auth->cb.for_each_sta(wpa_auth->cb.ctx, cb, cb_ctx);
453 }
454
455
456 static void wpa_auth_logger(struct wpa_authenticator *wpa_auth, const u8 *addr,
457                             logger_level level, const char *txt)
458 {
459         if (wpa_auth->cb.logger == NULL)
460                 return;
461         wpa_auth->cb.logger(wpa_auth->cb.ctx, addr, level, txt);
462 }
463
464
465 static void wpa_auth_vlogger(struct wpa_authenticator *wpa_auth,
466                              const u8 *addr, logger_level level,
467                              const char *fmt, ...)
468 {
469         char *format;
470         int maxlen;
471         va_list ap;
472
473         if (wpa_auth->cb.logger == NULL)
474                 return;
475
476         maxlen = strlen(fmt) + 100;
477         format = malloc(maxlen);
478         if (!format)
479                 return;
480
481         va_start(ap, fmt);
482         vsnprintf(format, maxlen, fmt, ap);
483         va_end(ap);
484
485         wpa_auth_logger(wpa_auth, addr, level, format);
486
487         free(format);
488 }
489
490
491 static int wpa_write_wpa_ie(struct wpa_auth_config *conf, u8 *buf, size_t len)
492 {
493         struct wpa_ie_hdr *hdr;
494         int num_suites;
495         u8 *pos, *count;
496
497         hdr = (struct wpa_ie_hdr *) buf;
498         hdr->elem_id = WLAN_EID_GENERIC;
499         memcpy(&hdr->oui, WPA_OUI_TYPE, WPA_SELECTOR_LEN);
500         hdr->version = host_to_le16(WPA_VERSION);
501         pos = (u8 *) (hdr + 1);
502
503         if (conf->wpa_group == WPA_CIPHER_CCMP) {
504                 memcpy(pos, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN);
505         } else if (conf->wpa_group == WPA_CIPHER_TKIP) {
506                 memcpy(pos, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN);
507         } else if (conf->wpa_group == WPA_CIPHER_WEP104) {
508                 memcpy(pos, WPA_CIPHER_SUITE_WEP104, WPA_SELECTOR_LEN);
509         } else if (conf->wpa_group == WPA_CIPHER_WEP40) {
510                 memcpy(pos, WPA_CIPHER_SUITE_WEP40, WPA_SELECTOR_LEN);
511         } else {
512                 wpa_printf(MSG_DEBUG, "Invalid group cipher (%d).",
513                            conf->wpa_group);
514                 return -1;
515         }
516         pos += WPA_SELECTOR_LEN;
517
518         num_suites = 0;
519         count = pos;
520         pos += 2;
521
522         if (conf->wpa_pairwise & WPA_CIPHER_CCMP) {
523                 memcpy(pos, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN);
524                 pos += WPA_SELECTOR_LEN;
525                 num_suites++;
526         }
527         if (conf->wpa_pairwise & WPA_CIPHER_TKIP) {
528                 memcpy(pos, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN);
529                 pos += WPA_SELECTOR_LEN;
530                 num_suites++;
531         }
532         if (conf->wpa_pairwise & WPA_CIPHER_NONE) {
533                 memcpy(pos, WPA_CIPHER_SUITE_NONE, WPA_SELECTOR_LEN);
534                 pos += WPA_SELECTOR_LEN;
535                 num_suites++;
536         }
537
538         if (num_suites == 0) {
539                 wpa_printf(MSG_DEBUG, "Invalid pairwise cipher (%d).",
540                            conf->wpa_pairwise);
541                 return -1;
542         }
543         *count++ = num_suites & 0xff;
544         *count = (num_suites >> 8) & 0xff;
545
546         num_suites = 0;
547         count = pos;
548         pos += 2;
549
550         if (conf->wpa_key_mgmt & WPA_KEY_MGMT_IEEE8021X) {
551                 memcpy(pos, WPA_AUTH_KEY_MGMT_UNSPEC_802_1X, WPA_SELECTOR_LEN);
552                 pos += WPA_SELECTOR_LEN;
553                 num_suites++;
554         }
555         if (conf->wpa_key_mgmt & WPA_KEY_MGMT_PSK) {
556                 memcpy(pos, WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X,
557                        WPA_SELECTOR_LEN);
558                 pos += WPA_SELECTOR_LEN;
559                 num_suites++;
560         }
561
562         if (num_suites == 0) {
563                 wpa_printf(MSG_DEBUG, "Invalid key management type (%d).",
564                            conf->wpa_key_mgmt);
565                 return -1;
566         }
567         *count++ = num_suites & 0xff;
568         *count = (num_suites >> 8) & 0xff;
569
570         /* WPA Capabilities; use defaults, so no need to include it */
571
572         hdr->len = (pos - buf) - 2;
573
574         return pos - buf;
575 }
576
577
578 static int wpa_write_rsn_ie(struct wpa_auth_config *conf, u8 *buf, size_t len)
579 {
580         struct rsn_ie_hdr *hdr;
581         int num_suites;
582         u8 *pos, *count;
583         u16 capab;
584
585         hdr = (struct rsn_ie_hdr *) buf;
586         hdr->elem_id = WLAN_EID_RSN;
587         pos = (u8 *) &hdr->version;
588         *pos++ = RSN_VERSION & 0xff;
589         *pos++ = RSN_VERSION >> 8;
590         pos = (u8 *) (hdr + 1);
591
592         if (conf->wpa_group == WPA_CIPHER_CCMP) {
593                 memcpy(pos, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN);
594         } else if (conf->wpa_group == WPA_CIPHER_TKIP) {
595                 memcpy(pos, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN);
596         } else if (conf->wpa_group == WPA_CIPHER_WEP104) {
597                 memcpy(pos, RSN_CIPHER_SUITE_WEP104, RSN_SELECTOR_LEN);
598         } else if (conf->wpa_group == WPA_CIPHER_WEP40) {
599                 memcpy(pos, RSN_CIPHER_SUITE_WEP40, RSN_SELECTOR_LEN);
600         } else {
601                 wpa_printf(MSG_DEBUG, "Invalid group cipher (%d).",
602                            conf->wpa_group);
603                 return -1;
604         }
605         pos += RSN_SELECTOR_LEN;
606
607         num_suites = 0;
608         count = pos;
609         pos += 2;
610
611         if (conf->wpa_pairwise & WPA_CIPHER_CCMP) {
612                 memcpy(pos, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN);
613                 pos += RSN_SELECTOR_LEN;
614                 num_suites++;
615         }
616         if (conf->wpa_pairwise & WPA_CIPHER_TKIP) {
617                 memcpy(pos, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN);
618                 pos += RSN_SELECTOR_LEN;
619                 num_suites++;
620         }
621         if (conf->wpa_pairwise & WPA_CIPHER_NONE) {
622                 memcpy(pos, RSN_CIPHER_SUITE_NONE, RSN_SELECTOR_LEN);
623                 pos += RSN_SELECTOR_LEN;
624                 num_suites++;
625         }
626
627         if (num_suites == 0) {
628                 wpa_printf(MSG_DEBUG, "Invalid pairwise cipher (%d).",
629                            conf->wpa_pairwise);
630                 return -1;
631         }
632         *count++ = num_suites & 0xff;
633         *count = (num_suites >> 8) & 0xff;
634
635         num_suites = 0;
636         count = pos;
637         pos += 2;
638
639         if (conf->wpa_key_mgmt & WPA_KEY_MGMT_IEEE8021X) {
640                 memcpy(pos, RSN_AUTH_KEY_MGMT_UNSPEC_802_1X, RSN_SELECTOR_LEN);
641                 pos += RSN_SELECTOR_LEN;
642                 num_suites++;
643         }
644         if (conf->wpa_key_mgmt & WPA_KEY_MGMT_PSK) {
645                 memcpy(pos, RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X,
646                        RSN_SELECTOR_LEN);
647                 pos += RSN_SELECTOR_LEN;
648                 num_suites++;
649         }
650
651         if (num_suites == 0) {
652                 wpa_printf(MSG_DEBUG, "Invalid key management type (%d).",
653                            conf->wpa_key_mgmt);
654                 return -1;
655         }
656         *count++ = num_suites & 0xff;
657         *count = (num_suites >> 8) & 0xff;
658
659         /* RSN Capabilities */
660         capab = 0;
661         if (conf->rsn_preauth)
662                 capab |= WPA_CAPABILITY_PREAUTH;
663         if (conf->peerkey)
664                 capab |= WPA_CAPABILITY_PEERKEY_ENABLED;
665         if (conf->wme_enabled) {
666                 /* 4 PTKSA replay counters when using WME */
667                 capab |= (RSN_NUM_REPLAY_COUNTERS_16 << 2);
668         }
669 #ifdef CONFIG_IEEE80211W
670         if (conf->ieee80211w != WPA_NO_IEEE80211W)
671                 capab |= WPA_CAPABILITY_MGMT_FRAME_PROTECTION;
672 #endif /* CONFIG_IEEE80211W */
673         *pos++ = capab & 0xff;
674         *pos++ = capab >> 8;
675
676 #ifdef CONFIG_IEEE80211W
677         if (conf->ieee80211w != WPA_NO_IEEE80211W) {
678                 if (pos + 2 + 4 > buf + len)
679                         return -1;
680                 /* PMKID Count */
681                 WPA_PUT_LE16(pos, 0);
682                 pos += 2;
683
684                 /* Management Group Cipher Suite */
685                 memcpy(pos, RSN_CIPHER_SUITE_AES_128_CMAC, RSN_SELECTOR_LEN);
686                 pos += RSN_SELECTOR_LEN;
687         }
688 #endif /* CONFIG_IEEE80211W */
689
690         hdr->len = (pos - buf) - 2;
691
692         return pos - buf;
693 }
694
695
696 static int wpa_gen_wpa_ie(struct wpa_authenticator *wpa_auth)
697 {
698         u8 *pos, buf[100];
699         int res;
700
701         pos = buf;
702
703         if (wpa_auth->conf.wpa & HOSTAPD_WPA_VERSION_WPA2) {
704                 res = wpa_write_rsn_ie(&wpa_auth->conf,
705                                        pos, buf + sizeof(buf) - pos);
706                 if (res < 0)
707                         return res;
708                 pos += res;
709         }
710         if (wpa_auth->conf.wpa & HOSTAPD_WPA_VERSION_WPA) {
711                 res = wpa_write_wpa_ie(&wpa_auth->conf,
712                                        pos, buf + sizeof(buf) - pos);
713                 if (res < 0)
714                         return res;
715                 pos += res;
716         }
717
718         free(wpa_auth->wpa_ie);
719         wpa_auth->wpa_ie = malloc(pos - buf);
720         if (wpa_auth->wpa_ie == NULL)
721                 return -1;
722         memcpy(wpa_auth->wpa_ie, buf, pos - buf);
723         wpa_auth->wpa_ie_len = pos - buf;
724
725         return 0;
726 }
727
728
729 static void wpa_sta_disconnect(struct wpa_authenticator *wpa_auth,
730                                const u8 *addr)
731 {
732         if (wpa_auth->cb.disconnect == NULL)
733                 return;
734         wpa_auth->cb.disconnect(wpa_auth->cb.ctx, addr,
735                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
736 }
737
738
739 static void wpa_rekey_gmk(void *eloop_ctx, void *timeout_ctx)
740 {
741         struct wpa_authenticator *wpa_auth = eloop_ctx;
742
743         if (hostapd_get_rand(wpa_auth->group->GMK, WPA_GMK_LEN)) {
744                 wpa_printf(MSG_ERROR, "Failed to get random data for WPA "
745                            "initialization.");
746         } else {
747                 wpa_auth_logger(wpa_auth, NULL, LOGGER_DEBUG, "GMK rekeyd");
748         }
749
750         if (wpa_auth->conf.wpa_gmk_rekey) {
751                 eloop_register_timeout(wpa_auth->conf.wpa_gmk_rekey, 0,
752                                        wpa_rekey_gmk, wpa_auth, NULL);
753         }
754 }
755
756
757 static void wpa_rekey_gtk(void *eloop_ctx, void *timeout_ctx)
758 {
759         struct wpa_authenticator *wpa_auth = eloop_ctx;
760         struct wpa_group *group;
761
762         wpa_auth_logger(wpa_auth, NULL, LOGGER_DEBUG, "rekeying GTK");
763         for (group = wpa_auth->group; group; group = group->next) {
764                 group->GTKReKey = TRUE;
765                 do {
766                         group->changed = FALSE;
767                         wpa_group_sm_step(wpa_auth, group);
768                 } while (group->changed);
769         }
770
771         if (wpa_auth->conf.wpa_group_rekey) {
772                 eloop_register_timeout(wpa_auth->conf.wpa_group_rekey,
773                                        0, wpa_rekey_gtk, wpa_auth, NULL);
774         }
775 }
776
777
778 static int wpa_auth_pmksa_clear_cb(struct wpa_state_machine *sm, void *ctx)
779 {
780         if (sm->pmksa == ctx)
781                 sm->pmksa = NULL;
782         return 0;
783 }
784
785
786 static void wpa_auth_pmksa_free_cb(struct rsn_pmksa_cache_entry *entry,
787                                    void *ctx)
788 {
789         struct wpa_authenticator *wpa_auth = ctx;
790         wpa_auth_for_each_sta(wpa_auth, wpa_auth_pmksa_clear_cb, entry);
791 }
792
793
794 static struct wpa_group * wpa_group_init(struct wpa_authenticator *wpa_auth,
795                                          int vlan_id)
796 {
797         struct wpa_group *group;
798         u8 buf[ETH_ALEN + 8 + sizeof(group)];
799         u8 rkey[32];
800
801         group = wpa_zalloc(sizeof(struct wpa_group));
802         if (group == NULL)
803                 return NULL;
804
805         group->GTKAuthenticator = TRUE;
806         group->vlan_id = vlan_id;
807
808         switch (wpa_auth->conf.wpa_group) {
809         case WPA_CIPHER_CCMP:
810                 group->GTK_len = 16;
811                 break;
812         case WPA_CIPHER_TKIP:
813                 group->GTK_len = 32;
814                 break;
815         case WPA_CIPHER_WEP104:
816                 group->GTK_len = 13;
817                 break;
818         case WPA_CIPHER_WEP40:
819                 group->GTK_len = 5;
820                 break;
821         }
822
823         /* Counter = PRF-256(Random number, "Init Counter",
824          *                   Local MAC Address || Time)
825          */
826         memcpy(buf, wpa_auth->addr, ETH_ALEN);
827         wpa_get_ntp_timestamp(buf + ETH_ALEN);
828         memcpy(buf + ETH_ALEN + 8, &group, sizeof(group));
829         if (hostapd_get_rand(rkey, sizeof(rkey)) ||
830             hostapd_get_rand(group->GMK, WPA_GMK_LEN)) {
831                 wpa_printf(MSG_ERROR, "Failed to get random data for WPA "
832                            "initialization.");
833                 free(group);
834                 return NULL;
835         }
836
837         sha1_prf(rkey, sizeof(rkey), "Init Counter", buf, sizeof(buf),
838                  group->Counter, WPA_NONCE_LEN);
839
840         group->GInit = TRUE;
841         wpa_group_sm_step(wpa_auth, group);
842         group->GInit = FALSE;
843         wpa_group_sm_step(wpa_auth, group);
844
845         return group;
846 }
847
848
849 /**
850  * wpa_init - Initialize WPA authenticator
851  * @addr: Authenticator address
852  * @conf: Configuration for WPA authenticator
853  * Returns: Pointer to WPA authenticator data or %NULL on failure
854  */
855 struct wpa_authenticator * wpa_init(const u8 *addr,
856                                     struct wpa_auth_config *conf,
857                                     struct wpa_auth_callbacks *cb)
858 {
859         struct wpa_authenticator *wpa_auth;
860
861         wpa_auth = wpa_zalloc(sizeof(struct wpa_authenticator));
862         if (wpa_auth == NULL)
863                 return NULL;
864         memcpy(wpa_auth->addr, addr, ETH_ALEN);
865         memcpy(&wpa_auth->conf, conf, sizeof(*conf));
866         memcpy(&wpa_auth->cb, cb, sizeof(*cb));
867
868         if (wpa_gen_wpa_ie(wpa_auth)) {
869                 wpa_printf(MSG_ERROR, "Could not generate WPA IE.");
870                 free(wpa_auth);
871                 return NULL;
872         }
873
874         wpa_auth->group = wpa_group_init(wpa_auth, 0);
875         if (wpa_auth->group == NULL) {
876                 free(wpa_auth->wpa_ie);
877                 free(wpa_auth);
878                 return NULL;
879         }
880
881         wpa_auth->pmksa = pmksa_cache_init(wpa_auth_pmksa_free_cb, wpa_auth);
882         if (wpa_auth->pmksa == NULL) {
883                 wpa_printf(MSG_ERROR, "PMKSA cache initialization failed.");
884                 free(wpa_auth->wpa_ie);
885                 free(wpa_auth);
886                 return NULL;
887         }
888
889         if (wpa_auth->conf.wpa_gmk_rekey) {
890                 eloop_register_timeout(wpa_auth->conf.wpa_gmk_rekey, 0,
891                                        wpa_rekey_gmk, wpa_auth, NULL);
892         }
893
894         if (wpa_auth->conf.wpa_group_rekey) {
895                 eloop_register_timeout(wpa_auth->conf.wpa_group_rekey, 0,
896                                        wpa_rekey_gtk, wpa_auth, NULL);
897         }
898
899         return wpa_auth;
900 }
901
902
903 /**
904  * wpa_deinit - Deinitialize WPA authenticator
905  * @wpa_auth: Pointer to WPA authenticator data from wpa_init()
906  */
907 void wpa_deinit(struct wpa_authenticator *wpa_auth)
908 {
909         struct wpa_group *group, *prev;
910
911         eloop_cancel_timeout(wpa_rekey_gmk, wpa_auth, NULL);
912         eloop_cancel_timeout(wpa_rekey_gtk, wpa_auth, NULL);
913
914         while (wpa_auth->stsl_negotiations)
915                 wpa_stsl_remove(wpa_auth, wpa_auth->stsl_negotiations);
916
917         pmksa_cache_deinit(wpa_auth->pmksa);
918
919         free(wpa_auth->wpa_ie);
920
921         group = wpa_auth->group;
922         while (group) {
923                 prev = group;
924                 group = group->next;
925                 free(prev);
926         }
927
928         free(wpa_auth);
929 }
930
931
932 /**
933  * wpa_reconfig - Update WPA authenticator configuration
934  * @wpa_auth: Pointer to WPA authenticator data from wpa_init()
935  * @conf: Configuration for WPA authenticator
936  */
937 int wpa_reconfig(struct wpa_authenticator *wpa_auth,
938                  struct wpa_auth_config *conf)
939 {
940         if (wpa_auth == NULL)
941                 return 0;
942
943         memcpy(&wpa_auth->conf, conf, sizeof(*conf));
944         /*
945          * TODO:
946          * Disassociate stations if configuration changed
947          * Update WPA/RSN IE
948          */
949         return 0;
950 }
951
952
953 static int wpa_selector_to_bitfield(u8 *s)
954 {
955         if (memcmp(s, WPA_CIPHER_SUITE_NONE, WPA_SELECTOR_LEN) == 0)
956                 return WPA_CIPHER_NONE;
957         if (memcmp(s, WPA_CIPHER_SUITE_WEP40, WPA_SELECTOR_LEN) == 0)
958                 return WPA_CIPHER_WEP40;
959         if (memcmp(s, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN) == 0)
960                 return WPA_CIPHER_TKIP;
961         if (memcmp(s, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN) == 0)
962                 return WPA_CIPHER_CCMP;
963         if (memcmp(s, WPA_CIPHER_SUITE_WEP104, WPA_SELECTOR_LEN) == 0)
964                 return WPA_CIPHER_WEP104;
965         return 0;
966 }
967
968
969 static int wpa_key_mgmt_to_bitfield(u8 *s)
970 {
971         if (memcmp(s, WPA_AUTH_KEY_MGMT_UNSPEC_802_1X, WPA_SELECTOR_LEN) == 0)
972                 return WPA_KEY_MGMT_IEEE8021X;
973         if (memcmp(s, WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X, WPA_SELECTOR_LEN) ==
974             0)
975                 return WPA_KEY_MGMT_PSK;
976         return 0;
977 }
978
979
980 static int rsn_selector_to_bitfield(u8 *s)
981 {
982         if (memcmp(s, RSN_CIPHER_SUITE_NONE, RSN_SELECTOR_LEN) == 0)
983                 return WPA_CIPHER_NONE;
984         if (memcmp(s, RSN_CIPHER_SUITE_WEP40, RSN_SELECTOR_LEN) == 0)
985                 return WPA_CIPHER_WEP40;
986         if (memcmp(s, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN) == 0)
987                 return WPA_CIPHER_TKIP;
988         if (memcmp(s, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN) == 0)
989                 return WPA_CIPHER_CCMP;
990         if (memcmp(s, RSN_CIPHER_SUITE_WEP104, RSN_SELECTOR_LEN) == 0)
991                 return WPA_CIPHER_WEP104;
992 #ifdef CONFIG_IEEE80211W
993         if (memcmp(s, RSN_CIPHER_SUITE_AES_128_CMAC, RSN_SELECTOR_LEN) == 0)
994                 return WPA_CIPHER_AES_128_CMAC;
995 #endif /* CONFIG_IEEE80211W */
996         return 0;
997 }
998
999
1000 static int rsn_key_mgmt_to_bitfield(u8 *s)
1001 {
1002         if (memcmp(s, RSN_AUTH_KEY_MGMT_UNSPEC_802_1X, RSN_SELECTOR_LEN) == 0)
1003                 return WPA_KEY_MGMT_IEEE8021X;
1004         if (memcmp(s, RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X, RSN_SELECTOR_LEN) ==
1005             0)
1006                 return WPA_KEY_MGMT_PSK;
1007         return 0;
1008 }
1009
1010
1011 static u8 * wpa_add_kde(u8 *pos, const u8 *kde, const u8 *data,
1012                         size_t data_len, const u8 *data2, size_t data2_len)
1013 {
1014         *pos++ = GENERIC_INFO_ELEM;
1015         *pos++ = RSN_SELECTOR_LEN + data_len + data2_len;
1016         memcpy(pos, kde, RSN_SELECTOR_LEN);
1017         pos += RSN_SELECTOR_LEN;
1018         memcpy(pos, data, data_len);
1019         pos += data_len;
1020         if (data2) {
1021                 memcpy(pos, data2, data2_len);
1022                 pos += data2_len;
1023         }
1024         return pos;
1025 }
1026
1027
1028 struct wpa_ie_data {
1029         int pairwise_cipher;
1030         int group_cipher;
1031         int key_mgmt;
1032         int capabilities;
1033         size_t num_pmkid;
1034         u8 *pmkid;
1035         int mgmt_group_cipher;
1036 };
1037
1038
1039 static int wpa_parse_wpa_ie_wpa(const u8 *wpa_ie, size_t wpa_ie_len,
1040                                 struct wpa_ie_data *data)
1041 {
1042         struct wpa_ie_hdr *hdr;
1043         u8 *pos;
1044         int left;
1045         int i, count;
1046
1047         memset(data, 0, sizeof(*data));
1048         data->pairwise_cipher = WPA_CIPHER_TKIP;
1049         data->group_cipher = WPA_CIPHER_TKIP;
1050         data->key_mgmt = WPA_KEY_MGMT_IEEE8021X;
1051         data->mgmt_group_cipher = 0;
1052
1053         if (wpa_ie_len < sizeof(struct wpa_ie_hdr))
1054                 return -1;
1055
1056         hdr = (struct wpa_ie_hdr *) wpa_ie;
1057
1058         if (hdr->elem_id != WLAN_EID_GENERIC ||
1059             hdr->len != wpa_ie_len - 2 ||
1060             memcmp(&hdr->oui, WPA_OUI_TYPE, WPA_SELECTOR_LEN) != 0 ||
1061             le_to_host16(hdr->version) != WPA_VERSION) {
1062                 return -2;
1063         }
1064
1065         pos = (u8 *) (hdr + 1);
1066         left = wpa_ie_len - sizeof(*hdr);
1067
1068         if (left >= WPA_SELECTOR_LEN) {
1069                 data->group_cipher = wpa_selector_to_bitfield(pos);
1070                 pos += WPA_SELECTOR_LEN;
1071                 left -= WPA_SELECTOR_LEN;
1072         } else if (left > 0)
1073                   return -3;
1074
1075         if (left >= 2) {
1076                 data->pairwise_cipher = 0;
1077                 count = pos[0] | (pos[1] << 8);
1078                 pos += 2;
1079                 left -= 2;
1080                 if (count == 0 || left < count * WPA_SELECTOR_LEN)
1081                         return -4;
1082                 for (i = 0; i < count; i++) {
1083                         data->pairwise_cipher |= wpa_selector_to_bitfield(pos);
1084                         pos += WPA_SELECTOR_LEN;
1085                         left -= WPA_SELECTOR_LEN;
1086                 }
1087         } else if (left == 1)
1088                 return -5;
1089
1090         if (left >= 2) {
1091                 data->key_mgmt = 0;
1092                 count = pos[0] | (pos[1] << 8);
1093                 pos += 2;
1094                 left -= 2;
1095                 if (count == 0 || left < count * WPA_SELECTOR_LEN)
1096                         return -6;
1097                 for (i = 0; i < count; i++) {
1098                         data->key_mgmt |= wpa_key_mgmt_to_bitfield(pos);
1099                         pos += WPA_SELECTOR_LEN;
1100                         left -= WPA_SELECTOR_LEN;
1101                 }
1102         } else if (left == 1)
1103                 return -7;
1104
1105         if (left >= 2) {
1106                 data->capabilities = pos[0] | (pos[1] << 8);
1107                 pos += 2;
1108                 left -= 2;
1109         }
1110
1111         if (left > 0) {
1112                 return -8;
1113         }
1114
1115         return 0;
1116 }
1117
1118
1119 static int wpa_parse_wpa_ie_rsn(const u8 *rsn_ie, size_t rsn_ie_len,
1120                                 struct wpa_ie_data *data)
1121 {
1122         struct rsn_ie_hdr *hdr;
1123         u8 *pos;
1124         int left;
1125         int i, count;
1126
1127         memset(data, 0, sizeof(*data));
1128         data->pairwise_cipher = WPA_CIPHER_CCMP;
1129         data->group_cipher = WPA_CIPHER_CCMP;
1130         data->key_mgmt = WPA_KEY_MGMT_IEEE8021X;
1131 #ifdef CONFIG_IEEE80211W
1132         data->mgmt_group_cipher = WPA_CIPHER_AES_128_CMAC;
1133 #else /* CONFIG_IEEE80211W */
1134         data->mgmt_group_cipher = 0;
1135 #endif /* CONFIG_IEEE80211W */
1136
1137         if (rsn_ie_len < sizeof(struct rsn_ie_hdr))
1138                 return -1;
1139
1140         hdr = (struct rsn_ie_hdr *) rsn_ie;
1141
1142         if (hdr->elem_id != WLAN_EID_RSN ||
1143             hdr->len != rsn_ie_len - 2 ||
1144             le_to_host16(hdr->version) != RSN_VERSION) {
1145                 return -2;
1146         }
1147
1148         pos = (u8 *) (hdr + 1);
1149         left = rsn_ie_len - sizeof(*hdr);
1150
1151         if (left >= RSN_SELECTOR_LEN) {
1152                 data->group_cipher = rsn_selector_to_bitfield(pos);
1153                 pos += RSN_SELECTOR_LEN;
1154                 left -= RSN_SELECTOR_LEN;
1155         } else if (left > 0)
1156                   return -3;
1157
1158         if (left >= 2) {
1159                 data->pairwise_cipher = 0;
1160                 count = pos[0] | (pos[1] << 8);
1161                 pos += 2;
1162                 left -= 2;
1163                 if (count == 0 || left < count * RSN_SELECTOR_LEN)
1164                         return -4;
1165                 for (i = 0; i < count; i++) {
1166                         data->pairwise_cipher |= rsn_selector_to_bitfield(pos);
1167                         pos += RSN_SELECTOR_LEN;
1168                         left -= RSN_SELECTOR_LEN;
1169                 }
1170         } else if (left == 1)
1171                 return -5;
1172
1173         if (left >= 2) {
1174                 data->key_mgmt = 0;
1175                 count = pos[0] | (pos[1] << 8);
1176                 pos += 2;
1177                 left -= 2;
1178                 if (count == 0 || left < count * RSN_SELECTOR_LEN)
1179                         return -6;
1180                 for (i = 0; i < count; i++) {
1181                         data->key_mgmt |= rsn_key_mgmt_to_bitfield(pos);
1182                         pos += RSN_SELECTOR_LEN;
1183                         left -= RSN_SELECTOR_LEN;
1184                 }
1185         } else if (left == 1)
1186                 return -7;
1187
1188         if (left >= 2) {
1189                 data->capabilities = pos[0] | (pos[1] << 8);
1190                 pos += 2;
1191                 left -= 2;
1192         }
1193
1194         if (left >= 2) {
1195                 data->num_pmkid = pos[0] | (pos[1] << 8);
1196                 pos += 2;
1197                 left -= 2;
1198                 if (left < (int) data->num_pmkid * PMKID_LEN) {
1199                         wpa_printf(MSG_DEBUG, "RSN: too short RSN IE for "
1200                                    "PMKIDs (num=%lu, left=%d)",
1201                                    (unsigned long) data->num_pmkid, left);
1202                         return -9;
1203                 }
1204                 data->pmkid = pos;
1205                 pos += data->num_pmkid * PMKID_LEN;
1206                 left -= data->num_pmkid * PMKID_LEN;
1207         }
1208
1209 #ifdef CONFIG_IEEE80211W
1210         if (left >= 4) {
1211                 data->mgmt_group_cipher = rsn_selector_to_bitfield(pos);
1212                 if (data->mgmt_group_cipher != WPA_CIPHER_AES_128_CMAC) {
1213                         wpa_printf(MSG_DEBUG, "RSN: Unsupported management "
1214                                    "group cipher 0x%x",
1215                                    data->mgmt_group_cipher);
1216                         return -10;
1217                 }
1218                 pos += RSN_SELECTOR_LEN;
1219                 left -= RSN_SELECTOR_LEN;
1220         }
1221 #endif /* CONFIG_IEEE80211W */
1222
1223         if (left > 0) {
1224                 return -8;
1225         }
1226
1227         return 0;
1228 }
1229
1230
1231 int wpa_validate_wpa_ie(struct wpa_authenticator *wpa_auth,
1232                         struct wpa_state_machine *sm,
1233                         const u8 *wpa_ie, size_t wpa_ie_len)
1234 {
1235         struct wpa_ie_data data;
1236         int ciphers, key_mgmt, res, version;
1237         const u8 *selector;
1238         size_t i;
1239
1240         if (wpa_auth == NULL || sm == NULL)
1241                 return WPA_NOT_ENABLED;
1242
1243         if (wpa_ie == NULL || wpa_ie_len < 1)
1244                 return WPA_INVALID_IE;
1245
1246         if (wpa_ie[0] == WLAN_EID_RSN)
1247                 version = HOSTAPD_WPA_VERSION_WPA2;
1248         else
1249                 version = HOSTAPD_WPA_VERSION_WPA;
1250
1251         if (version == HOSTAPD_WPA_VERSION_WPA2) {
1252                 res = wpa_parse_wpa_ie_rsn(wpa_ie, wpa_ie_len, &data);
1253
1254                 selector = RSN_AUTH_KEY_MGMT_UNSPEC_802_1X;
1255                 if (data.key_mgmt & WPA_KEY_MGMT_IEEE8021X)
1256                         selector = RSN_AUTH_KEY_MGMT_UNSPEC_802_1X;
1257                 else if (data.key_mgmt & WPA_KEY_MGMT_PSK)
1258                         selector = RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X;
1259                 memcpy(wpa_auth->dot11RSNAAuthenticationSuiteSelected,
1260                        selector, RSN_SELECTOR_LEN);
1261
1262                 selector = RSN_CIPHER_SUITE_CCMP;
1263                 if (data.pairwise_cipher & WPA_CIPHER_CCMP)
1264                         selector = RSN_CIPHER_SUITE_CCMP;
1265                 else if (data.pairwise_cipher & WPA_CIPHER_TKIP)
1266                         selector = RSN_CIPHER_SUITE_TKIP;
1267                 else if (data.pairwise_cipher & WPA_CIPHER_WEP104)
1268                         selector = RSN_CIPHER_SUITE_WEP104;
1269                 else if (data.pairwise_cipher & WPA_CIPHER_WEP40)
1270                         selector = RSN_CIPHER_SUITE_WEP40;
1271                 else if (data.pairwise_cipher & WPA_CIPHER_NONE)
1272                         selector = RSN_CIPHER_SUITE_NONE;
1273                 memcpy(wpa_auth->dot11RSNAPairwiseCipherSelected,
1274                        selector, RSN_SELECTOR_LEN);
1275
1276                 selector = RSN_CIPHER_SUITE_CCMP;
1277                 if (data.group_cipher & WPA_CIPHER_CCMP)
1278                         selector = RSN_CIPHER_SUITE_CCMP;
1279                 else if (data.group_cipher & WPA_CIPHER_TKIP)
1280                         selector = RSN_CIPHER_SUITE_TKIP;
1281                 else if (data.group_cipher & WPA_CIPHER_WEP104)
1282                         selector = RSN_CIPHER_SUITE_WEP104;
1283                 else if (data.group_cipher & WPA_CIPHER_WEP40)
1284                         selector = RSN_CIPHER_SUITE_WEP40;
1285                 else if (data.group_cipher & WPA_CIPHER_NONE)
1286                         selector = RSN_CIPHER_SUITE_NONE;
1287                 memcpy(wpa_auth->dot11RSNAGroupCipherSelected,
1288                        selector, RSN_SELECTOR_LEN);
1289         } else {
1290                 res = wpa_parse_wpa_ie_wpa(wpa_ie, wpa_ie_len, &data);
1291
1292                 selector = WPA_AUTH_KEY_MGMT_UNSPEC_802_1X;
1293                 if (data.key_mgmt & WPA_KEY_MGMT_IEEE8021X)
1294                         selector = WPA_AUTH_KEY_MGMT_UNSPEC_802_1X;
1295                 else if (data.key_mgmt & WPA_KEY_MGMT_PSK)
1296                         selector = WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X;
1297                 memcpy(wpa_auth->dot11RSNAAuthenticationSuiteSelected,
1298                        selector, WPA_SELECTOR_LEN);
1299
1300                 selector = WPA_CIPHER_SUITE_TKIP;
1301                 if (data.pairwise_cipher & WPA_CIPHER_CCMP)
1302                         selector = WPA_CIPHER_SUITE_CCMP;
1303                 else if (data.pairwise_cipher & WPA_CIPHER_TKIP)
1304                         selector = WPA_CIPHER_SUITE_TKIP;
1305                 else if (data.pairwise_cipher & WPA_CIPHER_WEP104)
1306                         selector = WPA_CIPHER_SUITE_WEP104;
1307                 else if (data.pairwise_cipher & WPA_CIPHER_WEP40)
1308                         selector = WPA_CIPHER_SUITE_WEP40;
1309                 else if (data.pairwise_cipher & WPA_CIPHER_NONE)
1310                         selector = WPA_CIPHER_SUITE_NONE;
1311                 memcpy(wpa_auth->dot11RSNAPairwiseCipherSelected,
1312                        selector, WPA_SELECTOR_LEN);
1313
1314                 selector = WPA_CIPHER_SUITE_TKIP;
1315                 if (data.group_cipher & WPA_CIPHER_CCMP)
1316                         selector = WPA_CIPHER_SUITE_CCMP;
1317                 else if (data.group_cipher & WPA_CIPHER_TKIP)
1318                         selector = WPA_CIPHER_SUITE_TKIP;
1319                 else if (data.group_cipher & WPA_CIPHER_WEP104)
1320                         selector = WPA_CIPHER_SUITE_WEP104;
1321                 else if (data.group_cipher & WPA_CIPHER_WEP40)
1322                         selector = WPA_CIPHER_SUITE_WEP40;
1323                 else if (data.group_cipher & WPA_CIPHER_NONE)
1324                         selector = WPA_CIPHER_SUITE_NONE;
1325                 memcpy(wpa_auth->dot11RSNAGroupCipherSelected,
1326                        selector, WPA_SELECTOR_LEN);
1327         }
1328         if (res) {
1329                 wpa_printf(MSG_DEBUG, "Failed to parse WPA/RSN IE from "
1330                            MACSTR " (res=%d)", MAC2STR(sm->addr), res);
1331                 wpa_hexdump(MSG_DEBUG, "WPA/RSN IE", wpa_ie, wpa_ie_len);
1332                 return WPA_INVALID_IE;
1333         }
1334
1335         if (data.group_cipher != wpa_auth->conf.wpa_group) {
1336                 wpa_printf(MSG_DEBUG, "Invalid WPA group cipher (0x%x) from "
1337                            MACSTR, data.group_cipher, MAC2STR(sm->addr));
1338                 return WPA_INVALID_GROUP;
1339         }
1340
1341         key_mgmt = data.key_mgmt & wpa_auth->conf.wpa_key_mgmt;
1342         if (!key_mgmt) {
1343                 wpa_printf(MSG_DEBUG, "Invalid WPA key mgmt (0x%x) from "
1344                            MACSTR, data.key_mgmt, MAC2STR(sm->addr));
1345                 return WPA_INVALID_AKMP;
1346         }
1347         if (key_mgmt & WPA_KEY_MGMT_IEEE8021X)
1348                 sm->wpa_key_mgmt = WPA_KEY_MGMT_IEEE8021X;
1349         else
1350                 sm->wpa_key_mgmt = WPA_KEY_MGMT_PSK;
1351
1352         ciphers = data.pairwise_cipher & wpa_auth->conf.wpa_pairwise;
1353         if (!ciphers) {
1354                 wpa_printf(MSG_DEBUG, "Invalid WPA pairwise cipher (0x%x) "
1355                            "from " MACSTR,
1356                            data.pairwise_cipher, MAC2STR(sm->addr));
1357                 return WPA_INVALID_PAIRWISE;
1358         }
1359
1360 #ifdef CONFIG_IEEE80211W
1361         if (wpa_auth->conf.ieee80211w == WPA_IEEE80211W_REQUIRED) {
1362                 if (!(data.capabilities &
1363                       WPA_CAPABILITY_MGMT_FRAME_PROTECTION)) {
1364                         wpa_printf(MSG_DEBUG, "Management frame protection "
1365                                    "required, but client did not enable it");
1366                         return WPA_MGMT_FRAME_PROTECTION_VIOLATION;
1367                 }
1368
1369                 if (ciphers & WPA_CIPHER_TKIP) {
1370                         wpa_printf(MSG_DEBUG, "Management frame protection "
1371                                    "cannot use TKIP");
1372                         return WPA_MGMT_FRAME_PROTECTION_VIOLATION;
1373                 }
1374
1375                 if (data.mgmt_group_cipher != WPA_CIPHER_AES_128_CMAC) {
1376                         wpa_printf(MSG_DEBUG, "Unsupported management group "
1377                                    "cipher %d", data.mgmt_group_cipher);
1378                         return WPA_INVALID_MGMT_GROUP_CIPHER;
1379                 }
1380         }
1381
1382         if (wpa_auth->conf.ieee80211w == WPA_NO_IEEE80211W ||
1383             !(data.capabilities & WPA_CAPABILITY_MGMT_FRAME_PROTECTION))
1384                 sm->mgmt_frame_prot = 0;
1385         else
1386                 sm->mgmt_frame_prot = 1;
1387 #endif /* CONFIG_IEEE80211W */
1388
1389         if (ciphers & WPA_CIPHER_CCMP)
1390                 sm->pairwise = WPA_CIPHER_CCMP;
1391         else
1392                 sm->pairwise = WPA_CIPHER_TKIP;
1393
1394         /* TODO: clear WPA/WPA2 state if STA changes from one to another */
1395         if (wpa_ie[0] == WLAN_EID_RSN)
1396                 sm->wpa = WPA_VERSION_WPA2;
1397         else
1398                 sm->wpa = WPA_VERSION_WPA;
1399
1400         for (i = 0; i < data.num_pmkid; i++) {
1401                 wpa_hexdump(MSG_DEBUG, "RSN IE: STA PMKID",
1402                             &data.pmkid[i * PMKID_LEN], PMKID_LEN);
1403                 sm->pmksa = pmksa_cache_get(wpa_auth->pmksa, sm->addr,
1404                                             &data.pmkid[i * PMKID_LEN]);
1405                 if (sm->pmksa) {
1406                         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_DEBUG,
1407                                          "PMKID found from PMKSA cache "
1408                                          "eap_type=%d vlan_id=%d",
1409                                          sm->pmksa->eap_type_authsrv,
1410                                          sm->pmksa->vlan_id);
1411                         memcpy(wpa_auth->dot11RSNAPMKIDUsed,
1412                                sm->pmksa->pmkid, PMKID_LEN);
1413                         break;
1414                 }
1415         }
1416
1417         if (sm->wpa_ie == NULL || sm->wpa_ie_len < wpa_ie_len) {
1418                 free(sm->wpa_ie);
1419                 sm->wpa_ie = malloc(wpa_ie_len);
1420                 if (sm->wpa_ie == NULL)
1421                         return WPA_ALLOC_FAIL;
1422         }
1423         memcpy(sm->wpa_ie, wpa_ie, wpa_ie_len);
1424         sm->wpa_ie_len = wpa_ie_len;
1425
1426         return WPA_IE_OK;
1427 }
1428
1429
1430 struct wpa_eapol_ie_parse {
1431         const u8 *wpa_ie;
1432         size_t wpa_ie_len;
1433         const u8 *rsn_ie;
1434         size_t rsn_ie_len;
1435         const u8 *pmkid;
1436         const u8 *gtk;
1437         size_t gtk_len;
1438         const u8 *mac_addr;
1439         size_t mac_addr_len;
1440 #ifdef CONFIG_PEERKEY
1441         const u8 *smk;
1442         size_t smk_len;
1443         const u8 *nonce;
1444         size_t nonce_len;
1445         const u8 *lifetime;
1446         size_t lifetime_len;
1447         const u8 *error;
1448         size_t error_len;
1449 #endif /* CONFIG_PEERKEY */
1450 };
1451
1452
1453 /**
1454  * wpa_parse_generic - Parse EAPOL-Key Key Data Generic IEs
1455  * @pos: Pointer to the IE header
1456  * @end: Pointer to the end of the Key Data buffer
1457  * @ie: Pointer to parsed IE data
1458  * Returns: 0 on success, 1 if end mark is found, -1 on failure
1459  */
1460 static int wpa_parse_generic(const u8 *pos, const u8 *end,
1461                              struct wpa_eapol_ie_parse *ie)
1462 {
1463         if (pos[1] == 0)
1464                 return 1;
1465
1466         if (pos[1] >= 6 &&
1467             memcmp(pos + 2, WPA_OUI_TYPE, WPA_SELECTOR_LEN) == 0 &&
1468             pos[2 + WPA_SELECTOR_LEN] == 1 &&
1469             pos[2 + WPA_SELECTOR_LEN + 1] == 0) {
1470                 ie->wpa_ie = pos;
1471                 ie->wpa_ie_len = pos[1] + 2;
1472                 return 0;
1473         }
1474
1475         if (pos + 1 + RSN_SELECTOR_LEN < end &&
1476             pos[1] >= RSN_SELECTOR_LEN + PMKID_LEN &&
1477             memcmp(pos + 2, RSN_KEY_DATA_PMKID, RSN_SELECTOR_LEN) == 0) {
1478                 ie->pmkid = pos + 2 + RSN_SELECTOR_LEN;
1479                 return 0;
1480         }
1481
1482         if (pos[1] > RSN_SELECTOR_LEN + 2 &&
1483             memcmp(pos + 2, RSN_KEY_DATA_GROUPKEY, RSN_SELECTOR_LEN) == 0) {
1484                 ie->gtk = pos + 2 + RSN_SELECTOR_LEN;
1485                 ie->gtk_len = pos[1] - RSN_SELECTOR_LEN;
1486                 return 0;
1487         }
1488
1489         if (pos[1] > RSN_SELECTOR_LEN + 2 &&
1490             memcmp(pos + 2, RSN_KEY_DATA_MAC_ADDR, RSN_SELECTOR_LEN) == 0) {
1491                 ie->mac_addr = pos + 2 + RSN_SELECTOR_LEN;
1492                 ie->mac_addr_len = pos[1] - RSN_SELECTOR_LEN;
1493                 return 0;
1494         }
1495
1496 #ifdef CONFIG_PEERKEY
1497         if (pos[1] > RSN_SELECTOR_LEN + 2 &&
1498             memcmp(pos + 2, RSN_KEY_DATA_SMK, RSN_SELECTOR_LEN) == 0) {
1499                 ie->smk = pos + 2 + RSN_SELECTOR_LEN;
1500                 ie->smk_len = pos[1] - RSN_SELECTOR_LEN;
1501                 return 0;
1502         }
1503
1504         if (pos[1] > RSN_SELECTOR_LEN + 2 &&
1505             memcmp(pos + 2, RSN_KEY_DATA_NONCE, RSN_SELECTOR_LEN) == 0) {
1506                 ie->nonce = pos + 2 + RSN_SELECTOR_LEN;
1507                 ie->nonce_len = pos[1] - RSN_SELECTOR_LEN;
1508                 return 0;
1509         }
1510
1511         if (pos[1] > RSN_SELECTOR_LEN + 2 &&
1512             memcmp(pos + 2, RSN_KEY_DATA_LIFETIME, RSN_SELECTOR_LEN) == 0) {
1513                 ie->lifetime = pos + 2 + RSN_SELECTOR_LEN;
1514                 ie->lifetime_len = pos[1] - RSN_SELECTOR_LEN;
1515                 return 0;
1516         }
1517
1518         if (pos[1] > RSN_SELECTOR_LEN + 2 &&
1519             memcmp(pos + 2, RSN_KEY_DATA_ERROR, RSN_SELECTOR_LEN) == 0) {
1520                 ie->error = pos + 2 + RSN_SELECTOR_LEN;
1521                 ie->error_len = pos[1] - RSN_SELECTOR_LEN;
1522                 return 0;
1523         }
1524 #endif /* CONFIG_PEERKEY */
1525
1526         return 0;
1527 }
1528
1529
1530 /**
1531  * wpa_parse_kde_ies - Parse EAPOL-Key Key Data IEs
1532  * @buf: Pointer to the Key Data buffer
1533  * @len: Key Data Length
1534  * @ie: Pointer to parsed IE data
1535  * Returns: 0 on success, -1 on failure
1536  */
1537 static int wpa_parse_kde_ies(const u8 *buf, size_t len,
1538                              struct wpa_eapol_ie_parse *ie)
1539 {
1540         const u8 *pos, *end;
1541         int ret = 0;
1542
1543         memset(ie, 0, sizeof(*ie));
1544         for (pos = buf, end = pos + len; pos + 1 < end; pos += 2 + pos[1]) {
1545                 if (pos[0] == 0xdd &&
1546                     ((pos == buf + len - 1) || pos[1] == 0)) {
1547                         /* Ignore padding */
1548                         break;
1549                 }
1550                 if (pos + 2 + pos[1] > end) {
1551                         wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key Key Data "
1552                                    "underflow (ie=%d len=%d)", pos[0], pos[1]);
1553                         ret = -1;
1554                         break;
1555                 }
1556                 if (*pos == RSN_INFO_ELEM) {
1557                         ie->rsn_ie = pos;
1558                         ie->rsn_ie_len = pos[1] + 2;
1559                 } else if (*pos == GENERIC_INFO_ELEM) {
1560                         ret = wpa_parse_generic(pos, end, ie);
1561                         if (ret < 0)
1562                                 break;
1563                         if (ret > 0) {
1564                                 ret = 0;
1565                                 break;
1566                         }
1567                 } else {
1568                         wpa_hexdump(MSG_DEBUG, "WPA: Unrecognized EAPOL-Key "
1569                                     "Key Data IE", pos, 2 + pos[1]);
1570                 }
1571         }
1572
1573         return ret;
1574 }
1575
1576
1577 struct wpa_state_machine *
1578 wpa_auth_sta_init(struct wpa_authenticator *wpa_auth, const u8 *addr)
1579 {
1580         struct wpa_state_machine *sm;
1581
1582         sm = wpa_zalloc(sizeof(struct wpa_state_machine));
1583         if (sm == NULL)
1584                 return NULL;
1585         memcpy(sm->addr, addr, ETH_ALEN);
1586
1587         sm->wpa_auth = wpa_auth;
1588         sm->group = wpa_auth->group;
1589
1590         return sm;
1591 }
1592
1593
1594 void wpa_auth_sta_associated(struct wpa_authenticator *wpa_auth,
1595                              struct wpa_state_machine *sm)
1596 {
1597         if (wpa_auth == NULL || !wpa_auth->conf.wpa || sm == NULL)
1598                 return;
1599
1600         if (sm->started) {
1601                 memset(sm->key_replay_counter, 0, WPA_REPLAY_COUNTER_LEN);
1602                 sm->ReAuthenticationRequest = TRUE;
1603                 wpa_sm_step(sm);
1604                 return;
1605         }
1606
1607         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG,
1608                         "start authentication");
1609         sm->started = 1;
1610
1611         sm->Init = TRUE;
1612         wpa_sm_step(sm);
1613         sm->Init = FALSE;
1614         sm->AuthenticationRequest = TRUE;
1615         wpa_sm_step(sm);
1616 }
1617
1618
1619 static void wpa_free_sta_sm(struct wpa_state_machine *sm)
1620 {
1621         free(sm->last_rx_eapol_key);
1622         free(sm->wpa_ie);
1623         free(sm);
1624 }
1625
1626
1627 void wpa_auth_sta_deinit(struct wpa_state_machine *sm)
1628 {
1629         if (sm == NULL)
1630                 return;
1631
1632         if (sm->wpa_auth->conf.wpa_strict_rekey && sm->has_GTK) {
1633                 wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
1634                                 "strict rekeying - force GTK rekey since STA "
1635                                 "is leaving");
1636                 eloop_cancel_timeout(wpa_rekey_gtk, sm->wpa_auth, NULL);
1637                 eloop_register_timeout(0, 500000, wpa_rekey_gtk, sm->wpa_auth,
1638                                        NULL);
1639         }
1640
1641         eloop_cancel_timeout(wpa_send_eapol_timeout, sm->wpa_auth, sm);
1642         eloop_cancel_timeout(wpa_sm_call_step, sm, NULL);
1643         if (sm->in_step_loop) {
1644                 /* Must not free state machine while wpa_sm_step() is running.
1645                  * Freeing will be completed in the end of wpa_sm_step(). */
1646                 wpa_printf(MSG_DEBUG, "WPA: Registering pending STA state "
1647                            "machine deinit for " MACSTR, MAC2STR(sm->addr));
1648                 sm->pending_deinit = 1;
1649         } else
1650                 wpa_free_sta_sm(sm);
1651 }
1652
1653
1654 static void wpa_request_new_ptk(struct wpa_state_machine *sm)
1655 {
1656         if (sm == NULL)
1657                 return;
1658
1659         sm->PTKRequest = TRUE;
1660         sm->PTK_valid = 0;
1661 }
1662
1663
1664 #ifdef CONFIG_PEERKEY
1665 static void wpa_stsl_step(void *eloop_ctx, void *timeout_ctx)
1666 {
1667 #if 0
1668         struct wpa_authenticator *wpa_auth = eloop_ctx;
1669         struct wpa_stsl_negotiation *neg = timeout_ctx;
1670 #endif
1671
1672         /* TODO: ? */
1673 }
1674
1675
1676 struct wpa_stsl_search {
1677         const u8 *addr;
1678         struct wpa_state_machine *sm;
1679 };
1680
1681
1682 static int wpa_stsl_select_sta(struct wpa_state_machine *sm, void *ctx)
1683 {
1684         struct wpa_stsl_search *search = ctx;
1685         if (memcmp(search->addr, sm->addr, ETH_ALEN) == 0) {
1686                 search->sm = sm;
1687                 return 1;
1688         }
1689         return 0;
1690 }
1691
1692
1693 static void wpa_smk_send_error(struct wpa_authenticator *wpa_auth,
1694                                struct wpa_state_machine *sm, const u8 *peer,
1695                                u16 mui, u16 error_type)
1696 {
1697         u8 kde[2 + RSN_SELECTOR_LEN + ETH_ALEN +
1698                2 + RSN_SELECTOR_LEN + sizeof(struct rsn_error_kde)];
1699         size_t kde_len;
1700         u8 *pos;
1701         struct rsn_error_kde error;
1702
1703         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG,
1704                         "Sending SMK Error");
1705
1706         kde_len = 2 + RSN_SELECTOR_LEN + sizeof(struct rsn_error_kde);
1707         pos = kde;
1708
1709         if (peer) {
1710                 pos = wpa_add_kde(pos, RSN_KEY_DATA_MAC_ADDR, peer, ETH_ALEN,
1711                                   NULL, 0);
1712                 kde_len += 2 + RSN_SELECTOR_LEN + ETH_ALEN;
1713         }
1714
1715         error.mui = host_to_be16(mui);
1716         error.error_type = host_to_be16(error_type);
1717         pos = wpa_add_kde(pos, RSN_KEY_DATA_ERROR,
1718                           (u8 *) &error, sizeof(error), NULL, 0);
1719
1720         __wpa_send_eapol(wpa_auth, sm,
1721                          WPA_KEY_INFO_SECURE | WPA_KEY_INFO_MIC |
1722                          WPA_KEY_INFO_SMK_MESSAGE | WPA_KEY_INFO_ERROR,
1723                          NULL, NULL, kde, kde_len, 0, 0, 0);
1724 }
1725
1726
1727 static void wpa_smk_m1(struct wpa_authenticator *wpa_auth,
1728                        struct wpa_state_machine *sm,
1729                        struct wpa_eapol_key *key)
1730 {
1731         struct wpa_eapol_ie_parse kde;
1732         struct wpa_stsl_search search;
1733         u8 *buf, *pos;
1734         size_t buf_len;
1735
1736         if (wpa_parse_kde_ies((const u8 *) (key + 1),
1737                               ntohs(key->key_data_length), &kde) < 0) {
1738                 wpa_printf(MSG_INFO, "RSN: Failed to parse KDEs in SMK M1");
1739                 return;
1740         }
1741
1742         if (kde.rsn_ie == NULL || kde.mac_addr == NULL ||
1743             kde.mac_addr_len < ETH_ALEN) {
1744                 wpa_printf(MSG_INFO, "RSN: No RSN IE or MAC address KDE in "
1745                            "SMK M1");
1746                 return;
1747         }
1748
1749         /* Initiator = sm->addr; Peer = kde.mac_addr */
1750
1751         search.addr = kde.mac_addr;
1752         search.sm = NULL;
1753         if (wpa_auth_for_each_sta(wpa_auth, wpa_stsl_select_sta, &search) ==
1754             0 || search.sm == NULL) {
1755                 wpa_printf(MSG_DEBUG, "RSN: SMK handshake with " MACSTR
1756                            " aborted - STA not associated anymore",
1757                            MAC2STR(kde.mac_addr));
1758                 wpa_smk_send_error(wpa_auth, sm, kde.mac_addr, STK_MUI_SMK,
1759                                    STK_ERR_STA_NR);
1760                 /* FIX: wpa_stsl_remove(wpa_auth, neg); */
1761                 return;
1762         }
1763
1764         buf_len = kde.rsn_ie_len + 2 + RSN_SELECTOR_LEN + ETH_ALEN;
1765         buf = malloc(buf_len);
1766         if (buf == NULL)
1767                 return;
1768         /* Initiator RSN IE */
1769         memcpy(buf, kde.rsn_ie, kde.rsn_ie_len);
1770         pos = buf + kde.rsn_ie_len;
1771         /* Initiator MAC Address */
1772         pos = wpa_add_kde(pos, RSN_KEY_DATA_MAC_ADDR, sm->addr, ETH_ALEN,
1773                           NULL, 0);
1774
1775         /* SMK M2:
1776          * EAPOL-Key(S=1, M=1, A=1, I=0, K=0, SM=1, KeyRSC=0, Nonce=INonce,
1777          *           MIC=MIC, DataKDs=(RSNIE_I, MAC_I KDE)
1778          */
1779
1780         wpa_auth_logger(wpa_auth, search.sm->addr, LOGGER_DEBUG,
1781                         "Sending SMK M2");
1782
1783         __wpa_send_eapol(wpa_auth, search.sm,
1784                          WPA_KEY_INFO_SECURE | WPA_KEY_INFO_MIC |
1785                          WPA_KEY_INFO_ACK | WPA_KEY_INFO_SMK_MESSAGE,
1786                          NULL, key->key_nonce, buf, buf_len, 0, 0, 0);
1787
1788         free(buf);
1789
1790 }
1791
1792
1793 static void wpa_send_smk_m4(struct wpa_authenticator *wpa_auth,
1794                             struct wpa_state_machine *sm,
1795                             struct wpa_eapol_key *key,
1796                             struct wpa_eapol_ie_parse *kde,
1797                             const u8 *smk)
1798 {
1799         u8 *buf, *pos;
1800         size_t buf_len;
1801         u32 lifetime;
1802
1803         /* SMK M4:
1804          * EAPOL-Key(S=1, M=1, A=0, I=1, K=0, SM=1, KeyRSC=0, Nonce=PNonce,
1805          *           MIC=MIC, DataKDs=(MAC_I KDE, INonce KDE, SMK KDE,
1806          *           Lifetime KDE)
1807          */
1808
1809         buf_len = 2 + RSN_SELECTOR_LEN + ETH_ALEN +
1810                 2 + RSN_SELECTOR_LEN + WPA_NONCE_LEN +
1811                 2 + RSN_SELECTOR_LEN + WPA_PMK_LEN + WPA_NONCE_LEN +
1812                 2 + RSN_SELECTOR_LEN + sizeof(lifetime);
1813         pos = buf = malloc(buf_len);
1814         if (buf == NULL)
1815                 return;
1816
1817         /* Initiator MAC Address */
1818         pos = wpa_add_kde(pos, RSN_KEY_DATA_MAC_ADDR, kde->mac_addr, ETH_ALEN,
1819                           NULL, 0);
1820
1821         /* Initiator Nonce */
1822         pos = wpa_add_kde(pos, RSN_KEY_DATA_NONCE, kde->nonce, WPA_NONCE_LEN,
1823                           NULL, 0);
1824
1825         /* SMK with PNonce */
1826         pos = wpa_add_kde(pos, RSN_KEY_DATA_SMK, smk, WPA_PMK_LEN,
1827                           key->key_nonce, WPA_NONCE_LEN);
1828
1829         /* Lifetime */
1830         lifetime = htonl(43200); /* dot11RSNAConfigSMKLifetime */
1831         pos = wpa_add_kde(pos, RSN_KEY_DATA_LIFETIME,
1832                           (u8 *) &lifetime, sizeof(lifetime), NULL, 0);
1833
1834         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
1835                         "Sending SMK M4");
1836
1837         __wpa_send_eapol(wpa_auth, sm,
1838                          WPA_KEY_INFO_SECURE | WPA_KEY_INFO_MIC |
1839                          WPA_KEY_INFO_INSTALL | WPA_KEY_INFO_SMK_MESSAGE,
1840                          NULL, key->key_nonce, buf, buf_len, 0, 1, 0);
1841
1842         free(buf);
1843 }
1844
1845
1846 static void wpa_send_smk_m5(struct wpa_authenticator *wpa_auth,
1847                             struct wpa_state_machine *sm,
1848                             struct wpa_eapol_key *key,
1849                             struct wpa_eapol_ie_parse *kde,
1850                             const u8 *smk, const u8 *peer)
1851 {
1852         u8 *buf, *pos;
1853         size_t buf_len;
1854         u32 lifetime;
1855
1856         /* SMK M5:
1857          * EAPOL-Key(S=1, M=1, A=0, I=0, K=0, SM=1, KeyRSC=0, Nonce=INonce,
1858          *           MIC=MIC, DataKDs=(RSNIE_P, MAC_P KDE, PNonce, SMK KDE,
1859          *                             Lifetime KDE))
1860          */
1861
1862         buf_len = kde->rsn_ie_len +
1863                 2 + RSN_SELECTOR_LEN + ETH_ALEN +
1864                 2 + RSN_SELECTOR_LEN + WPA_NONCE_LEN +
1865                 2 + RSN_SELECTOR_LEN + WPA_PMK_LEN + WPA_NONCE_LEN +
1866                 2 + RSN_SELECTOR_LEN + sizeof(lifetime);
1867         pos = buf = malloc(buf_len);
1868         if (buf == NULL)
1869                 return;
1870
1871         /* Peer RSN IE */
1872         memcpy(buf, kde->rsn_ie, kde->rsn_ie_len);
1873         pos = buf + kde->rsn_ie_len;
1874
1875         /* Peer MAC Address */
1876         pos = wpa_add_kde(pos, RSN_KEY_DATA_MAC_ADDR, peer, ETH_ALEN, NULL, 0);
1877
1878         /* PNonce */
1879         pos = wpa_add_kde(pos, RSN_KEY_DATA_NONCE, key->key_nonce,
1880                           WPA_NONCE_LEN, NULL, 0);
1881
1882         /* SMK and INonce */
1883         pos = wpa_add_kde(pos, RSN_KEY_DATA_SMK, smk, WPA_PMK_LEN,
1884                           kde->nonce, WPA_NONCE_LEN);
1885
1886         /* Lifetime */
1887         lifetime = htonl(43200); /* dot11RSNAConfigSMKLifetime */
1888         pos = wpa_add_kde(pos, RSN_KEY_DATA_LIFETIME,
1889                           (u8 *) &lifetime, sizeof(lifetime), NULL, 0);
1890
1891         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
1892                         "Sending SMK M5");
1893
1894         __wpa_send_eapol(wpa_auth, sm,
1895                          WPA_KEY_INFO_SECURE | WPA_KEY_INFO_MIC |
1896                          WPA_KEY_INFO_SMK_MESSAGE,
1897                          NULL, kde->nonce, buf, buf_len, 0, 1, 0);
1898
1899         free(buf);
1900 }
1901
1902
1903 static void wpa_smk_m3(struct wpa_authenticator *wpa_auth,
1904                        struct wpa_state_machine *sm,
1905                        struct wpa_eapol_key *key)
1906 {
1907         struct wpa_eapol_ie_parse kde;
1908         struct wpa_stsl_search search;
1909         u8 smk[32], buf[ETH_ALEN + 8 + 2 * WPA_NONCE_LEN], *pos;
1910
1911         if (wpa_parse_kde_ies((const u8 *) (key + 1),
1912                               ntohs(key->key_data_length), &kde) < 0) {
1913                 wpa_printf(MSG_INFO, "RSN: Failed to parse KDEs in SMK M3");
1914                 return;
1915         }
1916
1917         if (kde.rsn_ie == NULL ||
1918             kde.mac_addr == NULL || kde.mac_addr_len < ETH_ALEN ||
1919             kde.nonce == NULL || kde.nonce_len < WPA_NONCE_LEN) {
1920                 wpa_printf(MSG_INFO, "RSN: No RSN IE, MAC address KDE, or "
1921                            "Nonce KDE in SMK M3");
1922                 return;
1923         }
1924
1925         /* Peer = sm->addr; Initiator = kde.mac_addr;
1926          * Peer Nonce = key->key_nonce; Initiator Nonce = kde.nonce */
1927
1928         search.addr = kde.mac_addr;
1929         search.sm = NULL;
1930         if (wpa_auth_for_each_sta(wpa_auth, wpa_stsl_select_sta, &search) ==
1931             0 || search.sm == NULL) {
1932                 wpa_printf(MSG_DEBUG, "RSN: SMK handshake with " MACSTR
1933                            " aborted - STA not associated anymore",
1934                            MAC2STR(kde.mac_addr));
1935                 wpa_smk_send_error(wpa_auth, sm, kde.mac_addr, STK_MUI_SMK,
1936                                    STK_ERR_STA_NR);
1937                 /* FIX: wpa_stsl_remove(wpa_auth, neg); */
1938                 return;
1939         }
1940
1941         if (hostapd_get_rand(smk, WPA_PMK_LEN)) {
1942                 wpa_printf(MSG_DEBUG, "RSN: Failed to generate SMK");
1943                 return;
1944         }
1945
1946         /* SMK = PRF-256(Random number, "SMK Derivation",
1947          *               AA || Time || INonce || PNonce)
1948          */
1949         memcpy(buf, wpa_auth->addr, ETH_ALEN);
1950         pos = buf + ETH_ALEN;
1951         wpa_get_ntp_timestamp(pos);
1952         pos += 8;
1953         memcpy(pos, kde.nonce, WPA_NONCE_LEN);
1954         pos += WPA_NONCE_LEN;
1955         memcpy(pos, key->key_nonce, WPA_NONCE_LEN);
1956         sha1_prf(smk, WPA_PMK_LEN, "SMK Derivation", buf, sizeof(buf),
1957                  smk, WPA_PMK_LEN);
1958
1959         wpa_hexdump_key(MSG_DEBUG, "RSN: SMK", smk, WPA_PMK_LEN);
1960
1961         wpa_send_smk_m4(wpa_auth, sm, key, &kde, smk);
1962         wpa_send_smk_m5(wpa_auth, search.sm, key, &kde, smk, sm->addr);
1963
1964         /* Authenticator does not need SMK anymore and it is required to forget
1965          * it. */
1966         memset(smk, 0, sizeof(*smk));
1967 }
1968
1969
1970 static void wpa_smk_error(struct wpa_authenticator *wpa_auth,
1971                           struct wpa_state_machine *sm,
1972                           struct wpa_eapol_key *key)
1973 {
1974         struct wpa_eapol_ie_parse kde;
1975         struct wpa_stsl_search search;
1976         struct rsn_error_kde error;
1977         u16 mui, error_type;
1978
1979         if (wpa_parse_kde_ies((const u8 *) (key + 1),
1980                               ntohs(key->key_data_length), &kde) < 0) {
1981                 wpa_printf(MSG_INFO, "RSN: Failed to parse KDEs in SMK Error");
1982                 return;
1983         }
1984
1985         if (kde.mac_addr == NULL || kde.mac_addr_len < ETH_ALEN ||
1986             kde.error == NULL || kde.error_len < sizeof(error)) {
1987                 wpa_printf(MSG_INFO, "RSN: No MAC address or Error KDE in "
1988                            "SMK Error");
1989                 return;
1990         }
1991
1992         search.addr = kde.mac_addr;
1993         search.sm = NULL;
1994         if (wpa_auth_for_each_sta(wpa_auth, wpa_stsl_select_sta, &search) ==
1995             0 || search.sm == NULL) {
1996                 wpa_printf(MSG_DEBUG, "RSN: Peer STA " MACSTR " not "
1997                            "associated for SMK Error message from " MACSTR,
1998                            MAC2STR(kde.mac_addr), MAC2STR(sm->addr));
1999                 return;
2000         }
2001
2002         memcpy(&error, kde.error, sizeof(error));
2003         mui = be_to_host16(error.mui);
2004         error_type = be_to_host16(error.error_type);
2005         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
2006                          "STA reported SMK Error: Peer " MACSTR
2007                          " MUI %d Error Type %d",
2008                          MAC2STR(kde.mac_addr), mui, error_type);
2009
2010         wpa_smk_send_error(wpa_auth, search.sm, sm->addr, mui, error_type);
2011 }
2012 #endif /* CONFIG_PEERKEY */
2013
2014
2015 static int wpa_stsl_remove(struct wpa_authenticator *wpa_auth,
2016                            struct wpa_stsl_negotiation *neg)
2017 {
2018 #ifdef CONFIG_PEERKEY
2019         struct wpa_stsl_negotiation *pos, *prev;
2020
2021         if (wpa_auth == NULL)
2022                 return -1;
2023         pos = wpa_auth->stsl_negotiations;
2024         prev = NULL;
2025         while (pos) {
2026                 if (pos == neg) {
2027                         if (prev)
2028                                 prev->next = pos->next;
2029                         else
2030                                 wpa_auth->stsl_negotiations = pos->next;
2031
2032                         eloop_cancel_timeout(wpa_stsl_step, wpa_auth, pos);
2033                         free(pos);
2034                         return 0;
2035                 }
2036                 prev = pos;
2037                 pos = pos->next;
2038         }
2039 #endif /* CONFIG_PEERKEY */
2040
2041         return -1;
2042 }
2043
2044
2045 void wpa_receive(struct wpa_authenticator *wpa_auth,
2046                  struct wpa_state_machine *sm,
2047                  u8 *data, size_t data_len)
2048 {
2049         struct ieee802_1x_hdr *hdr;
2050         struct wpa_eapol_key *key;
2051         u16 key_info, key_data_length;
2052         enum { PAIRWISE_2, PAIRWISE_4, GROUP_2, REQUEST,
2053                SMK_M1, SMK_M3, SMK_ERROR } msg;
2054         char *msgtxt;
2055         struct wpa_eapol_ie_parse kde;
2056
2057         if (wpa_auth == NULL || !wpa_auth->conf.wpa || sm == NULL)
2058                 return;
2059
2060         if (data_len < sizeof(*hdr) + sizeof(*key))
2061                 return;
2062
2063         hdr = (struct ieee802_1x_hdr *) data;
2064         key = (struct wpa_eapol_key *) (hdr + 1);
2065         key_info = ntohs(key->key_info);
2066         key_data_length = ntohs(key->key_data_length);
2067         if (key_data_length > data_len - sizeof(*hdr) - sizeof(*key)) {
2068                 wpa_printf(MSG_INFO, "WPA: Invalid EAPOL-Key frame - "
2069                            "key_data overflow (%d > %lu)",
2070                            key_data_length,
2071                            (unsigned long) (data_len - sizeof(*hdr) -
2072                                             sizeof(*key)));
2073                 return;
2074         }
2075
2076         /* FIX: verify that the EAPOL-Key frame was encrypted if pairwise keys
2077          * are set */
2078
2079         if ((key_info & (WPA_KEY_INFO_SMK_MESSAGE | WPA_KEY_INFO_REQUEST)) ==
2080             (WPA_KEY_INFO_SMK_MESSAGE | WPA_KEY_INFO_REQUEST)) {
2081                 if (key_info & WPA_KEY_INFO_ERROR) {
2082                         msg = SMK_ERROR;
2083                         msgtxt = "SMK Error";
2084                 } else {
2085                         msg = SMK_M1;
2086                         msgtxt = "SMK M1";
2087                 }
2088         } else if (key_info & WPA_KEY_INFO_SMK_MESSAGE) {
2089                 msg = SMK_M3;
2090                 msgtxt = "SMK M3";
2091         } else if (key_info & WPA_KEY_INFO_REQUEST) {
2092                 msg = REQUEST;
2093                 msgtxt = "Request";
2094         } else if (!(key_info & WPA_KEY_INFO_KEY_TYPE)) {
2095                 msg = GROUP_2;
2096                 msgtxt = "2/2 Group";
2097         } else if (key_data_length == 0) {
2098                 msg = PAIRWISE_4;
2099                 msgtxt = "4/4 Pairwise";
2100         } else {
2101                 msg = PAIRWISE_2;
2102                 msgtxt = "2/4 Pairwise";
2103         }
2104
2105         if (key_info & WPA_KEY_INFO_REQUEST) {
2106                 if (sm->req_replay_counter_used &&
2107                     memcmp(key->replay_counter, sm->req_replay_counter,
2108                            WPA_REPLAY_COUNTER_LEN) <= 0) {
2109                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_WARNING,
2110                                         "received EAPOL-Key request with "
2111                                         "replayed counter");
2112                         return;
2113                 }
2114         }
2115
2116         if (!(key_info & WPA_KEY_INFO_REQUEST) &&
2117             (!sm->key_replay_counter_valid ||
2118              memcmp(key->replay_counter, sm->key_replay_counter,
2119                     WPA_REPLAY_COUNTER_LEN) != 0)) {
2120                 wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
2121                                  "received EAPOL-Key %s with unexpected "
2122                                  "replay counter", msgtxt);
2123                 wpa_hexdump(MSG_DEBUG, "expected replay counter",
2124                             sm->key_replay_counter, WPA_REPLAY_COUNTER_LEN);
2125                 wpa_hexdump(MSG_DEBUG, "received replay counter",
2126                             key->replay_counter, WPA_REPLAY_COUNTER_LEN);
2127                 return;
2128         }
2129
2130         switch (msg) {
2131         case PAIRWISE_2:
2132                 if (sm->wpa_ptk_state != WPA_PTK_PTKSTART &&
2133                     sm->wpa_ptk_state != WPA_PTK_PTKCALCNEGOTIATING) {
2134                         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
2135                                          "received EAPOL-Key msg 2/4 in "
2136                                          "invalid state (%d) - dropped",
2137                                          sm->wpa_ptk_state);
2138                         return;
2139                 }
2140                 if (sm->wpa_ie == NULL ||
2141                     sm->wpa_ie_len != key_data_length ||
2142                     memcmp(sm->wpa_ie, key + 1, key_data_length) != 0) {
2143                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2144                                         "WPA IE from (Re)AssocReq did not "
2145                                         "match with msg 2/4");
2146                         if (sm->wpa_ie) {
2147                                 wpa_hexdump(MSG_DEBUG, "WPA IE in AssocReq",
2148                                             sm->wpa_ie, sm->wpa_ie_len);
2149                         }
2150                         wpa_hexdump(MSG_DEBUG, "WPA IE in msg 2/4",
2151                                     (u8 *) (key + 1), key_data_length);
2152                         /* MLME-DEAUTHENTICATE.request */
2153                         wpa_sta_disconnect(wpa_auth, sm->addr);
2154                         return;
2155                 }
2156                 break;
2157         case PAIRWISE_4:
2158                 if (sm->wpa_ptk_state != WPA_PTK_PTKINITNEGOTIATING ||
2159                     !sm->PTK_valid) {
2160                         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
2161                                          "received EAPOL-Key msg 4/4 in "
2162                                          "invalid state (%d) - dropped",
2163                                          sm->wpa_ptk_state);
2164                         return;
2165                 }
2166                 break;
2167         case GROUP_2:
2168                 if (sm->wpa_ptk_group_state != WPA_PTK_GROUP_REKEYNEGOTIATING
2169                     || !sm->PTK_valid) {
2170                         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
2171                                          "received EAPOL-Key msg 2/2 in "
2172                                          "invalid state (%d) - dropped",
2173                                          sm->wpa_ptk_group_state);
2174                         return;
2175                 }
2176                 break;
2177 #ifdef CONFIG_PEERKEY
2178         case SMK_M1:
2179         case SMK_M3:
2180         case SMK_ERROR:
2181                 if (!wpa_auth->conf.peerkey) {
2182                         wpa_printf(MSG_DEBUG, "RSN: SMK M1/M3/Error, but "
2183                                    "PeerKey use disabled - ignoring message");
2184                         return;
2185                 }
2186                 if (!sm->PTK_valid) {
2187                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2188                                         "received EAPOL-Key msg SMK in "
2189                                         "invalid state - dropped");
2190                         return;
2191                 }
2192                 break;
2193 #else /* CONFIG_PEERKEY */
2194         case SMK_M1:
2195         case SMK_M3:
2196         case SMK_ERROR:
2197                 return; /* STSL disabled - ignore SMK messages */
2198 #endif /* CONFIG_PEERKEY */
2199         case REQUEST:
2200                 break;
2201         }
2202
2203         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_DEBUG,
2204                          "received EAPOL-Key frame (%s)", msgtxt);
2205
2206         if (key_info & WPA_KEY_INFO_ACK) {
2207                 wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2208                                 "received invalid EAPOL-Key: Key Ack set");
2209                 return;
2210         }
2211
2212         if (!(key_info & WPA_KEY_INFO_MIC)) {
2213                 wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2214                                 "received invalid EAPOL-Key: Key MIC not set");
2215                 return;
2216         }
2217
2218         sm->MICVerified = FALSE;
2219         if (sm->PTK_valid) {
2220                 if (wpa_verify_key_mic(&sm->PTK, data, data_len)) {
2221                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2222                                         "received EAPOL-Key with invalid MIC");
2223                         return;
2224                 }
2225                 sm->MICVerified = TRUE;
2226                 eloop_cancel_timeout(wpa_send_eapol_timeout, wpa_auth, sm);
2227         }
2228
2229         if (key_info & WPA_KEY_INFO_REQUEST) {
2230                 if (sm->MICVerified) {
2231                         sm->req_replay_counter_used = 1;
2232                         memcpy(sm->req_replay_counter, key->replay_counter,
2233                                WPA_REPLAY_COUNTER_LEN);
2234                 } else {
2235                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2236                                         "received EAPOL-Key request with "
2237                                         "invalid MIC");
2238                         return;
2239                 }
2240
2241                 /*
2242                  * TODO: should decrypt key data field if encryption was used;
2243                  * even though MAC address KDE is not normally encrypted,
2244                  * supplicant is allowed to encrypt it.
2245                  */
2246                 if (msg == SMK_ERROR) {
2247 #ifdef CONFIG_PEERKEY
2248                         wpa_smk_error(wpa_auth, sm, key);
2249 #endif /* CONFIG_PEERKEY */
2250                         return;
2251                 } else if (key_info & WPA_KEY_INFO_ERROR) {
2252                         /* Supplicant reported a Michael MIC error */
2253                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2254                                         "received EAPOL-Key Error Request "
2255                                         "(STA detected Michael MIC failure)");
2256                         wpa_auth_mic_failure_report(wpa_auth, sm->addr);
2257                         sm->dot11RSNAStatsTKIPRemoteMICFailures++;
2258                         wpa_auth->dot11RSNAStatsTKIPRemoteMICFailures++;
2259                         /* Error report is not a request for a new key
2260                          * handshake, but since Authenticator may do it, let's
2261                          * change the keys now anyway. */
2262                         wpa_request_new_ptk(sm);
2263                 } else if (key_info & WPA_KEY_INFO_KEY_TYPE) {
2264                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2265                                         "received EAPOL-Key Request for new "
2266                                         "4-Way Handshake");
2267                         wpa_request_new_ptk(sm);
2268 #ifdef CONFIG_PEERKEY
2269                 } else if (msg == SMK_M1) {
2270                         wpa_smk_m1(wpa_auth, sm, key);
2271 #endif /* CONFIG_PEERKEY */
2272                 } else if (key_data_length > 0 &&
2273                            wpa_parse_kde_ies((const u8 *) (key + 1),
2274                                              key_data_length, &kde) == 0 &&
2275                            kde.mac_addr) {
2276                 } else {
2277                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
2278                                         "received EAPOL-Key Request for GTK "
2279                                         "rekeying");
2280                         /* FIX: why was this triggering PTK rekeying for the
2281                          * STA that requested Group Key rekeying?? */
2282                         /* wpa_request_new_ptk(sta->wpa_sm); */
2283                         eloop_cancel_timeout(wpa_rekey_gtk, wpa_auth, NULL);
2284                         wpa_rekey_gtk(wpa_auth, NULL);
2285                 }
2286         } else {
2287                 /* Do not allow the same key replay counter to be reused. */
2288                 sm->key_replay_counter_valid = FALSE;
2289         }
2290
2291 #ifdef CONFIG_PEERKEY
2292         if (msg == SMK_M3) {
2293                 wpa_smk_m3(wpa_auth, sm, key);
2294                 return;
2295         }
2296 #endif /* CONFIG_PEERKEY */
2297
2298         free(sm->last_rx_eapol_key);
2299         sm->last_rx_eapol_key = malloc(data_len);
2300         if (sm->last_rx_eapol_key == NULL)
2301                 return;
2302         memcpy(sm->last_rx_eapol_key, data, data_len);
2303         sm->last_rx_eapol_key_len = data_len;
2304
2305         sm->EAPOLKeyReceived = TRUE;
2306         sm->EAPOLKeyPairwise = !!(key_info & WPA_KEY_INFO_KEY_TYPE);
2307         sm->EAPOLKeyRequest = !!(key_info & WPA_KEY_INFO_REQUEST);
2308         memcpy(sm->SNonce, key->key_nonce, WPA_NONCE_LEN);
2309         wpa_sm_step(sm);
2310 }
2311
2312
2313 static void wpa_pmk_to_ptk(const u8 *pmk, const u8 *addr1, const u8 *addr2,
2314                            const u8 *nonce1, const u8 *nonce2,
2315                            u8 *ptk, size_t ptk_len)
2316 {
2317         u8 data[2 * ETH_ALEN + 2 * WPA_NONCE_LEN];
2318
2319         /* PTK = PRF-X(PMK, "Pairwise key expansion",
2320          *             Min(AA, SA) || Max(AA, SA) ||
2321          *             Min(ANonce, SNonce) || Max(ANonce, SNonce)) */
2322
2323         if (memcmp(addr1, addr2, ETH_ALEN) < 0) {
2324                 memcpy(data, addr1, ETH_ALEN);
2325                 memcpy(data + ETH_ALEN, addr2, ETH_ALEN);
2326         } else {
2327                 memcpy(data, addr2, ETH_ALEN);
2328                 memcpy(data + ETH_ALEN, addr1, ETH_ALEN);
2329         }
2330
2331         if (memcmp(nonce1, nonce2, WPA_NONCE_LEN) < 0) {
2332                 memcpy(data + 2 * ETH_ALEN, nonce1, WPA_NONCE_LEN);
2333                 memcpy(data + 2 * ETH_ALEN + WPA_NONCE_LEN, nonce2,
2334                        WPA_NONCE_LEN);
2335         } else {
2336                 memcpy(data + 2 * ETH_ALEN, nonce2, WPA_NONCE_LEN);
2337                 memcpy(data + 2 * ETH_ALEN + WPA_NONCE_LEN, nonce1,
2338                        WPA_NONCE_LEN);
2339         }
2340
2341         sha1_prf(pmk, WPA_PMK_LEN, "Pairwise key expansion",
2342                  data, sizeof(data), ptk, ptk_len);
2343
2344         wpa_hexdump_key(MSG_DEBUG, "PMK", pmk, WPA_PMK_LEN);
2345         wpa_hexdump_key(MSG_DEBUG, "PTK", ptk, ptk_len);
2346 }
2347
2348
2349 static void wpa_gmk_to_gtk(const u8 *gmk, const u8 *addr, const u8 *gnonce,
2350                            u8 *gtk, size_t gtk_len)
2351 {
2352         u8 data[ETH_ALEN + WPA_NONCE_LEN];
2353
2354         /* GTK = PRF-X(GMK, "Group key expansion", AA || GNonce) */
2355         memcpy(data, addr, ETH_ALEN);
2356         memcpy(data + ETH_ALEN, gnonce, WPA_NONCE_LEN);
2357
2358         sha1_prf(gmk, WPA_GMK_LEN, "Group key expansion",
2359                  data, sizeof(data), gtk, gtk_len);
2360
2361         wpa_hexdump_key(MSG_DEBUG, "GMK", gmk, WPA_GMK_LEN);
2362         wpa_hexdump_key(MSG_DEBUG, "GTK", gtk, gtk_len);
2363 }
2364
2365
2366 static void wpa_send_eapol_timeout(void *eloop_ctx, void *timeout_ctx)
2367 {
2368         struct wpa_authenticator *wpa_auth = eloop_ctx;
2369         struct wpa_state_machine *sm = timeout_ctx;
2370
2371         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG, "EAPOL-Key timeout");
2372         sm->TimeoutEvt = TRUE;
2373         wpa_sm_step(sm);
2374 }
2375
2376
2377 static int wpa_calc_eapol_key_mic(int ver, u8 *key, u8 *data, size_t len,
2378                                   u8 *mic)
2379 {
2380         u8 hash[SHA1_MAC_LEN];
2381
2382         switch (ver) {
2383         case WPA_KEY_INFO_TYPE_HMAC_MD5_RC4:
2384                 hmac_md5(key, 16, data, len, mic);
2385                 break;
2386         case WPA_KEY_INFO_TYPE_HMAC_SHA1_AES:
2387                 hmac_sha1(key, 16, data, len, hash);
2388                 memcpy(mic, hash, MD5_MAC_LEN);
2389                 break;
2390         default:
2391                 return -1;
2392         }
2393         return 0;
2394 }
2395
2396
2397 static void __wpa_send_eapol(struct wpa_authenticator *wpa_auth,
2398                              struct wpa_state_machine *sm, int key_info,
2399                              const u8 *key_rsc, const u8 *nonce,
2400                              const u8 *kde, size_t kde_len,
2401                              int keyidx, int encr, int force_version)
2402 {
2403         struct ieee802_1x_hdr *hdr;
2404         struct wpa_eapol_key *key;
2405         size_t len;
2406         int alg;
2407         int key_data_len, pad_len = 0;
2408         u8 *buf, *pos;
2409         int version, pairwise;
2410
2411         len = sizeof(struct ieee802_1x_hdr) + sizeof(struct wpa_eapol_key);
2412
2413         if (force_version)
2414                 version = force_version;
2415         else if (sm->pairwise == WPA_CIPHER_CCMP)
2416                 version = WPA_KEY_INFO_TYPE_HMAC_SHA1_AES;
2417         else
2418                 version = WPA_KEY_INFO_TYPE_HMAC_MD5_RC4;
2419
2420         pairwise = key_info & WPA_KEY_INFO_KEY_TYPE;
2421
2422         wpa_printf(MSG_DEBUG, "WPA: Send EAPOL(secure=%d mic=%d ack=%d "
2423                    "install=%d pairwise=%d kde_len=%lu keyidx=%d encr=%d)",
2424                    (key_info & WPA_KEY_INFO_SECURE) ? 1 : 0,
2425                    (key_info & WPA_KEY_INFO_MIC) ? 1 : 0,
2426                    (key_info & WPA_KEY_INFO_ACK) ? 1 : 0,
2427                    (key_info & WPA_KEY_INFO_INSTALL) ? 1 : 0,
2428                    pairwise, (unsigned long) kde_len, keyidx, encr);
2429
2430         key_data_len = kde_len;
2431
2432         if (version == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES && encr) {
2433                 pad_len = key_data_len % 8;
2434                 if (pad_len)
2435                         pad_len = 8 - pad_len;
2436                 key_data_len += pad_len + 8;
2437         }
2438
2439         len += key_data_len;
2440
2441         hdr = wpa_zalloc(len);
2442         if (hdr == NULL)
2443                 return;
2444         hdr->version = wpa_auth->conf.eapol_version;
2445         hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
2446         hdr->length = htons(len  - sizeof(*hdr));
2447         key = (struct wpa_eapol_key *) (hdr + 1);
2448
2449         key->type = sm->wpa == WPA_VERSION_WPA2 ?
2450                 EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
2451         key_info |= version;
2452         if (encr && sm->wpa == WPA_VERSION_WPA2)
2453                 key_info |= WPA_KEY_INFO_ENCR_KEY_DATA;
2454         if (sm->wpa != WPA_VERSION_WPA2)
2455                 key_info |= keyidx << WPA_KEY_INFO_KEY_INDEX_SHIFT;
2456         key->key_info = htons(key_info);
2457
2458         alg = pairwise ? sm->pairwise : wpa_auth->conf.wpa_group;
2459         switch (alg) {
2460         case WPA_CIPHER_CCMP:
2461                 key->key_length = htons(16);
2462                 break;
2463         case WPA_CIPHER_TKIP:
2464                 key->key_length = htons(32);
2465                 break;
2466         case WPA_CIPHER_WEP40:
2467                 key->key_length = htons(5);
2468                 break;
2469         case WPA_CIPHER_WEP104:
2470                 key->key_length = htons(13);
2471                 break;
2472         }
2473         if (key_info & WPA_KEY_INFO_SMK_MESSAGE)
2474                 key->key_length = htons(0);
2475
2476         /* FIX: STSL: what to use as key_replay_counter? */
2477         inc_byte_array(sm->key_replay_counter, WPA_REPLAY_COUNTER_LEN);
2478         memcpy(key->replay_counter, sm->key_replay_counter,
2479                WPA_REPLAY_COUNTER_LEN);
2480         sm->key_replay_counter_valid = TRUE;
2481
2482         if (nonce)
2483                 memcpy(key->key_nonce, nonce, WPA_NONCE_LEN);
2484
2485         if (key_rsc)
2486                 memcpy(key->key_rsc, key_rsc, WPA_KEY_RSC_LEN);
2487
2488         if (kde && !encr) {
2489                 memcpy(key + 1, kde, kde_len);
2490                 key->key_data_length = htons(kde_len);
2491         } else if (encr && kde) {
2492                 buf = wpa_zalloc(key_data_len);
2493                 if (buf == NULL) {
2494                         free(hdr);
2495                         return;
2496                 }
2497                 pos = buf;
2498                 memcpy(pos, kde, kde_len);
2499                 pos += kde_len;
2500
2501                 if (pad_len)
2502                         *pos++ = 0xdd;
2503
2504                 wpa_hexdump_key(MSG_DEBUG, "Plaintext EAPOL-Key Key Data",
2505                                 buf, key_data_len);
2506                 if (version == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
2507                         aes_wrap(sm->PTK.encr_key, (key_data_len - 8) / 8, buf,
2508                                  (u8 *) (key + 1));
2509                         key->key_data_length = htons(key_data_len);
2510                 } else {
2511                         u8 ek[32];
2512                         memcpy(key->key_iv,
2513                                sm->group->Counter + WPA_NONCE_LEN - 16, 16);
2514                         inc_byte_array(sm->group->Counter, WPA_NONCE_LEN);
2515                         memcpy(ek, key->key_iv, 16);
2516                         memcpy(ek + 16, sm->PTK.encr_key, 16);
2517                         memcpy(key + 1, buf, key_data_len);
2518                         rc4_skip(ek, 32, 256, (u8 *) (key + 1), key_data_len);
2519                         key->key_data_length = htons(key_data_len);
2520                 }
2521                 free(buf);
2522         }
2523
2524         if (key_info & WPA_KEY_INFO_MIC) {
2525                 if (!sm->PTK_valid) {
2526                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG,
2527                                         "PTK not valid when sending EAPOL-Key "
2528                                         "frame");
2529                         free(hdr);
2530                         return;
2531                 }
2532                 wpa_calc_eapol_key_mic(version,
2533                                        sm->PTK.mic_key, (u8 *) hdr, len,
2534                                        key->key_mic);
2535         }
2536
2537         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_inc_EapolFramesTx,
2538                            1);
2539         wpa_auth_send_eapol(wpa_auth, sm->addr, (u8 *) hdr, len,
2540                             sm->pairwise_set);
2541         free(hdr);
2542 }
2543
2544
2545 static void wpa_send_eapol(struct wpa_authenticator *wpa_auth,
2546                            struct wpa_state_machine *sm, int key_info,
2547                            const u8 *key_rsc, const u8 *nonce,
2548                            const u8 *kde, size_t kde_len,
2549                            int keyidx, int encr)
2550 {
2551         int timeout_ms;
2552         int pairwise = key_info & WPA_KEY_INFO_KEY_TYPE;
2553
2554         if (sm == NULL)
2555                 return;
2556
2557         __wpa_send_eapol(wpa_auth, sm, key_info, key_rsc, nonce, kde, kde_len,
2558                          keyidx, encr, 0);
2559
2560         timeout_ms = pairwise ? dot11RSNAConfigPairwiseUpdateTimeOut :
2561                 dot11RSNAConfigGroupUpdateTimeOut;
2562         eloop_register_timeout(timeout_ms / 1000, (timeout_ms % 1000) * 1000,
2563                                wpa_send_eapol_timeout, wpa_auth, sm);
2564 }
2565
2566
2567 static int wpa_verify_key_mic(struct wpa_ptk *PTK, u8 *data, size_t data_len)
2568 {
2569         struct ieee802_1x_hdr *hdr;
2570         struct wpa_eapol_key *key;
2571         u16 key_info;
2572         int ret = 0;
2573         u8 mic[16];
2574
2575         if (data_len < sizeof(*hdr) + sizeof(*key))
2576                 return -1;
2577
2578         hdr = (struct ieee802_1x_hdr *) data;
2579         key = (struct wpa_eapol_key *) (hdr + 1);
2580         key_info = ntohs(key->key_info);
2581         memcpy(mic, key->key_mic, 16);
2582         memset(key->key_mic, 0, 16);
2583         if (wpa_calc_eapol_key_mic(key_info & WPA_KEY_INFO_TYPE_MASK,
2584                                    PTK->mic_key, data, data_len, key->key_mic)
2585             || memcmp(mic, key->key_mic, 16) != 0)
2586                 ret = -1;
2587         memcpy(key->key_mic, mic, 16);
2588         return ret;
2589 }
2590
2591
2592 void wpa_remove_ptk(struct wpa_state_machine *sm)
2593 {
2594         sm->PTK_valid = FALSE;
2595         memset(&sm->PTK, 0, sizeof(sm->PTK));
2596         wpa_auth_set_key(sm->wpa_auth, 0, "none", sm->addr, 0, (u8 *) "", 0);
2597         sm->pairwise_set = FALSE;
2598 }
2599
2600
2601 void wpa_auth_sm_event(struct wpa_state_machine *sm, wpa_event event)
2602 {
2603         if (sm == NULL)
2604                 return;
2605
2606         wpa_auth_vlogger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2607                          "event %d notification", event);
2608
2609         switch (event) {
2610         case WPA_AUTH:
2611         case WPA_ASSOC:
2612                 break;
2613         case WPA_DEAUTH:
2614         case WPA_DISASSOC:
2615                 sm->DeauthenticationRequest = TRUE;
2616                 break;
2617         case WPA_REAUTH:
2618         case WPA_REAUTH_EAPOL:
2619                 sm->ReAuthenticationRequest = TRUE;
2620                 break;
2621         }
2622
2623         sm->PTK_valid = FALSE;
2624         memset(&sm->PTK, 0, sizeof(sm->PTK));
2625
2626         if (event != WPA_REAUTH_EAPOL)
2627                 wpa_remove_ptk(sm);
2628
2629         wpa_sm_step(sm);
2630 }
2631
2632
2633 static const char * wpa_alg_txt(int alg)
2634 {
2635         switch (alg) {
2636         case WPA_CIPHER_CCMP:
2637                 return "CCMP";
2638         case WPA_CIPHER_TKIP:
2639                 return "TKIP";
2640         case WPA_CIPHER_WEP104:
2641         case WPA_CIPHER_WEP40:
2642                 return "WEP";
2643         default:
2644                 return "";
2645         }
2646 }
2647
2648
2649 SM_STATE(WPA_PTK, INITIALIZE)
2650 {
2651         SM_ENTRY_MA(WPA_PTK, INITIALIZE, wpa_ptk);
2652         if (sm->Init) {
2653                 /* Init flag is not cleared here, so avoid busy
2654                  * loop by claiming nothing changed. */
2655                 sm->changed = FALSE;
2656         }
2657
2658         sm->keycount = 0;
2659         if (sm->GUpdateStationKeys)
2660                 sm->group->GKeyDoneStations--;
2661         sm->GUpdateStationKeys = FALSE;
2662         if (sm->wpa == WPA_VERSION_WPA)
2663                 sm->PInitAKeys = FALSE;
2664         if (1 /* Unicast cipher supported AND (ESS OR ((IBSS or WDS) and
2665                * Local AA > Remote AA)) */) {
2666                 sm->Pair = TRUE;
2667         }
2668         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portEnabled, 0);
2669         wpa_remove_ptk(sm);
2670         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portValid, 0);
2671         sm->TimeoutCtr = 0;
2672         if (sm->wpa_key_mgmt == WPA_KEY_MGMT_PSK) {
2673                 wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
2674                                    WPA_EAPOL_authorized, 0);
2675         }
2676 }
2677
2678
2679 SM_STATE(WPA_PTK, DISCONNECT)
2680 {
2681         SM_ENTRY_MA(WPA_PTK, DISCONNECT, wpa_ptk);
2682         sm->Disconnect = FALSE;
2683         wpa_sta_disconnect(sm->wpa_auth, sm->addr);
2684 }
2685
2686
2687 SM_STATE(WPA_PTK, DISCONNECTED)
2688 {
2689         SM_ENTRY_MA(WPA_PTK, DISCONNECTED, wpa_ptk);
2690         if (sm->sta_counted) {
2691                 sm->group->GNoStations--;
2692                 sm->sta_counted = 0;
2693         } else {
2694                 wpa_printf(MSG_DEBUG, "WPA: WPA_PTK::DISCONNECTED - did not "
2695                            "decrease GNoStations (STA " MACSTR ")",
2696                            MAC2STR(sm->addr));
2697         }
2698         sm->DeauthenticationRequest = FALSE;
2699 }
2700
2701
2702 SM_STATE(WPA_PTK, AUTHENTICATION)
2703 {
2704         SM_ENTRY_MA(WPA_PTK, AUTHENTICATION, wpa_ptk);
2705         if (!sm->sta_counted) {
2706                 sm->group->GNoStations++;
2707                 sm->sta_counted = 1;
2708         } else {
2709                 wpa_printf(MSG_DEBUG, "WPA: WPA_PTK::DISCONNECTED - did not "
2710                            "increase GNoStations (STA " MACSTR ")",
2711                            MAC2STR(sm->addr));
2712         }
2713         memset(&sm->PTK, 0, sizeof(sm->PTK));
2714         sm->PTK_valid = FALSE;
2715         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portControl_Auto,
2716                            1);
2717         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portEnabled, 1);
2718         sm->AuthenticationRequest = FALSE;
2719 }
2720
2721
2722 SM_STATE(WPA_PTK, AUTHENTICATION2)
2723 {
2724         SM_ENTRY_MA(WPA_PTK, AUTHENTICATION2, wpa_ptk);
2725         memcpy(sm->ANonce, sm->group->Counter, WPA_NONCE_LEN);
2726         inc_byte_array(sm->group->Counter, WPA_NONCE_LEN);
2727         sm->ReAuthenticationRequest = FALSE;
2728         /* IEEE 802.11i does not clear TimeoutCtr here, but this is more
2729          * logical place than INITIALIZE since AUTHENTICATION2 can be
2730          * re-entered on ReAuthenticationRequest without going through
2731          * INITIALIZE. */
2732         sm->TimeoutCtr = 0;
2733 }
2734
2735
2736 SM_STATE(WPA_PTK, INITPMK)
2737 {
2738         size_t len = WPA_PMK_LEN;
2739
2740         SM_ENTRY_MA(WPA_PTK, INITPMK, wpa_ptk);
2741         if (sm->pmksa) {
2742                 wpa_printf(MSG_DEBUG, "WPA: PMK from PMKSA cache");
2743                 memcpy(sm->PMK, sm->pmksa->pmk, WPA_PMK_LEN);
2744         } else if (wpa_auth_get_pmk(sm->wpa_auth, sm->addr, sm->PMK, &len) ==
2745                    0) {
2746                 wpa_printf(MSG_DEBUG, "WPA: PMK from EAPOL state machine "
2747                            "(len=%lu)", (unsigned long) len);
2748         } else {
2749                 wpa_printf(MSG_DEBUG, "WPA: Could not get PMK");
2750         }
2751
2752         sm->req_replay_counter_used = 0;
2753         /* IEEE 802.11i does not set keyRun to FALSE, but not doing this
2754          * will break reauthentication since EAPOL state machines may not be
2755          * get into AUTHENTICATING state that clears keyRun before WPA state
2756          * machine enters AUTHENTICATION2 state and goes immediately to INITPMK
2757          * state and takes PMK from the previously used AAA Key. This will
2758          * eventually fail in 4-Way Handshake because Supplicant uses PMK
2759          * derived from the new AAA Key. Setting keyRun = FALSE here seems to
2760          * be good workaround for this issue. */
2761         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyRun, 0);
2762 }
2763
2764
2765 SM_STATE(WPA_PTK, INITPSK)
2766 {
2767         const u8 *psk;
2768         SM_ENTRY_MA(WPA_PTK, INITPSK, wpa_ptk);
2769         psk = wpa_auth_get_psk(sm->wpa_auth, sm->addr, NULL);
2770         if (psk)
2771                 memcpy(sm->PMK, psk, WPA_PMK_LEN);
2772         sm->req_replay_counter_used = 0;
2773 }
2774
2775
2776 SM_STATE(WPA_PTK, PTKSTART)
2777 {
2778         u8 buf[2 + RSN_SELECTOR_LEN + PMKID_LEN], *pmkid = NULL;
2779         size_t pmkid_len = 0;
2780
2781         SM_ENTRY_MA(WPA_PTK, PTKSTART, wpa_ptk);
2782         sm->PTKRequest = FALSE;
2783         sm->TimeoutEvt = FALSE;
2784         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2785                         "sending 1/4 msg of 4-Way Handshake");
2786         /*
2787          * TODO: Could add PMKID even with WPA2-PSK, but only if there is only
2788          * one possible PSK for this STA.
2789          */
2790         if (sm->wpa == WPA_VERSION_WPA2 &&
2791             sm->wpa_key_mgmt != WPA_KEY_MGMT_PSK) {
2792                 pmkid = buf;
2793                 pmkid_len = 2 + RSN_SELECTOR_LEN + PMKID_LEN;
2794                 pmkid[0] = WLAN_EID_GENERIC;
2795                 pmkid[1] = RSN_SELECTOR_LEN + PMKID_LEN;
2796                 memcpy(&pmkid[2], RSN_KEY_DATA_PMKID, RSN_SELECTOR_LEN);
2797                 if (sm->pmksa)
2798                         memcpy(&pmkid[2 + RSN_SELECTOR_LEN], sm->pmksa->pmkid,
2799                                PMKID_LEN);
2800                 else {
2801                         /*
2802                          * Calculate PMKID since no PMKSA cache entry was
2803                          * available with pre-calculated PMKID.
2804                          */
2805                         rsn_pmkid(sm->PMK, WPA_PMK_LEN, sm->wpa_auth->addr,
2806                                   sm->addr, &pmkid[2 + RSN_SELECTOR_LEN]);
2807                 }
2808         }
2809         wpa_send_eapol(sm->wpa_auth, sm,
2810                        WPA_KEY_INFO_ACK | WPA_KEY_INFO_KEY_TYPE, NULL,
2811                        sm->ANonce, pmkid, pmkid_len, 0, 0);
2812         sm->TimeoutCtr++;
2813 }
2814
2815
2816 SM_STATE(WPA_PTK, PTKCALCNEGOTIATING)
2817 {
2818         struct wpa_ptk PTK;
2819         int ok = 0;
2820         const u8 *pmk = NULL;
2821
2822         SM_ENTRY_MA(WPA_PTK, PTKCALCNEGOTIATING, wpa_ptk);
2823         sm->EAPOLKeyReceived = FALSE;
2824
2825         /* WPA with IEEE 802.1X: use the derived PMK from EAP
2826          * WPA-PSK: iterate through possible PSKs and select the one matching
2827          * the packet */
2828         for (;;) {
2829                 if (sm->wpa_key_mgmt == WPA_KEY_MGMT_PSK) {
2830                         pmk = wpa_auth_get_psk(sm->wpa_auth, sm->addr, pmk);
2831                         if (pmk == NULL)
2832                                 break;
2833                 } else
2834                         pmk = sm->PMK;
2835
2836                 wpa_pmk_to_ptk(pmk, sm->wpa_auth->addr, sm->addr,
2837                                sm->ANonce, sm->SNonce,
2838                                (u8 *) &PTK, sizeof(PTK));
2839
2840                 if (wpa_verify_key_mic(&PTK, sm->last_rx_eapol_key,
2841                                        sm->last_rx_eapol_key_len) == 0) {
2842                         ok = 1;
2843                         break;
2844                 }
2845
2846                 if (sm->wpa_key_mgmt != WPA_KEY_MGMT_PSK)
2847                         break;
2848         }
2849
2850         if (!ok) {
2851                 wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2852                                 "invalid MIC in msg 2/4 of 4-Way Handshake");
2853                 return;
2854         }
2855
2856         eloop_cancel_timeout(wpa_send_eapol_timeout, sm->wpa_auth, sm);
2857
2858         if (sm->wpa_key_mgmt == WPA_KEY_MGMT_PSK) {
2859                 /* PSK may have changed from the previous choice, so update
2860                  * state machine data based on whatever PSK was selected here.
2861                  */
2862                 memcpy(sm->PMK, pmk, WPA_PMK_LEN);
2863         }
2864
2865         sm->MICVerified = TRUE;
2866
2867         memcpy(&sm->PTK, &PTK, sizeof(PTK));
2868         sm->PTK_valid = TRUE;
2869 }
2870
2871
2872 SM_STATE(WPA_PTK, PTKCALCNEGOTIATING2)
2873 {
2874         SM_ENTRY_MA(WPA_PTK, PTKCALCNEGOTIATING2, wpa_ptk);
2875         sm->TimeoutCtr = 0;
2876 }
2877
2878
2879 #ifdef CONFIG_IEEE80211W
2880
2881 static int ieee80211w_kde_len(struct wpa_state_machine *sm)
2882 {
2883         if (sm->mgmt_frame_prot) {
2884                 return 2 + RSN_SELECTOR_LEN + sizeof(struct wpa_dhv_kde) +
2885                         2 + RSN_SELECTOR_LEN + sizeof(struct wpa_igtk_kde);
2886         }
2887
2888         return 0;
2889 }
2890
2891
2892 static u8 * ieee80211w_kde_add(struct wpa_state_machine *sm, u8 *pos)
2893 {
2894         struct wpa_dhv_kde dhv;
2895         struct wpa_igtk_kde igtk;
2896         struct wpa_group *gsm = sm->group;
2897         u8 mac[32];
2898         const u8 *addr[3];
2899         size_t len[3];
2900
2901         if (!sm->mgmt_frame_prot)
2902                 return pos;
2903
2904         addr[0] = sm->wpa_auth->addr;
2905         len[0] = ETH_ALEN;
2906         addr[1] = sm->addr;
2907         len[1] = ETH_ALEN;
2908         addr[2] = gsm->DGTK;
2909         len[2] = WPA_DGTK_LEN;
2910         sha256_vector(3, addr, len, mac);
2911         memcpy(dhv.dhv, mac, WPA_DHV_LEN);
2912         wpa_hexdump_key(MSG_DEBUG, "WPA: DHV", dhv.dhv, WPA_DHV_LEN);
2913         pos = wpa_add_kde(pos, RSN_KEY_DATA_DHV,
2914                           (const u8 *) &dhv, sizeof(dhv), NULL, 0);
2915
2916         igtk.keyid[0] = gsm->GN;
2917         igtk.keyid[1] = 0;
2918         if (wpa_auth_get_seqnum_igtk(sm->wpa_auth, NULL, gsm->GN, igtk.pn) < 0)
2919                 memset(igtk.pn, 0, sizeof(igtk.pn));
2920         memcpy(igtk.igtk, gsm->IGTK[gsm->GN - 1], WPA_IGTK_LEN);
2921         pos = wpa_add_kde(pos, RSN_KEY_DATA_IGTK,
2922                           (const u8 *) &igtk, sizeof(igtk), NULL, 0);
2923
2924         return pos;
2925 }
2926
2927 #else /* CONFIG_IEEE80211W */
2928
2929 static int ieee80211w_kde_len(struct wpa_state_machine *sm)
2930 {
2931         return 0;
2932 }
2933
2934
2935 static u8 * ieee80211w_kde_add(struct wpa_state_machine *sm, u8 *pos)
2936 {
2937         return pos;
2938 }
2939
2940 #endif /* CONFIG_IEEE80211W */
2941
2942
2943 SM_STATE(WPA_PTK, PTKINITNEGOTIATING)
2944 {
2945         u8 rsc[WPA_KEY_RSC_LEN], *_rsc, *gtk, *kde, *pos;
2946         size_t gtk_len, kde_len;
2947         struct wpa_group *gsm = sm->group;
2948         u8 *wpa_ie;
2949         int wpa_ie_len, secure, keyidx, encr = 0;
2950
2951         SM_ENTRY_MA(WPA_PTK, PTKINITNEGOTIATING, wpa_ptk);
2952         sm->TimeoutEvt = FALSE;
2953         /* Send EAPOL(1, 1, 1, Pair, P, RSC, ANonce, MIC(PTK), RSNIE, GTK[GN])
2954          */
2955         memset(rsc, 0, WPA_KEY_RSC_LEN);
2956         wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN, rsc);
2957         wpa_ie = sm->wpa_auth->wpa_ie;
2958         wpa_ie_len = sm->wpa_auth->wpa_ie_len;
2959         if (sm->wpa == WPA_VERSION_WPA &&
2960             (sm->wpa_auth->conf.wpa & HOSTAPD_WPA_VERSION_WPA2) &&
2961             wpa_ie_len > wpa_ie[1] + 2 && wpa_ie[0] == WLAN_EID_RSN) {
2962                 /* WPA-only STA, remove RSN IE */
2963                 wpa_ie = wpa_ie + wpa_ie[1] + 2;
2964                 wpa_ie_len = wpa_ie[1] + 2;
2965         }
2966         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2967                         "sending 3/4 msg of 4-Way Handshake");
2968         if (sm->wpa == WPA_VERSION_WPA2) {
2969                 /* WPA2 send GTK in the 4-way handshake */
2970                 secure = 1;
2971                 gtk = gsm->GTK[gsm->GN - 1];
2972                 gtk_len = gsm->GTK_len;
2973                 keyidx = gsm->GN;
2974                 _rsc = rsc;
2975                 encr = 1;
2976         } else {
2977                 /* WPA does not include GTK in msg 3/4 */
2978                 secure = 0;
2979                 gtk = NULL;
2980                 gtk_len = 0;
2981                 keyidx = 0;
2982                 _rsc = NULL;
2983         }
2984
2985         kde_len = wpa_ie_len + ieee80211w_kde_len(sm);
2986         if (gtk)
2987                 kde_len += 2 + RSN_SELECTOR_LEN + 2 + gtk_len;
2988         kde = malloc(kde_len);
2989         if (kde == NULL)
2990                 return;
2991
2992         pos = kde;
2993         memcpy(pos, wpa_ie, wpa_ie_len);
2994         pos += wpa_ie_len;
2995         if (gtk) {
2996                 u8 hdr[2];
2997                 hdr[0] = keyidx & 0x03;
2998                 hdr[1] = 0;
2999                 pos = wpa_add_kde(pos, RSN_KEY_DATA_GROUPKEY, hdr, 2,
3000                                   gtk, gtk_len);
3001         }
3002         pos = ieee80211w_kde_add(sm, pos);
3003
3004         wpa_send_eapol(sm->wpa_auth, sm,
3005                        (secure ? WPA_KEY_INFO_SECURE : 0) | WPA_KEY_INFO_MIC |
3006                        WPA_KEY_INFO_ACK | WPA_KEY_INFO_INSTALL |
3007                        WPA_KEY_INFO_KEY_TYPE,
3008                        _rsc, sm->ANonce, kde, pos - kde, keyidx, encr);
3009         free(kde);
3010         sm->TimeoutCtr++;
3011 }
3012
3013
3014 SM_STATE(WPA_PTK, PTKINITDONE)
3015 {
3016         SM_ENTRY_MA(WPA_PTK, PTKINITDONE, wpa_ptk);
3017         sm->EAPOLKeyReceived = FALSE;
3018         if (sm->Pair) {
3019                 char *alg;
3020                 int klen;
3021                 if (sm->pairwise == WPA_CIPHER_TKIP) {
3022                         alg = "TKIP";
3023                         klen = 32;
3024                 } else {
3025                         alg = "CCMP";
3026                         klen = 16;
3027                 }
3028                 if (wpa_auth_set_key(sm->wpa_auth, 0, alg, sm->addr, 0,
3029                                      sm->PTK.tk1, klen)) {
3030                         wpa_sta_disconnect(sm->wpa_auth, sm->addr);
3031                         return;
3032                 }
3033                 /* FIX: MLME-SetProtection.Request(TA, Tx_Rx) */
3034                 sm->pairwise_set = TRUE;
3035
3036                 if (sm->wpa_key_mgmt == WPA_KEY_MGMT_PSK) {
3037                         wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
3038                                            WPA_EAPOL_authorized, 1);
3039                 }
3040         }
3041
3042         if (0 /* IBSS == TRUE */) {
3043                 sm->keycount++;
3044                 if (sm->keycount == 2) {
3045                         wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
3046                                            WPA_EAPOL_portValid, 1);
3047                 }
3048         } else {
3049                 wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portValid,
3050                                    1);
3051         }
3052         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyAvailable, 0);
3053         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyDone, 1);
3054         if (sm->wpa == WPA_VERSION_WPA)
3055                 sm->PInitAKeys = TRUE;
3056         else
3057                 sm->has_GTK = TRUE;
3058         wpa_auth_vlogger(sm->wpa_auth, sm->addr, LOGGER_INFO,
3059                          "pairwise key handshake completed (%s)",
3060                          sm->wpa == WPA_VERSION_WPA ? "WPA" : "RSN");
3061 }
3062
3063
3064 SM_STEP(WPA_PTK)
3065 {
3066         struct wpa_authenticator *wpa_auth = sm->wpa_auth;
3067
3068         if (sm->Init)
3069                 SM_ENTER(WPA_PTK, INITIALIZE);
3070         else if (sm->Disconnect
3071                  /* || FIX: dot11RSNAConfigSALifetime timeout */)
3072                 SM_ENTER(WPA_PTK, DISCONNECT);
3073         else if (sm->DeauthenticationRequest)
3074                 SM_ENTER(WPA_PTK, DISCONNECTED);
3075         else if (sm->AuthenticationRequest)
3076                 SM_ENTER(WPA_PTK, AUTHENTICATION);
3077         else if (sm->ReAuthenticationRequest)
3078                 SM_ENTER(WPA_PTK, AUTHENTICATION2);
3079         else if (sm->PTKRequest)
3080                 SM_ENTER(WPA_PTK, PTKSTART);
3081         else switch (sm->wpa_ptk_state) {
3082         case WPA_PTK_INITIALIZE:
3083                 break;
3084         case WPA_PTK_DISCONNECT:
3085                 SM_ENTER(WPA_PTK, DISCONNECTED);
3086                 break;
3087         case WPA_PTK_DISCONNECTED:
3088                 SM_ENTER(WPA_PTK, INITIALIZE);
3089                 break;
3090         case WPA_PTK_AUTHENTICATION:
3091                 SM_ENTER(WPA_PTK, AUTHENTICATION2);
3092                 break;
3093         case WPA_PTK_AUTHENTICATION2:
3094                 if ((sm->wpa_key_mgmt == WPA_KEY_MGMT_IEEE8021X) &&
3095                     wpa_auth_get_eapol(sm->wpa_auth, sm->addr,
3096                                        WPA_EAPOL_keyRun) > 0)
3097                         SM_ENTER(WPA_PTK, INITPMK);
3098                 else if ((sm->wpa_key_mgmt == WPA_KEY_MGMT_PSK)
3099                          /* FIX: && 802.1X::keyRun */)
3100                         SM_ENTER(WPA_PTK, INITPSK);
3101                 break;
3102         case WPA_PTK_INITPMK:
3103                 if (wpa_auth_get_eapol(sm->wpa_auth, sm->addr,
3104                                        WPA_EAPOL_keyAvailable) > 0)
3105                         SM_ENTER(WPA_PTK, PTKSTART);
3106                 else {
3107                         wpa_auth->dot11RSNA4WayHandshakeFailures++;
3108                         SM_ENTER(WPA_PTK, DISCONNECT);
3109                 }
3110                 break;
3111         case WPA_PTK_INITPSK:
3112                 if (wpa_auth_get_psk(sm->wpa_auth, sm->addr, NULL))
3113                         SM_ENTER(WPA_PTK, PTKSTART);
3114                 else {
3115                         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_INFO,
3116                                         "no PSK configured for the STA");
3117                         wpa_auth->dot11RSNA4WayHandshakeFailures++;
3118                         SM_ENTER(WPA_PTK, DISCONNECT);
3119                 }
3120                 break;
3121         case WPA_PTK_PTKSTART:
3122                 if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
3123                     sm->EAPOLKeyPairwise)
3124                         SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING);
3125                 else if (sm->TimeoutCtr >
3126                          (int) dot11RSNAConfigPairwiseUpdateCount) {
3127                         wpa_auth->dot11RSNA4WayHandshakeFailures++;
3128                         SM_ENTER(WPA_PTK, DISCONNECT);
3129                 } else if (sm->TimeoutEvt)
3130                         SM_ENTER(WPA_PTK, PTKSTART);
3131                 break;
3132         case WPA_PTK_PTKCALCNEGOTIATING:
3133                 if (sm->MICVerified)
3134                         SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING2);
3135                 else if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
3136                          sm->EAPOLKeyPairwise)
3137                         SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING);
3138                 else if (sm->TimeoutEvt)
3139                         SM_ENTER(WPA_PTK, PTKSTART);
3140                 break;
3141         case WPA_PTK_PTKCALCNEGOTIATING2:
3142                 SM_ENTER(WPA_PTK, PTKINITNEGOTIATING);
3143                 break;
3144         case WPA_PTK_PTKINITNEGOTIATING:
3145                 if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
3146                     sm->EAPOLKeyPairwise && sm->MICVerified)
3147                         SM_ENTER(WPA_PTK, PTKINITDONE);
3148                 else if (sm->TimeoutCtr >
3149                          (int) dot11RSNAConfigPairwiseUpdateCount) {
3150                         wpa_auth->dot11RSNA4WayHandshakeFailures++;
3151                         SM_ENTER(WPA_PTK, DISCONNECT);
3152                 } else if (sm->TimeoutEvt)
3153                         SM_ENTER(WPA_PTK, PTKINITNEGOTIATING);
3154                 break;
3155         case WPA_PTK_PTKINITDONE:
3156                 break;
3157         }
3158 }
3159
3160
3161 SM_STATE(WPA_PTK_GROUP, IDLE)
3162 {
3163         SM_ENTRY_MA(WPA_PTK_GROUP, IDLE, wpa_ptk_group);
3164         if (sm->Init) {
3165                 /* Init flag is not cleared here, so avoid busy
3166                  * loop by claiming nothing changed. */
3167                 sm->changed = FALSE;
3168         }
3169         sm->GTimeoutCtr = 0;
3170 }
3171
3172
3173 SM_STATE(WPA_PTK_GROUP, REKEYNEGOTIATING)
3174 {
3175         u8 rsc[WPA_KEY_RSC_LEN];
3176         struct wpa_group *gsm = sm->group;
3177         u8 *kde, *pos, hdr[2];
3178         size_t kde_len;
3179
3180         SM_ENTRY_MA(WPA_PTK_GROUP, REKEYNEGOTIATING, wpa_ptk_group);
3181         if (sm->wpa == WPA_VERSION_WPA)
3182                 sm->PInitAKeys = FALSE;
3183         sm->TimeoutEvt = FALSE;
3184         /* Send EAPOL(1, 1, 1, !Pair, G, RSC, GNonce, MIC(PTK), GTK[GN]) */
3185         memset(rsc, 0, WPA_KEY_RSC_LEN);
3186         if (gsm->wpa_group_state == WPA_GROUP_SETKEYSDONE)
3187                 wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN, rsc);
3188         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
3189                         "sending 1/2 msg of Group Key Handshake");
3190
3191         if (sm->wpa == WPA_VERSION_WPA2) {
3192                 kde_len = 2 + RSN_SELECTOR_LEN + 2 + gsm->GTK_len +
3193                         ieee80211w_kde_len(sm);
3194                 kde = malloc(kde_len);
3195                 if (kde == NULL)
3196                         return;
3197
3198                 pos = kde;
3199                 hdr[0] = gsm->GN & 0x03;
3200                 hdr[1] = 0;
3201                 pos = wpa_add_kde(pos, RSN_KEY_DATA_GROUPKEY, hdr, 2,
3202                                   gsm->GTK[gsm->GN - 1], gsm->GTK_len);
3203                 pos = ieee80211w_kde_add(sm, pos);
3204         } else {
3205                 kde = gsm->GTK[gsm->GN - 1];
3206                 pos = kde + gsm->GTK_len;
3207         }
3208
3209         wpa_send_eapol(sm->wpa_auth, sm,
3210                        WPA_KEY_INFO_SECURE | WPA_KEY_INFO_MIC |
3211                        WPA_KEY_INFO_ACK |
3212                        (!sm->Pair ? WPA_KEY_INFO_INSTALL : 0),
3213                        rsc, gsm->GNonce, kde, pos - kde, gsm->GN, 1);
3214         if (sm->wpa == WPA_VERSION_WPA2)
3215                 free(kde);
3216         sm->GTimeoutCtr++;
3217 }
3218
3219
3220 SM_STATE(WPA_PTK_GROUP, REKEYESTABLISHED)
3221 {
3222         SM_ENTRY_MA(WPA_PTK_GROUP, REKEYESTABLISHED, wpa_ptk_group);
3223         sm->EAPOLKeyReceived = FALSE;
3224         sm->GUpdateStationKeys = FALSE;
3225         sm->group->GKeyDoneStations--;
3226         sm->GTimeoutCtr = 0;
3227         /* FIX: MLME.SetProtection.Request(TA, Tx_Rx) */
3228         wpa_auth_vlogger(sm->wpa_auth, sm->addr, LOGGER_INFO,
3229                          "group key handshake completed (%s)",
3230                          sm->wpa == WPA_VERSION_WPA ? "WPA" : "RSN");
3231         sm->has_GTK = TRUE;
3232 }
3233
3234
3235 SM_STATE(WPA_PTK_GROUP, KEYERROR)
3236 {
3237         SM_ENTRY_MA(WPA_PTK_GROUP, KEYERROR, wpa_ptk_group);
3238         sm->group->GKeyDoneStations--;
3239         sm->GUpdateStationKeys = FALSE;
3240         sm->Disconnect = TRUE;
3241 }
3242
3243
3244 SM_STEP(WPA_PTK_GROUP)
3245 {
3246         if (sm->Init)
3247                 SM_ENTER(WPA_PTK_GROUP, IDLE);
3248         else switch (sm->wpa_ptk_group_state) {
3249         case WPA_PTK_GROUP_IDLE:
3250                 if (sm->GUpdateStationKeys ||
3251                     (sm->wpa == WPA_VERSION_WPA && sm->PInitAKeys))
3252                         SM_ENTER(WPA_PTK_GROUP, REKEYNEGOTIATING);
3253                 break;
3254         case WPA_PTK_GROUP_REKEYNEGOTIATING:
3255                 if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
3256                     !sm->EAPOLKeyPairwise && sm->MICVerified)
3257                         SM_ENTER(WPA_PTK_GROUP, REKEYESTABLISHED);
3258                 else if (sm->GTimeoutCtr >
3259                          (int) dot11RSNAConfigGroupUpdateCount)
3260                         SM_ENTER(WPA_PTK_GROUP, KEYERROR);
3261                 else if (sm->TimeoutEvt)
3262                         SM_ENTER(WPA_PTK_GROUP, REKEYNEGOTIATING);
3263                 break;
3264         case WPA_PTK_GROUP_KEYERROR:
3265                 SM_ENTER(WPA_PTK_GROUP, IDLE);
3266                 break;
3267         case WPA_PTK_GROUP_REKEYESTABLISHED:
3268                 SM_ENTER(WPA_PTK_GROUP, IDLE);
3269                 break;
3270         }
3271 }
3272
3273
3274 static void wpa_gtk_update(struct wpa_authenticator *wpa_auth,
3275                            struct wpa_group *group)
3276 {
3277         /* FIX: is this the correct way of getting GNonce? */
3278         memcpy(group->GNonce, group->Counter, WPA_NONCE_LEN);
3279         inc_byte_array(group->Counter, WPA_NONCE_LEN);
3280         wpa_gmk_to_gtk(group->GMK, wpa_auth->addr, group->GNonce,
3281                        group->GTK[group->GN - 1], group->GTK_len);
3282
3283 #ifdef CONFIG_IEEE80211W
3284         if (wpa_auth->conf.ieee80211w != WPA_NO_IEEE80211W) {
3285                 hostapd_get_rand(group->DGTK, WPA_DGTK_LEN);
3286                 wpa_hexdump_key(MSG_DEBUG, "DGTK", group->DGTK, WPA_DGTK_LEN);
3287                 hostapd_get_rand(group->IGTK[group->GN - 1], WPA_IGTK_LEN);
3288                 wpa_hexdump_key(MSG_DEBUG, "IGTK",
3289                                 group->IGTK[group->GN - 1], WPA_IGTK_LEN);
3290         }
3291 #endif /* CONFIG_IEEE80211W */
3292 }
3293
3294
3295 static void wpa_group_gtk_init(struct wpa_authenticator *wpa_auth,
3296                                struct wpa_group *group)
3297 {
3298         wpa_printf(MSG_DEBUG, "WPA: group state machine entering state "
3299                    "GTK_INIT (VLAN-ID %d)", group->vlan_id);
3300         group->changed = FALSE; /* GInit is not cleared here; avoid loop */
3301         group->wpa_group_state = WPA_GROUP_GTK_INIT;
3302
3303         /* GTK[0..N] = 0 */
3304         memset(group->GTK, 0, sizeof(group->GTK));
3305         group->GN = 1;
3306         group->GM = 2;
3307         /* GTK[GN] = CalcGTK() */
3308         wpa_gtk_update(wpa_auth, group);
3309 }
3310
3311
3312 static int wpa_group_update_sta(struct wpa_state_machine *sm, void *ctx)
3313 {
3314         sm->GUpdateStationKeys = TRUE;
3315         wpa_sm_step(sm);
3316         return 0;
3317 }
3318
3319
3320 static void wpa_group_setkeys(struct wpa_authenticator *wpa_auth,
3321                               struct wpa_group *group)
3322 {
3323         int tmp;
3324
3325         wpa_printf(MSG_DEBUG, "WPA: group state machine entering state "
3326                    "SETKEYS (VLAN-ID %d)", group->vlan_id);
3327         group->changed = TRUE;
3328         group->wpa_group_state = WPA_GROUP_SETKEYS;
3329         group->GTKReKey = FALSE;
3330         tmp = group->GM;
3331         group->GM = group->GN;
3332         group->GN = tmp;
3333         group->GKeyDoneStations = group->GNoStations;
3334         wpa_gtk_update(wpa_auth, group);
3335
3336         wpa_auth_for_each_sta(wpa_auth, wpa_group_update_sta, NULL);
3337 }
3338
3339
3340 static void wpa_group_setkeysdone(struct wpa_authenticator *wpa_auth,
3341                                   struct wpa_group *group)
3342 {
3343         wpa_printf(MSG_DEBUG, "WPA: group state machine entering state "
3344                    "SETKEYSDONE (VLAN-ID %d)", group->vlan_id);
3345         group->changed = TRUE;
3346         group->wpa_group_state = WPA_GROUP_SETKEYSDONE;
3347         wpa_auth_set_key(wpa_auth, group->vlan_id,
3348                          wpa_alg_txt(wpa_auth->conf.wpa_group),
3349                          NULL, group->GN, group->GTK[group->GN - 1],
3350                          group->GTK_len);
3351
3352 #ifdef CONFIG_IEEE80211W
3353         if (wpa_auth->conf.ieee80211w != WPA_NO_IEEE80211W) {
3354                 wpa_auth_set_key(wpa_auth, group->vlan_id, "IGTK",
3355                                  NULL, group->GN, group->IGTK[group->GN - 1],
3356                                  WPA_IGTK_LEN);
3357                 wpa_auth_set_key(wpa_auth, group->vlan_id, "DGTK",
3358                                  NULL, 0, group->DGTK, WPA_DGTK_LEN);
3359         }
3360 #endif /* CONFIG_IEEE80211W */
3361 }
3362
3363
3364 static void wpa_group_sm_step(struct wpa_authenticator *wpa_auth,
3365                               struct wpa_group *group)
3366 {
3367         if (group->GInit) {
3368                 wpa_group_gtk_init(wpa_auth, group);
3369         } else if (group->wpa_group_state == WPA_GROUP_GTK_INIT &&
3370                    group->GTKAuthenticator) {
3371                 wpa_group_setkeysdone(wpa_auth, group);
3372         } else if (group->wpa_group_state == WPA_GROUP_SETKEYSDONE &&
3373                    group->GTKReKey) {
3374                 wpa_group_setkeys(wpa_auth, group);
3375         } else if (group->wpa_group_state == WPA_GROUP_SETKEYS) {
3376                 if (group->GKeyDoneStations == 0)
3377                         wpa_group_setkeysdone(wpa_auth, group);
3378                 else if (group->GTKReKey)
3379                         wpa_group_setkeys(wpa_auth, group);
3380         }
3381 }
3382
3383
3384 static void wpa_sm_step(struct wpa_state_machine *sm)
3385 {
3386         if (sm == NULL)
3387                 return;
3388
3389         if (sm->in_step_loop) {
3390                 /* This should not happen, but if it does, make sure we do not
3391                  * end up freeing the state machine too early by exiting the
3392                  * recursive call. */
3393                 wpa_printf(MSG_ERROR, "WPA: wpa_sm_step() called recursively");
3394                 return;
3395         }
3396
3397         sm->in_step_loop = 1;
3398         do {
3399                 if (sm->pending_deinit)
3400                         break;
3401
3402                 sm->changed = FALSE;
3403                 sm->wpa_auth->group->changed = FALSE;
3404
3405                 SM_STEP_RUN(WPA_PTK);
3406                 if (sm->pending_deinit)
3407                         break;
3408                 SM_STEP_RUN(WPA_PTK_GROUP);
3409                 if (sm->pending_deinit)
3410                         break;
3411                 wpa_group_sm_step(sm->wpa_auth, sm->group);
3412         } while (sm->changed || sm->wpa_auth->group->changed);
3413         sm->in_step_loop = 0;
3414
3415         if (sm->pending_deinit) {
3416                 wpa_printf(MSG_DEBUG, "WPA: Completing pending STA state "
3417                            "machine deinit for " MACSTR, MAC2STR(sm->addr));
3418                 wpa_free_sta_sm(sm);
3419         }
3420 }
3421
3422
3423 static void wpa_sm_call_step(void *eloop_ctx, void *timeout_ctx)
3424 {
3425         struct wpa_state_machine *sm = eloop_ctx;
3426         wpa_sm_step(sm);
3427 }
3428
3429
3430 void wpa_auth_sm_notify(struct wpa_state_machine *sm)
3431 {
3432         if (sm == NULL)
3433                 return;
3434         eloop_register_timeout(0, 0, wpa_sm_call_step, sm, NULL);
3435 }
3436
3437
3438 void wpa_gtk_rekey(struct wpa_authenticator *wpa_auth)
3439 {
3440         int tmp, i;
3441         struct wpa_group *group;
3442
3443         if (wpa_auth == NULL)
3444                 return;
3445
3446         group = wpa_auth->group;
3447
3448         for (i = 0; i < 2; i++) {
3449                 tmp = group->GM;
3450                 group->GM = group->GN;
3451                 group->GN = tmp;
3452                 wpa_gtk_update(wpa_auth, group);
3453         }
3454 }
3455
3456
3457 static const char * wpa_bool_txt(int bool)
3458 {
3459         return bool ? "TRUE" : "FALSE";
3460 }
3461
3462
3463 static int wpa_cipher_bits(int cipher)
3464 {
3465         switch (cipher) {
3466         case WPA_CIPHER_CCMP:
3467                 return 128;
3468         case WPA_CIPHER_TKIP:
3469                 return 256;
3470         case WPA_CIPHER_WEP104:
3471                 return 104;
3472         case WPA_CIPHER_WEP40:
3473                 return 40;
3474         default:
3475                 return 0;
3476         }
3477 }
3478
3479
3480 #define RSN_SUITE "%02x-%02x-%02x-%d"
3481 #define RSN_SUITE_ARG(s) (s)[0], (s)[1], (s)[2], (s)[3]
3482
3483 int wpa_get_mib(struct wpa_authenticator *wpa_auth, char *buf, size_t buflen)
3484 {
3485         int len = 0, ret;
3486         char pmkid_txt[PMKID_LEN * 2 + 1];
3487
3488         if (wpa_auth == NULL)
3489                 return len;
3490
3491         ret = snprintf(buf + len, buflen - len,
3492                        "dot11RSNAOptionImplemented=TRUE\n"
3493 #ifdef CONFIG_RSN_PREAUTH
3494                        "dot11RSNAPreauthenticationImplemented=TRUE\n"
3495 #else /* CONFIG_RSN_PREAUTH */
3496                        "dot11RSNAPreauthenticationImplemented=FALSE\n"
3497 #endif /* CONFIG_RSN_PREAUTH */
3498                        "dot11RSNAEnabled=%s\n"
3499                        "dot11RSNAPreauthenticationEnabled=%s\n",
3500                        wpa_bool_txt(wpa_auth->conf.wpa &
3501                                     HOSTAPD_WPA_VERSION_WPA2),
3502                        wpa_bool_txt(wpa_auth->conf.rsn_preauth));
3503         if (ret < 0 || (size_t) ret >= buflen - len)
3504                 return len;
3505         len += ret;
3506
3507         wpa_snprintf_hex(pmkid_txt, sizeof(pmkid_txt),
3508                          wpa_auth->dot11RSNAPMKIDUsed, PMKID_LEN);
3509
3510         ret = snprintf(buf + len, buflen - len,
3511                        "dot11RSNAConfigVersion=%u\n"
3512                        "dot11RSNAConfigPairwiseKeysSupported=9999\n"
3513                        /* FIX: dot11RSNAConfigGroupCipher */
3514                        /* FIX: dot11RSNAConfigGroupRekeyMethod */
3515                        /* FIX: dot11RSNAConfigGroupRekeyTime */
3516                        /* FIX: dot11RSNAConfigGroupRekeyPackets */
3517                        "dot11RSNAConfigGroupRekeyStrict=%u\n"
3518                        "dot11RSNAConfigGroupUpdateCount=%u\n"
3519                        "dot11RSNAConfigPairwiseUpdateCount=%u\n"
3520                        "dot11RSNAConfigGroupCipherSize=%u\n"
3521                        "dot11RSNAConfigPMKLifetime=%u\n"
3522                        "dot11RSNAConfigPMKReauthThreshold=%u\n"
3523                        "dot11RSNAConfigNumberOfPTKSAReplayCounters=0\n"
3524                        "dot11RSNAConfigSATimeout=%u\n"
3525                        "dot11RSNAAuthenticationSuiteSelected=" RSN_SUITE "\n"
3526                        "dot11RSNAPairwiseCipherSelected=" RSN_SUITE "\n"
3527                        "dot11RSNAGroupCipherSelected=" RSN_SUITE "\n"
3528                        "dot11RSNAPMKIDUsed=%s\n"
3529                        "dot11RSNAAuthenticationSuiteRequested=" RSN_SUITE "\n"
3530                        "dot11RSNAPairwiseCipherRequested=" RSN_SUITE "\n"
3531                        "dot11RSNAGroupCipherRequested=" RSN_SUITE "\n"
3532                        "dot11RSNATKIPCounterMeasuresInvoked=%u\n"
3533                        "dot11RSNA4WayHandshakeFailures=%u\n"
3534                        "dot11RSNAConfigNumberOfGTKSAReplayCounters=0\n",
3535                        RSN_VERSION,
3536                        !!wpa_auth->conf.wpa_strict_rekey,
3537                        dot11RSNAConfigGroupUpdateCount,
3538                        dot11RSNAConfigPairwiseUpdateCount,
3539                        wpa_cipher_bits(wpa_auth->conf.wpa_group),
3540                        dot11RSNAConfigPMKLifetime,
3541                        dot11RSNAConfigPMKReauthThreshold,
3542                        dot11RSNAConfigSATimeout,
3543                        RSN_SUITE_ARG(wpa_auth->
3544                                      dot11RSNAAuthenticationSuiteSelected),
3545                        RSN_SUITE_ARG(wpa_auth->
3546                                      dot11RSNAPairwiseCipherSelected),
3547                        RSN_SUITE_ARG(wpa_auth->dot11RSNAGroupCipherSelected),
3548                        pmkid_txt,
3549                        RSN_SUITE_ARG(wpa_auth->
3550                                      dot11RSNAAuthenticationSuiteRequested),
3551                        RSN_SUITE_ARG(wpa_auth->
3552                                      dot11RSNAPairwiseCipherRequested),
3553                        RSN_SUITE_ARG(wpa_auth->dot11RSNAGroupCipherRequested),
3554                        wpa_auth->dot11RSNATKIPCounterMeasuresInvoked,
3555                        wpa_auth->dot11RSNA4WayHandshakeFailures);
3556         if (ret < 0 || (size_t) ret >= buflen - len)
3557                 return len;
3558         len += ret;
3559
3560         /* TODO: dot11RSNAConfigPairwiseCiphersTable */
3561         /* TODO: dot11RSNAConfigAuthenticationSuitesTable */
3562
3563         /* Private MIB */
3564         ret = snprintf(buf + len, buflen - len, "hostapdWPAGroupState=%d\n",
3565                        wpa_auth->group->wpa_group_state);
3566         if (ret < 0 || (size_t) ret >= buflen - len)
3567                 return len;
3568         len += ret;
3569
3570         return len;
3571 }
3572
3573
3574 int wpa_get_mib_sta(struct wpa_state_machine *sm, char *buf, size_t buflen)
3575 {
3576         int len = 0, ret;
3577         u8 not_used[4] = { 0, 0, 0, 0 };
3578         const u8 *pairwise = not_used;
3579
3580         if (sm == NULL)
3581                 return 0;
3582
3583         /* TODO: FF-FF-FF-FF-FF-FF entry for broadcast/multicast stats */
3584
3585         /* dot11RSNAStatsEntry */
3586
3587         if (sm->wpa == WPA_VERSION_WPA) {
3588                 if (sm->pairwise == WPA_CIPHER_CCMP)
3589                         pairwise = WPA_CIPHER_SUITE_CCMP;
3590                 else if (sm->pairwise == WPA_CIPHER_TKIP)
3591                         pairwise = WPA_CIPHER_SUITE_TKIP;
3592                 else if (sm->pairwise == WPA_CIPHER_WEP104)
3593                         pairwise = WPA_CIPHER_SUITE_WEP104;
3594                 else if (sm->pairwise == WPA_CIPHER_WEP40)
3595                         pairwise = WPA_CIPHER_SUITE_WEP40;
3596                 else if (sm->pairwise == WPA_CIPHER_NONE)
3597                         pairwise = WPA_CIPHER_SUITE_NONE;
3598         } else if (sm->wpa == WPA_VERSION_WPA2) {
3599                 if (sm->pairwise == WPA_CIPHER_CCMP)
3600                         pairwise = RSN_CIPHER_SUITE_CCMP;
3601                 else if (sm->pairwise == WPA_CIPHER_TKIP)
3602                         pairwise = RSN_CIPHER_SUITE_TKIP;
3603                 else if (sm->pairwise == WPA_CIPHER_WEP104)
3604                         pairwise = RSN_CIPHER_SUITE_WEP104;
3605                 else if (sm->pairwise == WPA_CIPHER_WEP40)
3606                         pairwise = RSN_CIPHER_SUITE_WEP40;
3607                 else if (sm->pairwise == WPA_CIPHER_NONE)
3608                         pairwise = RSN_CIPHER_SUITE_NONE;
3609         } else
3610                 return 0;
3611
3612         ret = snprintf(buf + len, buflen - len,
3613                        /* TODO: dot11RSNAStatsIndex */
3614                        "dot11RSNAStatsSTAAddress=" MACSTR "\n"
3615                        "dot11RSNAStatsVersion=1\n"
3616                        "dot11RSNAStatsSelectedPairwiseCipher=" RSN_SUITE "\n"
3617                        /* TODO: dot11RSNAStatsTKIPICVErrors */
3618                        "dot11RSNAStatsTKIPLocalMICFailures=%u\n"
3619                        "dot11RSNAStatsTKIPRemoveMICFailures=%u\n"
3620                        /* TODO: dot11RSNAStatsCCMPReplays */
3621                        /* TODO: dot11RSNAStatsCCMPDecryptErrors */
3622                        /* TODO: dot11RSNAStatsTKIPReplays */,
3623                        MAC2STR(sm->addr),
3624                        RSN_SUITE_ARG(pairwise),
3625                        sm->dot11RSNAStatsTKIPLocalMICFailures,
3626                        sm->dot11RSNAStatsTKIPRemoteMICFailures);
3627         if (ret < 0 || (size_t) ret >= buflen - len)
3628                 return len;
3629         len += ret;
3630
3631         /* Private MIB */
3632         ret = snprintf(buf + len, buflen - len,
3633                        "hostapdWPAPTKState=%d\n"
3634                        "hostapdWPAPTKGroupState=%d\n",
3635                        sm->wpa_ptk_state,
3636                        sm->wpa_ptk_group_state);
3637         if (ret < 0 || (size_t) ret >= buflen - len)
3638                 return len;
3639         len += ret;
3640
3641         return len;
3642 }
3643
3644
3645 void wpa_auth_countermeasures_start(struct wpa_authenticator *wpa_auth)
3646 {
3647         if (wpa_auth)
3648                 wpa_auth->dot11RSNATKIPCounterMeasuresInvoked++;
3649 }
3650
3651
3652 int wpa_auth_pairwise_set(struct wpa_state_machine *sm)
3653 {
3654         return sm && sm->pairwise_set;
3655 }
3656
3657
3658 int wpa_auth_sta_key_mgmt(struct wpa_state_machine *sm)
3659 {
3660         if (sm == NULL)
3661                 return -1;
3662         return sm->wpa_key_mgmt;
3663 }
3664
3665
3666 int wpa_auth_sta_wpa_version(struct wpa_state_machine *sm)
3667 {
3668         if (sm == NULL)
3669                 return 0;
3670         return sm->wpa;
3671 }
3672
3673
3674 int wpa_auth_sta_clear_pmksa(struct wpa_state_machine *sm,
3675                              struct rsn_pmksa_cache_entry *entry)
3676 {
3677         if (sm == NULL || sm->pmksa != entry)
3678                 return -1;
3679         sm->pmksa = NULL;
3680         return 0;
3681 }
3682
3683
3684 struct rsn_pmksa_cache_entry *
3685 wpa_auth_sta_get_pmksa(struct wpa_state_machine *sm)
3686 {
3687         return sm ? sm->pmksa : NULL;
3688 }
3689
3690
3691 void wpa_auth_sta_local_mic_failure_report(struct wpa_state_machine *sm)
3692 {
3693         if (sm)
3694                 sm->dot11RSNAStatsTKIPLocalMICFailures++;
3695 }
3696
3697
3698 const u8 * wpa_auth_get_wpa_ie(struct wpa_authenticator *wpa_auth, size_t *len)
3699 {
3700         if (wpa_auth == NULL)
3701                 return NULL;
3702         *len = wpa_auth->wpa_ie_len;
3703         return wpa_auth->wpa_ie;
3704 }
3705
3706
3707 int wpa_auth_pmksa_add(struct wpa_state_machine *sm, const u8 *pmk,
3708                        int session_timeout, struct eapol_state_machine *eapol)
3709 {
3710         if (sm == NULL || sm->wpa != WPA_VERSION_WPA2)
3711                 return -1;
3712
3713         if (pmksa_cache_add(sm->wpa_auth->pmksa, pmk, WPA_PMK_LEN,
3714                             sm->wpa_auth->addr, sm->addr, session_timeout,
3715                             eapol))
3716                 return 0;
3717
3718         return -1;
3719 }
3720
3721
3722 int wpa_auth_pmksa_add_preauth(struct wpa_authenticator *wpa_auth,
3723                                const u8 *pmk, size_t len, const u8 *sta_addr,
3724                                int session_timeout,
3725                                struct eapol_state_machine *eapol)
3726 {
3727         if (wpa_auth == NULL)
3728                 return -1;
3729
3730         if (pmksa_cache_add(wpa_auth->pmksa, pmk, len, wpa_auth->addr,
3731                             sta_addr, session_timeout, eapol))
3732                 return 0;
3733
3734         return -1;
3735 }
3736
3737
3738 static struct wpa_group *
3739 wpa_auth_add_group(struct wpa_authenticator *wpa_auth, int vlan_id)
3740 {
3741         struct wpa_group *group;
3742
3743         if (wpa_auth == NULL || wpa_auth->group == NULL)
3744                 return NULL;
3745
3746         wpa_printf(MSG_DEBUG, "WPA: Add group state machine for VLAN-ID %d",
3747                    vlan_id);
3748         group = wpa_group_init(wpa_auth, vlan_id);
3749         if (group == NULL)
3750                 return NULL;
3751
3752         group->next = wpa_auth->group->next;
3753         wpa_auth->group->next = group;
3754
3755         return group;
3756 }
3757
3758
3759 int wpa_auth_sta_set_vlan(struct wpa_state_machine *sm, int vlan_id)
3760 {
3761         struct wpa_group *group;
3762
3763         if (sm == NULL || sm->wpa_auth == NULL)
3764                 return 0;
3765
3766         group = sm->wpa_auth->group;
3767         while (group) {
3768                 if (group->vlan_id == vlan_id)
3769                         break;
3770                 group = group->next;
3771         }
3772
3773         if (group == NULL) {
3774                 group = wpa_auth_add_group(sm->wpa_auth, vlan_id);
3775                 if (group == NULL)
3776                         return -1;
3777         }
3778
3779         if (sm->group == group)
3780                 return 0;
3781
3782         wpa_printf(MSG_DEBUG, "WPA: Moving STA " MACSTR " to use group state "
3783                    "machine for VLAN ID %d", MAC2STR(sm->addr), vlan_id);
3784
3785         if (sm->group && sm->group != group && sm->sta_counted) {
3786                 sm->group->GNoStations--;
3787                 sm->sta_counted = 0;
3788                 wpa_printf(MSG_DEBUG, "WLA: Decreased GNoStations for the "
3789                            "previously used group state machine");
3790         }
3791
3792         sm->group = group;
3793         return 0;
3794 }
3795
3796 #endif /* CONFIG_NATIVE_WINDOWS */