OSDN Git Service

3fbb88b93544de008e0d02330f65694ed205202d
[android-x86/external-wpa_supplicant_8.git] / src / ap / wpa_auth.c
1 /*
2  * hostapd - IEEE 802.11i-2004 / WPA Authenticator
3  * Copyright (c) 2004-2009, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14
15 #include "utils/includes.h"
16
17 #include "utils/common.h"
18 #include "utils/eloop.h"
19 #include "utils/state_machine.h"
20 #include "common/ieee802_11_defs.h"
21 #include "crypto/aes_wrap.h"
22 #include "crypto/crypto.h"
23 #include "crypto/sha1.h"
24 #include "crypto/sha256.h"
25 #include "crypto/random.h"
26 #include "eapol_auth/eapol_auth_sm.h"
27 #include "ap_config.h"
28 #include "ieee802_11.h"
29 #include "wpa_auth.h"
30 #include "pmksa_cache_auth.h"
31 #include "wpa_auth_i.h"
32 #include "wpa_auth_ie.h"
33
34 #define STATE_MACHINE_DATA struct wpa_state_machine
35 #define STATE_MACHINE_DEBUG_PREFIX "WPA"
36 #define STATE_MACHINE_ADDR sm->addr
37
38
39 static void wpa_send_eapol_timeout(void *eloop_ctx, void *timeout_ctx);
40 static int wpa_sm_step(struct wpa_state_machine *sm);
41 static int wpa_verify_key_mic(struct wpa_ptk *PTK, u8 *data, size_t data_len);
42 static void wpa_sm_call_step(void *eloop_ctx, void *timeout_ctx);
43 static void wpa_group_sm_step(struct wpa_authenticator *wpa_auth,
44                               struct wpa_group *group);
45 static void wpa_request_new_ptk(struct wpa_state_machine *sm);
46 static int wpa_gtk_update(struct wpa_authenticator *wpa_auth,
47                           struct wpa_group *group);
48 static int wpa_group_config_group_keys(struct wpa_authenticator *wpa_auth,
49                                        struct wpa_group *group);
50
51 static const u32 dot11RSNAConfigGroupUpdateCount = 4;
52 static const u32 dot11RSNAConfigPairwiseUpdateCount = 4;
53 static const u32 eapol_key_timeout_first = 100; /* ms */
54 static const u32 eapol_key_timeout_subseq = 1000; /* ms */
55
56 /* TODO: make these configurable */
57 static const int dot11RSNAConfigPMKLifetime = 43200;
58 static const int dot11RSNAConfigPMKReauthThreshold = 70;
59 static const int dot11RSNAConfigSATimeout = 60;
60
61
62 static inline void wpa_auth_mic_failure_report(
63         struct wpa_authenticator *wpa_auth, const u8 *addr)
64 {
65         if (wpa_auth->cb.mic_failure_report)
66                 wpa_auth->cb.mic_failure_report(wpa_auth->cb.ctx, addr);
67 }
68
69
70 static inline void wpa_auth_set_eapol(struct wpa_authenticator *wpa_auth,
71                                       const u8 *addr, wpa_eapol_variable var,
72                                       int value)
73 {
74         if (wpa_auth->cb.set_eapol)
75                 wpa_auth->cb.set_eapol(wpa_auth->cb.ctx, addr, var, value);
76 }
77
78
79 static inline int wpa_auth_get_eapol(struct wpa_authenticator *wpa_auth,
80                                      const u8 *addr, wpa_eapol_variable var)
81 {
82         if (wpa_auth->cb.get_eapol == NULL)
83                 return -1;
84         return wpa_auth->cb.get_eapol(wpa_auth->cb.ctx, addr, var);
85 }
86
87
88 static inline const u8 * wpa_auth_get_psk(struct wpa_authenticator *wpa_auth,
89                                           const u8 *addr, const u8 *prev_psk)
90 {
91         if (wpa_auth->cb.get_psk == NULL)
92                 return NULL;
93         return wpa_auth->cb.get_psk(wpa_auth->cb.ctx, addr, prev_psk);
94 }
95
96
97 static inline int wpa_auth_get_msk(struct wpa_authenticator *wpa_auth,
98                                    const u8 *addr, u8 *msk, size_t *len)
99 {
100         if (wpa_auth->cb.get_msk == NULL)
101                 return -1;
102         return wpa_auth->cb.get_msk(wpa_auth->cb.ctx, addr, msk, len);
103 }
104
105
106 static inline int wpa_auth_set_key(struct wpa_authenticator *wpa_auth,
107                                    int vlan_id,
108                                    enum wpa_alg alg, const u8 *addr, int idx,
109                                    u8 *key, size_t key_len)
110 {
111         if (wpa_auth->cb.set_key == NULL)
112                 return -1;
113         return wpa_auth->cb.set_key(wpa_auth->cb.ctx, vlan_id, alg, addr, idx,
114                                     key, key_len);
115 }
116
117
118 static inline int wpa_auth_get_seqnum(struct wpa_authenticator *wpa_auth,
119                                       const u8 *addr, int idx, u8 *seq)
120 {
121         if (wpa_auth->cb.get_seqnum == NULL)
122                 return -1;
123         return wpa_auth->cb.get_seqnum(wpa_auth->cb.ctx, addr, idx, seq);
124 }
125
126
127 static inline int
128 wpa_auth_send_eapol(struct wpa_authenticator *wpa_auth, const u8 *addr,
129                     const u8 *data, size_t data_len, int encrypt)
130 {
131         if (wpa_auth->cb.send_eapol == NULL)
132                 return -1;
133         return wpa_auth->cb.send_eapol(wpa_auth->cb.ctx, addr, data, data_len,
134                                        encrypt);
135 }
136
137
138 int wpa_auth_for_each_sta(struct wpa_authenticator *wpa_auth,
139                           int (*cb)(struct wpa_state_machine *sm, void *ctx),
140                           void *cb_ctx)
141 {
142         if (wpa_auth->cb.for_each_sta == NULL)
143                 return 0;
144         return wpa_auth->cb.for_each_sta(wpa_auth->cb.ctx, cb, cb_ctx);
145 }
146
147
148 int wpa_auth_for_each_auth(struct wpa_authenticator *wpa_auth,
149                            int (*cb)(struct wpa_authenticator *a, void *ctx),
150                            void *cb_ctx)
151 {
152         if (wpa_auth->cb.for_each_auth == NULL)
153                 return 0;
154         return wpa_auth->cb.for_each_auth(wpa_auth->cb.ctx, cb, cb_ctx);
155 }
156
157
158 void wpa_auth_logger(struct wpa_authenticator *wpa_auth, const u8 *addr,
159                      logger_level level, const char *txt)
160 {
161         if (wpa_auth->cb.logger == NULL)
162                 return;
163         wpa_auth->cb.logger(wpa_auth->cb.ctx, addr, level, txt);
164 }
165
166
167 void wpa_auth_vlogger(struct wpa_authenticator *wpa_auth, const u8 *addr,
168                       logger_level level, const char *fmt, ...)
169 {
170         char *format;
171         int maxlen;
172         va_list ap;
173
174         if (wpa_auth->cb.logger == NULL)
175                 return;
176
177         maxlen = os_strlen(fmt) + 100;
178         format = os_malloc(maxlen);
179         if (!format)
180                 return;
181
182         va_start(ap, fmt);
183         vsnprintf(format, maxlen, fmt, ap);
184         va_end(ap);
185
186         wpa_auth_logger(wpa_auth, addr, level, format);
187
188         os_free(format);
189 }
190
191
192 static void wpa_sta_disconnect(struct wpa_authenticator *wpa_auth,
193                                const u8 *addr)
194 {
195         if (wpa_auth->cb.disconnect == NULL)
196                 return;
197         wpa_auth->cb.disconnect(wpa_auth->cb.ctx, addr,
198                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
199 }
200
201
202 static int wpa_use_aes_cmac(struct wpa_state_machine *sm)
203 {
204         int ret = 0;
205 #ifdef CONFIG_IEEE80211R
206         if (wpa_key_mgmt_ft(sm->wpa_key_mgmt))
207                 ret = 1;
208 #endif /* CONFIG_IEEE80211R */
209 #ifdef CONFIG_IEEE80211W
210         if (wpa_key_mgmt_sha256(sm->wpa_key_mgmt))
211                 ret = 1;
212 #endif /* CONFIG_IEEE80211W */
213         return ret;
214 }
215
216
217 static void wpa_rekey_gmk(void *eloop_ctx, void *timeout_ctx)
218 {
219         struct wpa_authenticator *wpa_auth = eloop_ctx;
220
221         if (random_get_bytes(wpa_auth->group->GMK, WPA_GMK_LEN)) {
222                 wpa_printf(MSG_ERROR, "Failed to get random data for WPA "
223                            "initialization.");
224         } else {
225                 wpa_auth_logger(wpa_auth, NULL, LOGGER_DEBUG, "GMK rekeyd");
226                 wpa_hexdump_key(MSG_DEBUG, "GMK",
227                                 wpa_auth->group->GMK, WPA_GMK_LEN);
228         }
229
230         if (wpa_auth->conf.wpa_gmk_rekey) {
231                 eloop_register_timeout(wpa_auth->conf.wpa_gmk_rekey, 0,
232                                        wpa_rekey_gmk, wpa_auth, NULL);
233         }
234 }
235
236
237 static void wpa_rekey_gtk(void *eloop_ctx, void *timeout_ctx)
238 {
239         struct wpa_authenticator *wpa_auth = eloop_ctx;
240         struct wpa_group *group;
241
242         wpa_auth_logger(wpa_auth, NULL, LOGGER_DEBUG, "rekeying GTK");
243         for (group = wpa_auth->group; group; group = group->next) {
244                 group->GTKReKey = TRUE;
245                 do {
246                         group->changed = FALSE;
247                         wpa_group_sm_step(wpa_auth, group);
248                 } while (group->changed);
249         }
250
251         if (wpa_auth->conf.wpa_group_rekey) {
252                 eloop_register_timeout(wpa_auth->conf.wpa_group_rekey,
253                                        0, wpa_rekey_gtk, wpa_auth, NULL);
254         }
255 }
256
257
258 static void wpa_rekey_ptk(void *eloop_ctx, void *timeout_ctx)
259 {
260         struct wpa_authenticator *wpa_auth = eloop_ctx;
261         struct wpa_state_machine *sm = timeout_ctx;
262
263         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG, "rekeying PTK");
264         wpa_request_new_ptk(sm);
265         wpa_sm_step(sm);
266 }
267
268
269 static int wpa_auth_pmksa_clear_cb(struct wpa_state_machine *sm, void *ctx)
270 {
271         if (sm->pmksa == ctx)
272                 sm->pmksa = NULL;
273         return 0;
274 }
275
276
277 static void wpa_auth_pmksa_free_cb(struct rsn_pmksa_cache_entry *entry,
278                                    void *ctx)
279 {
280         struct wpa_authenticator *wpa_auth = ctx;
281         wpa_auth_for_each_sta(wpa_auth, wpa_auth_pmksa_clear_cb, entry);
282 }
283
284
285 static void wpa_group_set_key_len(struct wpa_group *group, int cipher)
286 {
287         switch (cipher) {
288         case WPA_CIPHER_CCMP:
289                 group->GTK_len = 16;
290                 break;
291         case WPA_CIPHER_TKIP:
292                 group->GTK_len = 32;
293                 break;
294         case WPA_CIPHER_WEP104:
295                 group->GTK_len = 13;
296                 break;
297         case WPA_CIPHER_WEP40:
298                 group->GTK_len = 5;
299                 break;
300         }
301 }
302
303
304 static int wpa_group_init_gmk_and_counter(struct wpa_authenticator *wpa_auth,
305                                           struct wpa_group *group)
306 {
307         u8 buf[ETH_ALEN + 8 + sizeof(group)];
308         u8 rkey[32];
309
310         if (random_get_bytes(group->GMK, WPA_GMK_LEN) < 0)
311                 return -1;
312         wpa_hexdump_key(MSG_DEBUG, "GMK", group->GMK, WPA_GMK_LEN);
313
314         /*
315          * Counter = PRF-256(Random number, "Init Counter",
316          *                   Local MAC Address || Time)
317          */
318         os_memcpy(buf, wpa_auth->addr, ETH_ALEN);
319         wpa_get_ntp_timestamp(buf + ETH_ALEN);
320         os_memcpy(buf + ETH_ALEN + 8, &group, sizeof(group));
321         if (random_get_bytes(rkey, sizeof(rkey)) < 0)
322                 return -1;
323
324         if (sha1_prf(rkey, sizeof(rkey), "Init Counter", buf, sizeof(buf),
325                      group->Counter, WPA_NONCE_LEN) < 0)
326                 return -1;
327         wpa_hexdump_key(MSG_DEBUG, "Key Counter",
328                         group->Counter, WPA_NONCE_LEN);
329
330         return 0;
331 }
332
333
334 static struct wpa_group * wpa_group_init(struct wpa_authenticator *wpa_auth,
335                                          int vlan_id)
336 {
337         struct wpa_group *group;
338
339         group = os_zalloc(sizeof(struct wpa_group));
340         if (group == NULL)
341                 return NULL;
342
343         group->GTKAuthenticator = TRUE;
344         group->vlan_id = vlan_id;
345
346         wpa_group_set_key_len(group, wpa_auth->conf.wpa_group);
347
348         if (random_pool_ready() != 1) {
349                 wpa_printf(MSG_INFO, "WPA: Not enough entropy in random pool "
350                            "for secure operations - update keys later when "
351                            "the first station connects");
352         }
353
354         /*
355          * Set initial GMK/Counter value here. The actual values that will be
356          * used in negotiations will be set once the first station tries to
357          * connect. This allows more time for collecting additional randomness
358          * on embedded devices.
359          */
360         if (wpa_group_init_gmk_and_counter(wpa_auth, group) < 0) {
361                 wpa_printf(MSG_ERROR, "Failed to get random data for WPA "
362                            "initialization.");
363                 os_free(group);
364                 return NULL;
365         }
366
367         group->GInit = TRUE;
368         wpa_group_sm_step(wpa_auth, group);
369         group->GInit = FALSE;
370         wpa_group_sm_step(wpa_auth, group);
371
372         return group;
373 }
374
375
376 /**
377  * wpa_init - Initialize WPA authenticator
378  * @addr: Authenticator address
379  * @conf: Configuration for WPA authenticator
380  * @cb: Callback functions for WPA authenticator
381  * Returns: Pointer to WPA authenticator data or %NULL on failure
382  */
383 struct wpa_authenticator * wpa_init(const u8 *addr,
384                                     struct wpa_auth_config *conf,
385                                     struct wpa_auth_callbacks *cb)
386 {
387         struct wpa_authenticator *wpa_auth;
388
389         wpa_auth = os_zalloc(sizeof(struct wpa_authenticator));
390         if (wpa_auth == NULL)
391                 return NULL;
392         os_memcpy(wpa_auth->addr, addr, ETH_ALEN);
393         os_memcpy(&wpa_auth->conf, conf, sizeof(*conf));
394         os_memcpy(&wpa_auth->cb, cb, sizeof(*cb));
395
396         if (wpa_auth_gen_wpa_ie(wpa_auth)) {
397                 wpa_printf(MSG_ERROR, "Could not generate WPA IE.");
398                 os_free(wpa_auth);
399                 return NULL;
400         }
401
402         wpa_auth->group = wpa_group_init(wpa_auth, 0);
403         if (wpa_auth->group == NULL) {
404                 os_free(wpa_auth->wpa_ie);
405                 os_free(wpa_auth);
406                 return NULL;
407         }
408
409         wpa_auth->pmksa = pmksa_cache_auth_init(wpa_auth_pmksa_free_cb,
410                                                 wpa_auth);
411         if (wpa_auth->pmksa == NULL) {
412                 wpa_printf(MSG_ERROR, "PMKSA cache initialization failed.");
413                 os_free(wpa_auth->wpa_ie);
414                 os_free(wpa_auth);
415                 return NULL;
416         }
417
418 #ifdef CONFIG_IEEE80211R
419         wpa_auth->ft_pmk_cache = wpa_ft_pmk_cache_init();
420         if (wpa_auth->ft_pmk_cache == NULL) {
421                 wpa_printf(MSG_ERROR, "FT PMK cache initialization failed.");
422                 os_free(wpa_auth->wpa_ie);
423                 pmksa_cache_auth_deinit(wpa_auth->pmksa);
424                 os_free(wpa_auth);
425                 return NULL;
426         }
427 #endif /* CONFIG_IEEE80211R */
428
429         if (wpa_auth->conf.wpa_gmk_rekey) {
430                 eloop_register_timeout(wpa_auth->conf.wpa_gmk_rekey, 0,
431                                        wpa_rekey_gmk, wpa_auth, NULL);
432         }
433
434         if (wpa_auth->conf.wpa_group_rekey) {
435                 eloop_register_timeout(wpa_auth->conf.wpa_group_rekey, 0,
436                                        wpa_rekey_gtk, wpa_auth, NULL);
437         }
438
439         return wpa_auth;
440 }
441
442
443 /**
444  * wpa_deinit - Deinitialize WPA authenticator
445  * @wpa_auth: Pointer to WPA authenticator data from wpa_init()
446  */
447 void wpa_deinit(struct wpa_authenticator *wpa_auth)
448 {
449         struct wpa_group *group, *prev;
450
451         eloop_cancel_timeout(wpa_rekey_gmk, wpa_auth, NULL);
452         eloop_cancel_timeout(wpa_rekey_gtk, wpa_auth, NULL);
453
454 #ifdef CONFIG_PEERKEY
455         while (wpa_auth->stsl_negotiations)
456                 wpa_stsl_remove(wpa_auth, wpa_auth->stsl_negotiations);
457 #endif /* CONFIG_PEERKEY */
458
459         pmksa_cache_auth_deinit(wpa_auth->pmksa);
460
461 #ifdef CONFIG_IEEE80211R
462         wpa_ft_pmk_cache_deinit(wpa_auth->ft_pmk_cache);
463         wpa_auth->ft_pmk_cache = NULL;
464 #endif /* CONFIG_IEEE80211R */
465
466         os_free(wpa_auth->wpa_ie);
467
468         group = wpa_auth->group;
469         while (group) {
470                 prev = group;
471                 group = group->next;
472                 os_free(prev);
473         }
474
475         os_free(wpa_auth);
476 }
477
478
479 /**
480  * wpa_reconfig - Update WPA authenticator configuration
481  * @wpa_auth: Pointer to WPA authenticator data from wpa_init()
482  * @conf: Configuration for WPA authenticator
483  */
484 int wpa_reconfig(struct wpa_authenticator *wpa_auth,
485                  struct wpa_auth_config *conf)
486 {
487         struct wpa_group *group;
488         if (wpa_auth == NULL)
489                 return 0;
490
491         os_memcpy(&wpa_auth->conf, conf, sizeof(*conf));
492         if (wpa_auth_gen_wpa_ie(wpa_auth)) {
493                 wpa_printf(MSG_ERROR, "Could not generate WPA IE.");
494                 return -1;
495         }
496
497         /*
498          * Reinitialize GTK to make sure it is suitable for the new
499          * configuration.
500          */
501         group = wpa_auth->group;
502         wpa_group_set_key_len(group, wpa_auth->conf.wpa_group);
503         group->GInit = TRUE;
504         wpa_group_sm_step(wpa_auth, group);
505         group->GInit = FALSE;
506         wpa_group_sm_step(wpa_auth, group);
507
508         return 0;
509 }
510
511
512 struct wpa_state_machine *
513 wpa_auth_sta_init(struct wpa_authenticator *wpa_auth, const u8 *addr)
514 {
515         struct wpa_state_machine *sm;
516
517         sm = os_zalloc(sizeof(struct wpa_state_machine));
518         if (sm == NULL)
519                 return NULL;
520         os_memcpy(sm->addr, addr, ETH_ALEN);
521
522         sm->wpa_auth = wpa_auth;
523         sm->group = wpa_auth->group;
524
525         return sm;
526 }
527
528
529 int wpa_auth_sta_associated(struct wpa_authenticator *wpa_auth,
530                             struct wpa_state_machine *sm)
531 {
532         if (wpa_auth == NULL || !wpa_auth->conf.wpa || sm == NULL)
533                 return -1;
534
535 #ifdef CONFIG_IEEE80211R
536         if (sm->ft_completed) {
537                 wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG,
538                                 "FT authentication already completed - do not "
539                                 "start 4-way handshake");
540                 return 0;
541         }
542 #endif /* CONFIG_IEEE80211R */
543
544         if (sm->started) {
545                 os_memset(&sm->key_replay, 0, sizeof(sm->key_replay));
546                 sm->ReAuthenticationRequest = TRUE;
547                 return wpa_sm_step(sm);
548         }
549
550         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG,
551                         "start authentication");
552         sm->started = 1;
553
554         sm->Init = TRUE;
555         if (wpa_sm_step(sm) == 1)
556                 return 1; /* should not really happen */
557         sm->Init = FALSE;
558         sm->AuthenticationRequest = TRUE;
559         return wpa_sm_step(sm);
560 }
561
562
563 void wpa_auth_sta_no_wpa(struct wpa_state_machine *sm)
564 {
565         /* WPA/RSN was not used - clear WPA state. This is needed if the STA
566          * reassociates back to the same AP while the previous entry for the
567          * STA has not yet been removed. */
568         if (sm == NULL)
569                 return;
570
571         sm->wpa_key_mgmt = 0;
572 }
573
574
575 static void wpa_free_sta_sm(struct wpa_state_machine *sm)
576 {
577         if (sm->GUpdateStationKeys) {
578                 sm->group->GKeyDoneStations--;
579                 sm->GUpdateStationKeys = FALSE;
580         }
581 #ifdef CONFIG_IEEE80211R
582         os_free(sm->assoc_resp_ftie);
583 #endif /* CONFIG_IEEE80211R */
584         os_free(sm->last_rx_eapol_key);
585         os_free(sm->wpa_ie);
586         os_free(sm);
587 }
588
589
590 void wpa_auth_sta_deinit(struct wpa_state_machine *sm)
591 {
592         if (sm == NULL)
593                 return;
594
595         if (sm->wpa_auth->conf.wpa_strict_rekey && sm->has_GTK) {
596                 wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
597                                 "strict rekeying - force GTK rekey since STA "
598                                 "is leaving");
599                 eloop_cancel_timeout(wpa_rekey_gtk, sm->wpa_auth, NULL);
600                 eloop_register_timeout(0, 500000, wpa_rekey_gtk, sm->wpa_auth,
601                                        NULL);
602         }
603
604         eloop_cancel_timeout(wpa_send_eapol_timeout, sm->wpa_auth, sm);
605         sm->pending_1_of_4_timeout = 0;
606         eloop_cancel_timeout(wpa_sm_call_step, sm, NULL);
607         eloop_cancel_timeout(wpa_rekey_ptk, sm->wpa_auth, sm);
608         if (sm->in_step_loop) {
609                 /* Must not free state machine while wpa_sm_step() is running.
610                  * Freeing will be completed in the end of wpa_sm_step(). */
611                 wpa_printf(MSG_DEBUG, "WPA: Registering pending STA state "
612                            "machine deinit for " MACSTR, MAC2STR(sm->addr));
613                 sm->pending_deinit = 1;
614         } else
615                 wpa_free_sta_sm(sm);
616 }
617
618
619 static void wpa_request_new_ptk(struct wpa_state_machine *sm)
620 {
621         if (sm == NULL)
622                 return;
623
624         sm->PTKRequest = TRUE;
625         sm->PTK_valid = 0;
626 }
627
628
629 static int wpa_replay_counter_valid(struct wpa_state_machine *sm,
630                                     const u8 *replay_counter)
631 {
632         int i;
633         for (i = 0; i < RSNA_MAX_EAPOL_RETRIES; i++) {
634                 if (!sm->key_replay[i].valid)
635                         break;
636                 if (os_memcmp(replay_counter, sm->key_replay[i].counter,
637                               WPA_REPLAY_COUNTER_LEN) == 0)
638                         return 1;
639         }
640         return 0;
641 }
642
643
644 #ifdef CONFIG_IEEE80211R
645 static int ft_check_msg_2_of_4(struct wpa_authenticator *wpa_auth,
646                                struct wpa_state_machine *sm,
647                                struct wpa_eapol_ie_parse *kde)
648 {
649         struct wpa_ie_data ie;
650         struct rsn_mdie *mdie;
651
652         if (wpa_parse_wpa_ie_rsn(kde->rsn_ie, kde->rsn_ie_len, &ie) < 0 ||
653             ie.num_pmkid != 1 || ie.pmkid == NULL) {
654                 wpa_printf(MSG_DEBUG, "FT: No PMKR1Name in "
655                            "FT 4-way handshake message 2/4");
656                 return -1;
657         }
658
659         os_memcpy(sm->sup_pmk_r1_name, ie.pmkid, PMKID_LEN);
660         wpa_hexdump(MSG_DEBUG, "FT: PMKR1Name from Supplicant",
661                     sm->sup_pmk_r1_name, PMKID_LEN);
662
663         if (!kde->mdie || !kde->ftie) {
664                 wpa_printf(MSG_DEBUG, "FT: No %s in FT 4-way handshake "
665                            "message 2/4", kde->mdie ? "FTIE" : "MDIE");
666                 return -1;
667         }
668
669         mdie = (struct rsn_mdie *) (kde->mdie + 2);
670         if (kde->mdie[1] < sizeof(struct rsn_mdie) ||
671             os_memcmp(wpa_auth->conf.mobility_domain, mdie->mobility_domain,
672                       MOBILITY_DOMAIN_ID_LEN) != 0) {
673                 wpa_printf(MSG_DEBUG, "FT: MDIE mismatch");
674                 return -1;
675         }
676
677         if (sm->assoc_resp_ftie &&
678             (kde->ftie[1] != sm->assoc_resp_ftie[1] ||
679              os_memcmp(kde->ftie, sm->assoc_resp_ftie,
680                        2 + sm->assoc_resp_ftie[1]) != 0)) {
681                 wpa_printf(MSG_DEBUG, "FT: FTIE mismatch");
682                 wpa_hexdump(MSG_DEBUG, "FT: FTIE in EAPOL-Key msg 2/4",
683                             kde->ftie, kde->ftie_len);
684                 wpa_hexdump(MSG_DEBUG, "FT: FTIE in (Re)AssocResp",
685                             sm->assoc_resp_ftie, 2 + sm->assoc_resp_ftie[1]);
686                 return -1;
687         }
688
689         return 0;
690 }
691 #endif /* CONFIG_IEEE80211R */
692
693
694 void wpa_receive(struct wpa_authenticator *wpa_auth,
695                  struct wpa_state_machine *sm,
696                  u8 *data, size_t data_len)
697 {
698         struct ieee802_1x_hdr *hdr;
699         struct wpa_eapol_key *key;
700         u16 key_info, key_data_length;
701         enum { PAIRWISE_2, PAIRWISE_4, GROUP_2, REQUEST,
702                SMK_M1, SMK_M3, SMK_ERROR } msg;
703         char *msgtxt;
704         struct wpa_eapol_ie_parse kde;
705         int ft;
706         const u8 *eapol_key_ie;
707         size_t eapol_key_ie_len;
708
709         if (wpa_auth == NULL || !wpa_auth->conf.wpa || sm == NULL)
710                 return;
711
712         if (data_len < sizeof(*hdr) + sizeof(*key))
713                 return;
714
715         hdr = (struct ieee802_1x_hdr *) data;
716         key = (struct wpa_eapol_key *) (hdr + 1);
717         key_info = WPA_GET_BE16(key->key_info);
718         key_data_length = WPA_GET_BE16(key->key_data_length);
719         if (key_data_length > data_len - sizeof(*hdr) - sizeof(*key)) {
720                 wpa_printf(MSG_INFO, "WPA: Invalid EAPOL-Key frame - "
721                            "key_data overflow (%d > %lu)",
722                            key_data_length,
723                            (unsigned long) (data_len - sizeof(*hdr) -
724                                             sizeof(*key)));
725                 return;
726         }
727
728         if (sm->wpa == WPA_VERSION_WPA2) {
729                 if (key->type != EAPOL_KEY_TYPE_RSN) {
730                         wpa_printf(MSG_DEBUG, "Ignore EAPOL-Key with "
731                                    "unexpected type %d in RSN mode",
732                                    key->type);
733                         return;
734                 }
735         } else {
736                 if (key->type != EAPOL_KEY_TYPE_WPA) {
737                         wpa_printf(MSG_DEBUG, "Ignore EAPOL-Key with "
738                                    "unexpected type %d in WPA mode",
739                                    key->type);
740                         return;
741                 }
742         }
743
744         wpa_hexdump(MSG_DEBUG, "WPA: Received Key Nonce", key->key_nonce,
745                     WPA_NONCE_LEN);
746         wpa_hexdump(MSG_DEBUG, "WPA: Received Replay Counter",
747                     key->replay_counter, WPA_REPLAY_COUNTER_LEN);
748
749         /* FIX: verify that the EAPOL-Key frame was encrypted if pairwise keys
750          * are set */
751
752         if ((key_info & (WPA_KEY_INFO_SMK_MESSAGE | WPA_KEY_INFO_REQUEST)) ==
753             (WPA_KEY_INFO_SMK_MESSAGE | WPA_KEY_INFO_REQUEST)) {
754                 if (key_info & WPA_KEY_INFO_ERROR) {
755                         msg = SMK_ERROR;
756                         msgtxt = "SMK Error";
757                 } else {
758                         msg = SMK_M1;
759                         msgtxt = "SMK M1";
760                 }
761         } else if (key_info & WPA_KEY_INFO_SMK_MESSAGE) {
762                 msg = SMK_M3;
763                 msgtxt = "SMK M3";
764         } else if (key_info & WPA_KEY_INFO_REQUEST) {
765                 msg = REQUEST;
766                 msgtxt = "Request";
767         } else if (!(key_info & WPA_KEY_INFO_KEY_TYPE)) {
768                 msg = GROUP_2;
769                 msgtxt = "2/2 Group";
770         } else if (key_data_length == 0) {
771                 msg = PAIRWISE_4;
772                 msgtxt = "4/4 Pairwise";
773         } else {
774                 msg = PAIRWISE_2;
775                 msgtxt = "2/4 Pairwise";
776         }
777
778         /* TODO: key_info type validation for PeerKey */
779         if (msg == REQUEST || msg == PAIRWISE_2 || msg == PAIRWISE_4 ||
780             msg == GROUP_2) {
781                 u16 ver = key_info & WPA_KEY_INFO_TYPE_MASK;
782                 if (sm->pairwise == WPA_CIPHER_CCMP) {
783                         if (wpa_use_aes_cmac(sm) &&
784                             ver != WPA_KEY_INFO_TYPE_AES_128_CMAC) {
785                                 wpa_auth_logger(wpa_auth, sm->addr,
786                                                 LOGGER_WARNING,
787                                                 "advertised support for "
788                                                 "AES-128-CMAC, but did not "
789                                                 "use it");
790                                 return;
791                         }
792
793                         if (!wpa_use_aes_cmac(sm) &&
794                             ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
795                                 wpa_auth_logger(wpa_auth, sm->addr,
796                                                 LOGGER_WARNING,
797                                                 "did not use HMAC-SHA1-AES "
798                                                 "with CCMP");
799                                 return;
800                         }
801                 }
802         }
803
804         if (key_info & WPA_KEY_INFO_REQUEST) {
805                 if (sm->req_replay_counter_used &&
806                     os_memcmp(key->replay_counter, sm->req_replay_counter,
807                               WPA_REPLAY_COUNTER_LEN) <= 0) {
808                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_WARNING,
809                                         "received EAPOL-Key request with "
810                                         "replayed counter");
811                         return;
812                 }
813         }
814
815         if (!(key_info & WPA_KEY_INFO_REQUEST) &&
816             !wpa_replay_counter_valid(sm, key->replay_counter)) {
817                 int i;
818                 wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
819                                  "received EAPOL-Key %s with unexpected "
820                                  "replay counter", msgtxt);
821                 for (i = 0; i < RSNA_MAX_EAPOL_RETRIES; i++) {
822                         if (!sm->key_replay[i].valid)
823                                 break;
824                         wpa_hexdump(MSG_DEBUG, "pending replay counter",
825                                     sm->key_replay[i].counter,
826                                     WPA_REPLAY_COUNTER_LEN);
827                 }
828                 wpa_hexdump(MSG_DEBUG, "received replay counter",
829                             key->replay_counter, WPA_REPLAY_COUNTER_LEN);
830                 return;
831         }
832
833         switch (msg) {
834         case PAIRWISE_2:
835                 if (sm->wpa_ptk_state != WPA_PTK_PTKSTART &&
836                     sm->wpa_ptk_state != WPA_PTK_PTKCALCNEGOTIATING) {
837                         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
838                                          "received EAPOL-Key msg 2/4 in "
839                                          "invalid state (%d) - dropped",
840                                          sm->wpa_ptk_state);
841                         return;
842                 }
843                 random_add_randomness(key->key_nonce, WPA_NONCE_LEN);
844                 if (sm->group->reject_4way_hs_for_entropy) {
845                         /*
846                          * The system did not have enough entropy to generate
847                          * strong random numbers. Reject the first 4-way
848                          * handshake(s) and collect some entropy based on the
849                          * information from it. Once enough entropy is
850                          * available, the next atempt will trigger GMK/Key
851                          * Counter update and the station will be allowed to
852                          * continue.
853                          */
854                         wpa_printf(MSG_DEBUG, "WPA: Reject 4-way handshake to "
855                                    "collect more entropy for random number "
856                                    "generation");
857                         sm->group->reject_4way_hs_for_entropy = FALSE;
858                         random_mark_pool_ready();
859                         sm->group->first_sta_seen = FALSE;
860                         wpa_sta_disconnect(wpa_auth, sm->addr);
861                         return;
862                 }
863                 if (wpa_parse_kde_ies((u8 *) (key + 1), key_data_length,
864                                       &kde) < 0) {
865                         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
866                                          "received EAPOL-Key msg 2/4 with "
867                                          "invalid Key Data contents");
868                         return;
869                 }
870                 if (kde.rsn_ie) {
871                         eapol_key_ie = kde.rsn_ie;
872                         eapol_key_ie_len = kde.rsn_ie_len;
873                 } else {
874                         eapol_key_ie = kde.wpa_ie;
875                         eapol_key_ie_len = kde.wpa_ie_len;
876                 }
877                 ft = sm->wpa == WPA_VERSION_WPA2 &&
878                         wpa_key_mgmt_ft(sm->wpa_key_mgmt);
879                 if (sm->wpa_ie == NULL ||
880                     wpa_compare_rsn_ie(ft,
881                                        sm->wpa_ie, sm->wpa_ie_len,
882                                        eapol_key_ie, eapol_key_ie_len)) {
883                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
884                                         "WPA IE from (Re)AssocReq did not "
885                                         "match with msg 2/4");
886                         if (sm->wpa_ie) {
887                                 wpa_hexdump(MSG_DEBUG, "WPA IE in AssocReq",
888                                             sm->wpa_ie, sm->wpa_ie_len);
889                         }
890                         wpa_hexdump(MSG_DEBUG, "WPA IE in msg 2/4",
891                                     eapol_key_ie, eapol_key_ie_len);
892                         /* MLME-DEAUTHENTICATE.request */
893                         wpa_sta_disconnect(wpa_auth, sm->addr);
894                         return;
895                 }
896 #ifdef CONFIG_IEEE80211R
897                 if (ft && ft_check_msg_2_of_4(wpa_auth, sm, &kde) < 0) {
898                         wpa_sta_disconnect(wpa_auth, sm->addr);
899                         return;
900                 }
901 #endif /* CONFIG_IEEE80211R */
902                 break;
903         case PAIRWISE_4:
904                 if (sm->wpa_ptk_state != WPA_PTK_PTKINITNEGOTIATING ||
905                     !sm->PTK_valid) {
906                         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
907                                          "received EAPOL-Key msg 4/4 in "
908                                          "invalid state (%d) - dropped",
909                                          sm->wpa_ptk_state);
910                         return;
911                 }
912                 break;
913         case GROUP_2:
914                 if (sm->wpa_ptk_group_state != WPA_PTK_GROUP_REKEYNEGOTIATING
915                     || !sm->PTK_valid) {
916                         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_INFO,
917                                          "received EAPOL-Key msg 2/2 in "
918                                          "invalid state (%d) - dropped",
919                                          sm->wpa_ptk_group_state);
920                         return;
921                 }
922                 break;
923 #ifdef CONFIG_PEERKEY
924         case SMK_M1:
925         case SMK_M3:
926         case SMK_ERROR:
927                 if (!wpa_auth->conf.peerkey) {
928                         wpa_printf(MSG_DEBUG, "RSN: SMK M1/M3/Error, but "
929                                    "PeerKey use disabled - ignoring message");
930                         return;
931                 }
932                 if (!sm->PTK_valid) {
933                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
934                                         "received EAPOL-Key msg SMK in "
935                                         "invalid state - dropped");
936                         return;
937                 }
938                 break;
939 #else /* CONFIG_PEERKEY */
940         case SMK_M1:
941         case SMK_M3:
942         case SMK_ERROR:
943                 return; /* STSL disabled - ignore SMK messages */
944 #endif /* CONFIG_PEERKEY */
945         case REQUEST:
946                 break;
947         }
948
949         wpa_auth_vlogger(wpa_auth, sm->addr, LOGGER_DEBUG,
950                          "received EAPOL-Key frame (%s)", msgtxt);
951
952         if (key_info & WPA_KEY_INFO_ACK) {
953                 wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
954                                 "received invalid EAPOL-Key: Key Ack set");
955                 return;
956         }
957
958         if (!(key_info & WPA_KEY_INFO_MIC)) {
959                 wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
960                                 "received invalid EAPOL-Key: Key MIC not set");
961                 return;
962         }
963
964         sm->MICVerified = FALSE;
965         if (sm->PTK_valid) {
966                 if (wpa_verify_key_mic(&sm->PTK, data, data_len)) {
967                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
968                                         "received EAPOL-Key with invalid MIC");
969                         return;
970                 }
971                 sm->MICVerified = TRUE;
972                 eloop_cancel_timeout(wpa_send_eapol_timeout, wpa_auth, sm);
973                 sm->pending_1_of_4_timeout = 0;
974         }
975
976         if (key_info & WPA_KEY_INFO_REQUEST) {
977                 if (sm->MICVerified) {
978                         sm->req_replay_counter_used = 1;
979                         os_memcpy(sm->req_replay_counter, key->replay_counter,
980                                   WPA_REPLAY_COUNTER_LEN);
981                 } else {
982                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
983                                         "received EAPOL-Key request with "
984                                         "invalid MIC");
985                         return;
986                 }
987
988                 /*
989                  * TODO: should decrypt key data field if encryption was used;
990                  * even though MAC address KDE is not normally encrypted,
991                  * supplicant is allowed to encrypt it.
992                  */
993                 if (msg == SMK_ERROR) {
994 #ifdef CONFIG_PEERKEY
995                         wpa_smk_error(wpa_auth, sm, key);
996 #endif /* CONFIG_PEERKEY */
997                         return;
998                 } else if (key_info & WPA_KEY_INFO_ERROR) {
999                         /* Supplicant reported a Michael MIC error */
1000                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
1001                                         "received EAPOL-Key Error Request "
1002                                         "(STA detected Michael MIC failure)");
1003                         wpa_auth_mic_failure_report(wpa_auth, sm->addr);
1004                         sm->dot11RSNAStatsTKIPRemoteMICFailures++;
1005                         wpa_auth->dot11RSNAStatsTKIPRemoteMICFailures++;
1006                         /* Error report is not a request for a new key
1007                          * handshake, but since Authenticator may do it, let's
1008                          * change the keys now anyway. */
1009                         wpa_request_new_ptk(sm);
1010                 } else if (key_info & WPA_KEY_INFO_KEY_TYPE) {
1011                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
1012                                         "received EAPOL-Key Request for new "
1013                                         "4-Way Handshake");
1014                         wpa_request_new_ptk(sm);
1015 #ifdef CONFIG_PEERKEY
1016                 } else if (msg == SMK_M1) {
1017                         wpa_smk_m1(wpa_auth, sm, key);
1018 #endif /* CONFIG_PEERKEY */
1019                 } else if (key_data_length > 0 &&
1020                            wpa_parse_kde_ies((const u8 *) (key + 1),
1021                                              key_data_length, &kde) == 0 &&
1022                            kde.mac_addr) {
1023                 } else {
1024                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_INFO,
1025                                         "received EAPOL-Key Request for GTK "
1026                                         "rekeying");
1027                         /* FIX: why was this triggering PTK rekeying for the
1028                          * STA that requested Group Key rekeying?? */
1029                         /* wpa_request_new_ptk(sta->wpa_sm); */
1030                         eloop_cancel_timeout(wpa_rekey_gtk, wpa_auth, NULL);
1031                         wpa_rekey_gtk(wpa_auth, NULL);
1032                 }
1033         } else {
1034                 /* Do not allow the same key replay counter to be reused. This
1035                  * does also invalidate all other pending replay counters if
1036                  * retransmissions were used, i.e., we will only process one of
1037                  * the pending replies and ignore rest if more than one is
1038                  * received. */
1039                 sm->key_replay[0].valid = FALSE;
1040         }
1041
1042 #ifdef CONFIG_PEERKEY
1043         if (msg == SMK_M3) {
1044                 wpa_smk_m3(wpa_auth, sm, key);
1045                 return;
1046         }
1047 #endif /* CONFIG_PEERKEY */
1048
1049         os_free(sm->last_rx_eapol_key);
1050         sm->last_rx_eapol_key = os_malloc(data_len);
1051         if (sm->last_rx_eapol_key == NULL)
1052                 return;
1053         os_memcpy(sm->last_rx_eapol_key, data, data_len);
1054         sm->last_rx_eapol_key_len = data_len;
1055
1056         sm->EAPOLKeyReceived = TRUE;
1057         sm->EAPOLKeyPairwise = !!(key_info & WPA_KEY_INFO_KEY_TYPE);
1058         sm->EAPOLKeyRequest = !!(key_info & WPA_KEY_INFO_REQUEST);
1059         os_memcpy(sm->SNonce, key->key_nonce, WPA_NONCE_LEN);
1060         wpa_sm_step(sm);
1061 }
1062
1063
1064 static int wpa_gmk_to_gtk(const u8 *gmk, const char *label, const u8 *addr,
1065                           const u8 *gnonce, u8 *gtk, size_t gtk_len)
1066 {
1067         u8 data[ETH_ALEN + WPA_NONCE_LEN + 8 + 16];
1068         u8 *pos;
1069         int ret = 0;
1070
1071         /* GTK = PRF-X(GMK, "Group key expansion",
1072          *      AA || GNonce || Time || random data)
1073          * The example described in the IEEE 802.11 standard uses only AA and
1074          * GNonce as inputs here. Add some more entropy since this derivation
1075          * is done only at the Authenticator and as such, does not need to be
1076          * exactly same.
1077          */
1078         os_memcpy(data, addr, ETH_ALEN);
1079         os_memcpy(data + ETH_ALEN, gnonce, WPA_NONCE_LEN);
1080         pos = data + ETH_ALEN + WPA_NONCE_LEN;
1081         wpa_get_ntp_timestamp(pos);
1082         pos += 8;
1083         if (random_get_bytes(pos, 16) < 0)
1084                 ret = -1;
1085
1086 #ifdef CONFIG_IEEE80211W
1087         sha256_prf(gmk, WPA_GMK_LEN, label, data, sizeof(data), gtk, gtk_len);
1088 #else /* CONFIG_IEEE80211W */
1089         if (sha1_prf(gmk, WPA_GMK_LEN, label, data, sizeof(data), gtk, gtk_len)
1090             < 0)
1091                 ret = -1;
1092 #endif /* CONFIG_IEEE80211W */
1093
1094         return ret;
1095 }
1096
1097
1098 static void wpa_send_eapol_timeout(void *eloop_ctx, void *timeout_ctx)
1099 {
1100         struct wpa_authenticator *wpa_auth = eloop_ctx;
1101         struct wpa_state_machine *sm = timeout_ctx;
1102
1103         sm->pending_1_of_4_timeout = 0;
1104         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG, "EAPOL-Key timeout");
1105         sm->TimeoutEvt = TRUE;
1106         wpa_sm_step(sm);
1107 }
1108
1109
1110 void __wpa_send_eapol(struct wpa_authenticator *wpa_auth,
1111                       struct wpa_state_machine *sm, int key_info,
1112                       const u8 *key_rsc, const u8 *nonce,
1113                       const u8 *kde, size_t kde_len,
1114                       int keyidx, int encr, int force_version)
1115 {
1116         struct ieee802_1x_hdr *hdr;
1117         struct wpa_eapol_key *key;
1118         size_t len;
1119         int alg;
1120         int key_data_len, pad_len = 0;
1121         u8 *buf, *pos;
1122         int version, pairwise;
1123         int i;
1124
1125         len = sizeof(struct ieee802_1x_hdr) + sizeof(struct wpa_eapol_key);
1126
1127         if (force_version)
1128                 version = force_version;
1129         else if (wpa_use_aes_cmac(sm))
1130                 version = WPA_KEY_INFO_TYPE_AES_128_CMAC;
1131         else if (sm->pairwise == WPA_CIPHER_CCMP)
1132                 version = WPA_KEY_INFO_TYPE_HMAC_SHA1_AES;
1133         else
1134                 version = WPA_KEY_INFO_TYPE_HMAC_MD5_RC4;
1135
1136         pairwise = key_info & WPA_KEY_INFO_KEY_TYPE;
1137
1138         wpa_printf(MSG_DEBUG, "WPA: Send EAPOL(version=%d secure=%d mic=%d "
1139                    "ack=%d install=%d pairwise=%d kde_len=%lu keyidx=%d "
1140                    "encr=%d)",
1141                    version,
1142                    (key_info & WPA_KEY_INFO_SECURE) ? 1 : 0,
1143                    (key_info & WPA_KEY_INFO_MIC) ? 1 : 0,
1144                    (key_info & WPA_KEY_INFO_ACK) ? 1 : 0,
1145                    (key_info & WPA_KEY_INFO_INSTALL) ? 1 : 0,
1146                    pairwise, (unsigned long) kde_len, keyidx, encr);
1147
1148         key_data_len = kde_len;
1149
1150         if ((version == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES ||
1151              version == WPA_KEY_INFO_TYPE_AES_128_CMAC) && encr) {
1152                 pad_len = key_data_len % 8;
1153                 if (pad_len)
1154                         pad_len = 8 - pad_len;
1155                 key_data_len += pad_len + 8;
1156         }
1157
1158         len += key_data_len;
1159
1160         hdr = os_zalloc(len);
1161         if (hdr == NULL)
1162                 return;
1163         hdr->version = wpa_auth->conf.eapol_version;
1164         hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
1165         hdr->length = host_to_be16(len  - sizeof(*hdr));
1166         key = (struct wpa_eapol_key *) (hdr + 1);
1167
1168         key->type = sm->wpa == WPA_VERSION_WPA2 ?
1169                 EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
1170         key_info |= version;
1171         if (encr && sm->wpa == WPA_VERSION_WPA2)
1172                 key_info |= WPA_KEY_INFO_ENCR_KEY_DATA;
1173         if (sm->wpa != WPA_VERSION_WPA2)
1174                 key_info |= keyidx << WPA_KEY_INFO_KEY_INDEX_SHIFT;
1175         WPA_PUT_BE16(key->key_info, key_info);
1176
1177         alg = pairwise ? sm->pairwise : wpa_auth->conf.wpa_group;
1178         switch (alg) {
1179         case WPA_CIPHER_CCMP:
1180                 WPA_PUT_BE16(key->key_length, 16);
1181                 break;
1182         case WPA_CIPHER_TKIP:
1183                 WPA_PUT_BE16(key->key_length, 32);
1184                 break;
1185         case WPA_CIPHER_WEP40:
1186                 WPA_PUT_BE16(key->key_length, 5);
1187                 break;
1188         case WPA_CIPHER_WEP104:
1189                 WPA_PUT_BE16(key->key_length, 13);
1190                 break;
1191         }
1192         if (key_info & WPA_KEY_INFO_SMK_MESSAGE)
1193                 WPA_PUT_BE16(key->key_length, 0);
1194
1195         /* FIX: STSL: what to use as key_replay_counter? */
1196         for (i = RSNA_MAX_EAPOL_RETRIES - 1; i > 0; i--) {
1197                 sm->key_replay[i].valid = sm->key_replay[i - 1].valid;
1198                 os_memcpy(sm->key_replay[i].counter,
1199                           sm->key_replay[i - 1].counter,
1200                           WPA_REPLAY_COUNTER_LEN);
1201         }
1202         inc_byte_array(sm->key_replay[0].counter, WPA_REPLAY_COUNTER_LEN);
1203         os_memcpy(key->replay_counter, sm->key_replay[0].counter,
1204                   WPA_REPLAY_COUNTER_LEN);
1205         sm->key_replay[0].valid = TRUE;
1206
1207         if (nonce)
1208                 os_memcpy(key->key_nonce, nonce, WPA_NONCE_LEN);
1209
1210         if (key_rsc)
1211                 os_memcpy(key->key_rsc, key_rsc, WPA_KEY_RSC_LEN);
1212
1213         if (kde && !encr) {
1214                 os_memcpy(key + 1, kde, kde_len);
1215                 WPA_PUT_BE16(key->key_data_length, kde_len);
1216         } else if (encr && kde) {
1217                 buf = os_zalloc(key_data_len);
1218                 if (buf == NULL) {
1219                         os_free(hdr);
1220                         return;
1221                 }
1222                 pos = buf;
1223                 os_memcpy(pos, kde, kde_len);
1224                 pos += kde_len;
1225
1226                 if (pad_len)
1227                         *pos++ = 0xdd;
1228
1229                 wpa_hexdump_key(MSG_DEBUG, "Plaintext EAPOL-Key Key Data",
1230                                 buf, key_data_len);
1231                 if (version == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES ||
1232                     version == WPA_KEY_INFO_TYPE_AES_128_CMAC) {
1233                         if (aes_wrap(sm->PTK.kek, (key_data_len - 8) / 8, buf,
1234                                      (u8 *) (key + 1))) {
1235                                 os_free(hdr);
1236                                 os_free(buf);
1237                                 return;
1238                         }
1239                         WPA_PUT_BE16(key->key_data_length, key_data_len);
1240                 } else {
1241                         u8 ek[32];
1242                         os_memcpy(key->key_iv,
1243                                   sm->group->Counter + WPA_NONCE_LEN - 16, 16);
1244                         inc_byte_array(sm->group->Counter, WPA_NONCE_LEN);
1245                         os_memcpy(ek, key->key_iv, 16);
1246                         os_memcpy(ek + 16, sm->PTK.kek, 16);
1247                         os_memcpy(key + 1, buf, key_data_len);
1248                         rc4_skip(ek, 32, 256, (u8 *) (key + 1), key_data_len);
1249                         WPA_PUT_BE16(key->key_data_length, key_data_len);
1250                 }
1251                 os_free(buf);
1252         }
1253
1254         if (key_info & WPA_KEY_INFO_MIC) {
1255                 if (!sm->PTK_valid) {
1256                         wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG,
1257                                         "PTK not valid when sending EAPOL-Key "
1258                                         "frame");
1259                         os_free(hdr);
1260                         return;
1261                 }
1262                 wpa_eapol_key_mic(sm->PTK.kck, version, (u8 *) hdr, len,
1263                                   key->key_mic);
1264         }
1265
1266         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_inc_EapolFramesTx,
1267                            1);
1268         wpa_auth_send_eapol(wpa_auth, sm->addr, (u8 *) hdr, len,
1269                             sm->pairwise_set);
1270         os_free(hdr);
1271 }
1272
1273
1274 static void wpa_send_eapol(struct wpa_authenticator *wpa_auth,
1275                            struct wpa_state_machine *sm, int key_info,
1276                            const u8 *key_rsc, const u8 *nonce,
1277                            const u8 *kde, size_t kde_len,
1278                            int keyidx, int encr)
1279 {
1280         int timeout_ms;
1281         int pairwise = key_info & WPA_KEY_INFO_KEY_TYPE;
1282         int ctr;
1283
1284         if (sm == NULL)
1285                 return;
1286
1287         __wpa_send_eapol(wpa_auth, sm, key_info, key_rsc, nonce, kde, kde_len,
1288                          keyidx, encr, 0);
1289
1290         ctr = pairwise ? sm->TimeoutCtr : sm->GTimeoutCtr;
1291         if (ctr == 1 && wpa_auth->conf.tx_status)
1292                 timeout_ms = eapol_key_timeout_first;
1293         else
1294                 timeout_ms = eapol_key_timeout_subseq;
1295         if (pairwise && ctr == 1 && !(key_info & WPA_KEY_INFO_MIC))
1296                 sm->pending_1_of_4_timeout = 1;
1297         wpa_printf(MSG_DEBUG, "WPA: Use EAPOL-Key timeout of %u ms (retry "
1298                    "counter %d)", timeout_ms, ctr);
1299         eloop_register_timeout(timeout_ms / 1000, (timeout_ms % 1000) * 1000,
1300                                wpa_send_eapol_timeout, wpa_auth, sm);
1301 }
1302
1303
1304 static int wpa_verify_key_mic(struct wpa_ptk *PTK, u8 *data, size_t data_len)
1305 {
1306         struct ieee802_1x_hdr *hdr;
1307         struct wpa_eapol_key *key;
1308         u16 key_info;
1309         int ret = 0;
1310         u8 mic[16];
1311
1312         if (data_len < sizeof(*hdr) + sizeof(*key))
1313                 return -1;
1314
1315         hdr = (struct ieee802_1x_hdr *) data;
1316         key = (struct wpa_eapol_key *) (hdr + 1);
1317         key_info = WPA_GET_BE16(key->key_info);
1318         os_memcpy(mic, key->key_mic, 16);
1319         os_memset(key->key_mic, 0, 16);
1320         if (wpa_eapol_key_mic(PTK->kck, key_info & WPA_KEY_INFO_TYPE_MASK,
1321                               data, data_len, key->key_mic) ||
1322             os_memcmp(mic, key->key_mic, 16) != 0)
1323                 ret = -1;
1324         os_memcpy(key->key_mic, mic, 16);
1325         return ret;
1326 }
1327
1328
1329 void wpa_remove_ptk(struct wpa_state_machine *sm)
1330 {
1331         sm->PTK_valid = FALSE;
1332         os_memset(&sm->PTK, 0, sizeof(sm->PTK));
1333         wpa_auth_set_key(sm->wpa_auth, 0, WPA_ALG_NONE, sm->addr, 0, NULL, 0);
1334         sm->pairwise_set = FALSE;
1335         eloop_cancel_timeout(wpa_rekey_ptk, sm->wpa_auth, sm);
1336 }
1337
1338
1339 int wpa_auth_sm_event(struct wpa_state_machine *sm, wpa_event event)
1340 {
1341         int remove_ptk = 1;
1342
1343         if (sm == NULL)
1344                 return -1;
1345
1346         wpa_auth_vlogger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
1347                          "event %d notification", event);
1348
1349         switch (event) {
1350         case WPA_AUTH:
1351         case WPA_ASSOC:
1352                 break;
1353         case WPA_DEAUTH:
1354         case WPA_DISASSOC:
1355                 sm->DeauthenticationRequest = TRUE;
1356                 break;
1357         case WPA_REAUTH:
1358         case WPA_REAUTH_EAPOL:
1359                 if (!sm->started) {
1360                         /*
1361                          * When using WPS, we may end up here if the STA
1362                          * manages to re-associate without the previous STA
1363                          * entry getting removed. Consequently, we need to make
1364                          * sure that the WPA state machines gets initialized
1365                          * properly at this point.
1366                          */
1367                         wpa_printf(MSG_DEBUG, "WPA state machine had not been "
1368                                    "started - initialize now");
1369                         sm->started = 1;
1370                         sm->Init = TRUE;
1371                         if (wpa_sm_step(sm) == 1)
1372                                 return 1; /* should not really happen */
1373                         sm->Init = FALSE;
1374                         sm->AuthenticationRequest = TRUE;
1375                         break;
1376                 }
1377                 if (sm->GUpdateStationKeys) {
1378                         /*
1379                          * Reauthentication cancels the pending group key
1380                          * update for this STA.
1381                          */
1382                         sm->group->GKeyDoneStations--;
1383                         sm->GUpdateStationKeys = FALSE;
1384                         sm->PtkGroupInit = TRUE;
1385                 }
1386                 sm->ReAuthenticationRequest = TRUE;
1387                 break;
1388         case WPA_ASSOC_FT:
1389 #ifdef CONFIG_IEEE80211R
1390                 wpa_printf(MSG_DEBUG, "FT: Retry PTK configuration "
1391                            "after association");
1392                 wpa_ft_install_ptk(sm);
1393
1394                 /* Using FT protocol, not WPA auth state machine */
1395                 sm->ft_completed = 1;
1396                 return 0;
1397 #else /* CONFIG_IEEE80211R */
1398                 break;
1399 #endif /* CONFIG_IEEE80211R */
1400         }
1401
1402 #ifdef CONFIG_IEEE80211R
1403         sm->ft_completed = 0;
1404 #endif /* CONFIG_IEEE80211R */
1405
1406 #ifdef CONFIG_IEEE80211W
1407         if (sm->mgmt_frame_prot && event == WPA_AUTH)
1408                 remove_ptk = 0;
1409 #endif /* CONFIG_IEEE80211W */
1410
1411         if (remove_ptk) {
1412                 sm->PTK_valid = FALSE;
1413                 os_memset(&sm->PTK, 0, sizeof(sm->PTK));
1414
1415                 if (event != WPA_REAUTH_EAPOL)
1416                         wpa_remove_ptk(sm);
1417         }
1418
1419         return wpa_sm_step(sm);
1420 }
1421
1422
1423 static enum wpa_alg wpa_alg_enum(int alg)
1424 {
1425         switch (alg) {
1426         case WPA_CIPHER_CCMP:
1427                 return WPA_ALG_CCMP;
1428         case WPA_CIPHER_TKIP:
1429                 return WPA_ALG_TKIP;
1430         case WPA_CIPHER_WEP104:
1431         case WPA_CIPHER_WEP40:
1432                 return WPA_ALG_WEP;
1433         default:
1434                 return WPA_ALG_NONE;
1435         }
1436 }
1437
1438
1439 SM_STATE(WPA_PTK, INITIALIZE)
1440 {
1441         SM_ENTRY_MA(WPA_PTK, INITIALIZE, wpa_ptk);
1442         if (sm->Init) {
1443                 /* Init flag is not cleared here, so avoid busy
1444                  * loop by claiming nothing changed. */
1445                 sm->changed = FALSE;
1446         }
1447
1448         sm->keycount = 0;
1449         if (sm->GUpdateStationKeys)
1450                 sm->group->GKeyDoneStations--;
1451         sm->GUpdateStationKeys = FALSE;
1452         if (sm->wpa == WPA_VERSION_WPA)
1453                 sm->PInitAKeys = FALSE;
1454         if (1 /* Unicast cipher supported AND (ESS OR ((IBSS or WDS) and
1455                * Local AA > Remote AA)) */) {
1456                 sm->Pair = TRUE;
1457         }
1458         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portEnabled, 0);
1459         wpa_remove_ptk(sm);
1460         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portValid, 0);
1461         sm->TimeoutCtr = 0;
1462         if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt)) {
1463                 wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
1464                                    WPA_EAPOL_authorized, 0);
1465         }
1466 }
1467
1468
1469 SM_STATE(WPA_PTK, DISCONNECT)
1470 {
1471         SM_ENTRY_MA(WPA_PTK, DISCONNECT, wpa_ptk);
1472         sm->Disconnect = FALSE;
1473         wpa_sta_disconnect(sm->wpa_auth, sm->addr);
1474 }
1475
1476
1477 SM_STATE(WPA_PTK, DISCONNECTED)
1478 {
1479         SM_ENTRY_MA(WPA_PTK, DISCONNECTED, wpa_ptk);
1480         sm->DeauthenticationRequest = FALSE;
1481 }
1482
1483
1484 SM_STATE(WPA_PTK, AUTHENTICATION)
1485 {
1486         SM_ENTRY_MA(WPA_PTK, AUTHENTICATION, wpa_ptk);
1487         os_memset(&sm->PTK, 0, sizeof(sm->PTK));
1488         sm->PTK_valid = FALSE;
1489         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portControl_Auto,
1490                            1);
1491         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portEnabled, 1);
1492         sm->AuthenticationRequest = FALSE;
1493 }
1494
1495
1496 static void wpa_group_first_station(struct wpa_authenticator *wpa_auth,
1497                                     struct wpa_group *group)
1498 {
1499         /*
1500          * System has run bit further than at the time hostapd was started
1501          * potentially very early during boot up. This provides better chances
1502          * of collecting more randomness on embedded systems. Re-initialize the
1503          * GMK and Counter here to improve their strength if there was not
1504          * enough entropy available immediately after system startup.
1505          */
1506         wpa_printf(MSG_DEBUG, "WPA: Re-initialize GMK/Counter on first "
1507                    "station");
1508         if (random_pool_ready() != 1) {
1509                 wpa_printf(MSG_INFO, "WPA: Not enough entropy in random pool "
1510                            "to proceed - reject first 4-way handshake");
1511                 group->reject_4way_hs_for_entropy = TRUE;
1512         }
1513         wpa_group_init_gmk_and_counter(wpa_auth, group);
1514         wpa_gtk_update(wpa_auth, group);
1515         wpa_group_config_group_keys(wpa_auth, group);
1516 }
1517
1518
1519 SM_STATE(WPA_PTK, AUTHENTICATION2)
1520 {
1521         SM_ENTRY_MA(WPA_PTK, AUTHENTICATION2, wpa_ptk);
1522
1523         if (!sm->group->first_sta_seen) {
1524                 wpa_group_first_station(sm->wpa_auth, sm->group);
1525                 sm->group->first_sta_seen = TRUE;
1526         }
1527
1528         os_memcpy(sm->ANonce, sm->group->Counter, WPA_NONCE_LEN);
1529         wpa_hexdump(MSG_DEBUG, "WPA: Assign ANonce", sm->ANonce,
1530                     WPA_NONCE_LEN);
1531         inc_byte_array(sm->group->Counter, WPA_NONCE_LEN);
1532         sm->ReAuthenticationRequest = FALSE;
1533         /* IEEE 802.11i does not clear TimeoutCtr here, but this is more
1534          * logical place than INITIALIZE since AUTHENTICATION2 can be
1535          * re-entered on ReAuthenticationRequest without going through
1536          * INITIALIZE. */
1537         sm->TimeoutCtr = 0;
1538 }
1539
1540
1541 SM_STATE(WPA_PTK, INITPMK)
1542 {
1543         u8 msk[2 * PMK_LEN];
1544         size_t len = 2 * PMK_LEN;
1545
1546         SM_ENTRY_MA(WPA_PTK, INITPMK, wpa_ptk);
1547 #ifdef CONFIG_IEEE80211R
1548         sm->xxkey_len = 0;
1549 #endif /* CONFIG_IEEE80211R */
1550         if (sm->pmksa) {
1551                 wpa_printf(MSG_DEBUG, "WPA: PMK from PMKSA cache");
1552                 os_memcpy(sm->PMK, sm->pmksa->pmk, PMK_LEN);
1553         } else if (wpa_auth_get_msk(sm->wpa_auth, sm->addr, msk, &len) == 0) {
1554                 wpa_printf(MSG_DEBUG, "WPA: PMK from EAPOL state machine "
1555                            "(len=%lu)", (unsigned long) len);
1556                 os_memcpy(sm->PMK, msk, PMK_LEN);
1557 #ifdef CONFIG_IEEE80211R
1558                 if (len >= 2 * PMK_LEN) {
1559                         os_memcpy(sm->xxkey, msk + PMK_LEN, PMK_LEN);
1560                         sm->xxkey_len = PMK_LEN;
1561                 }
1562 #endif /* CONFIG_IEEE80211R */
1563         } else {
1564                 wpa_printf(MSG_DEBUG, "WPA: Could not get PMK");
1565         }
1566
1567         sm->req_replay_counter_used = 0;
1568         /* IEEE 802.11i does not set keyRun to FALSE, but not doing this
1569          * will break reauthentication since EAPOL state machines may not be
1570          * get into AUTHENTICATING state that clears keyRun before WPA state
1571          * machine enters AUTHENTICATION2 state and goes immediately to INITPMK
1572          * state and takes PMK from the previously used AAA Key. This will
1573          * eventually fail in 4-Way Handshake because Supplicant uses PMK
1574          * derived from the new AAA Key. Setting keyRun = FALSE here seems to
1575          * be good workaround for this issue. */
1576         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyRun, 0);
1577 }
1578
1579
1580 SM_STATE(WPA_PTK, INITPSK)
1581 {
1582         const u8 *psk;
1583         SM_ENTRY_MA(WPA_PTK, INITPSK, wpa_ptk);
1584         psk = wpa_auth_get_psk(sm->wpa_auth, sm->addr, NULL);
1585         if (psk) {
1586                 os_memcpy(sm->PMK, psk, PMK_LEN);
1587 #ifdef CONFIG_IEEE80211R
1588                 os_memcpy(sm->xxkey, psk, PMK_LEN);
1589                 sm->xxkey_len = PMK_LEN;
1590 #endif /* CONFIG_IEEE80211R */
1591         }
1592         sm->req_replay_counter_used = 0;
1593 }
1594
1595
1596 SM_STATE(WPA_PTK, PTKSTART)
1597 {
1598         u8 buf[2 + RSN_SELECTOR_LEN + PMKID_LEN], *pmkid = NULL;
1599         size_t pmkid_len = 0;
1600
1601         SM_ENTRY_MA(WPA_PTK, PTKSTART, wpa_ptk);
1602         sm->PTKRequest = FALSE;
1603         sm->TimeoutEvt = FALSE;
1604
1605         sm->TimeoutCtr++;
1606         if (sm->TimeoutCtr > (int) dot11RSNAConfigPairwiseUpdateCount) {
1607                 /* No point in sending the EAPOL-Key - we will disconnect
1608                  * immediately following this. */
1609                 return;
1610         }
1611
1612         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
1613                         "sending 1/4 msg of 4-Way Handshake");
1614         /*
1615          * TODO: Could add PMKID even with WPA2-PSK, but only if there is only
1616          * one possible PSK for this STA.
1617          */
1618         if (sm->wpa == WPA_VERSION_WPA2 &&
1619             wpa_key_mgmt_wpa_ieee8021x(sm->wpa_key_mgmt)) {
1620                 pmkid = buf;
1621                 pmkid_len = 2 + RSN_SELECTOR_LEN + PMKID_LEN;
1622                 pmkid[0] = WLAN_EID_VENDOR_SPECIFIC;
1623                 pmkid[1] = RSN_SELECTOR_LEN + PMKID_LEN;
1624                 RSN_SELECTOR_PUT(&pmkid[2], RSN_KEY_DATA_PMKID);
1625                 if (sm->pmksa)
1626                         os_memcpy(&pmkid[2 + RSN_SELECTOR_LEN],
1627                                   sm->pmksa->pmkid, PMKID_LEN);
1628                 else {
1629                         /*
1630                          * Calculate PMKID since no PMKSA cache entry was
1631                          * available with pre-calculated PMKID.
1632                          */
1633                         rsn_pmkid(sm->PMK, PMK_LEN, sm->wpa_auth->addr,
1634                                   sm->addr, &pmkid[2 + RSN_SELECTOR_LEN],
1635                                   wpa_key_mgmt_sha256(sm->wpa_key_mgmt));
1636                 }
1637         }
1638         wpa_send_eapol(sm->wpa_auth, sm,
1639                        WPA_KEY_INFO_ACK | WPA_KEY_INFO_KEY_TYPE, NULL,
1640                        sm->ANonce, pmkid, pmkid_len, 0, 0);
1641 }
1642
1643
1644 static int wpa_derive_ptk(struct wpa_state_machine *sm, const u8 *pmk,
1645                           struct wpa_ptk *ptk)
1646 {
1647         size_t ptk_len = sm->pairwise == WPA_CIPHER_CCMP ? 48 : 64;
1648 #ifdef CONFIG_IEEE80211R
1649         if (wpa_key_mgmt_ft(sm->wpa_key_mgmt))
1650                 return wpa_auth_derive_ptk_ft(sm, pmk, ptk, ptk_len);
1651 #endif /* CONFIG_IEEE80211R */
1652
1653         wpa_pmk_to_ptk(pmk, PMK_LEN, "Pairwise key expansion",
1654                        sm->wpa_auth->addr, sm->addr, sm->ANonce, sm->SNonce,
1655                        (u8 *) ptk, ptk_len,
1656                        wpa_key_mgmt_sha256(sm->wpa_key_mgmt));
1657
1658         return 0;
1659 }
1660
1661
1662 SM_STATE(WPA_PTK, PTKCALCNEGOTIATING)
1663 {
1664         struct wpa_ptk PTK;
1665         int ok = 0;
1666         const u8 *pmk = NULL;
1667
1668         SM_ENTRY_MA(WPA_PTK, PTKCALCNEGOTIATING, wpa_ptk);
1669         sm->EAPOLKeyReceived = FALSE;
1670
1671         /* WPA with IEEE 802.1X: use the derived PMK from EAP
1672          * WPA-PSK: iterate through possible PSKs and select the one matching
1673          * the packet */
1674         for (;;) {
1675                 if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt)) {
1676                         pmk = wpa_auth_get_psk(sm->wpa_auth, sm->addr, pmk);
1677                         if (pmk == NULL)
1678                                 break;
1679                 } else
1680                         pmk = sm->PMK;
1681
1682                 wpa_derive_ptk(sm, pmk, &PTK);
1683
1684                 if (wpa_verify_key_mic(&PTK, sm->last_rx_eapol_key,
1685                                        sm->last_rx_eapol_key_len) == 0) {
1686                         ok = 1;
1687                         break;
1688                 }
1689
1690                 if (!wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt))
1691                         break;
1692         }
1693
1694         if (!ok) {
1695                 wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
1696                                 "invalid MIC in msg 2/4 of 4-Way Handshake");
1697                 return;
1698         }
1699
1700 #ifdef CONFIG_IEEE80211R
1701         if (sm->wpa == WPA_VERSION_WPA2 && wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
1702                 /*
1703                  * Verify that PMKR1Name from EAPOL-Key message 2/4 matches
1704                  * with the value we derived.
1705                  */
1706                 if (os_memcmp(sm->sup_pmk_r1_name, sm->pmk_r1_name,
1707                               WPA_PMK_NAME_LEN) != 0) {
1708                         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
1709                                         "PMKR1Name mismatch in FT 4-way "
1710                                         "handshake");
1711                         wpa_hexdump(MSG_DEBUG, "FT: PMKR1Name from "
1712                                     "Supplicant",
1713                                     sm->sup_pmk_r1_name, WPA_PMK_NAME_LEN);
1714                         wpa_hexdump(MSG_DEBUG, "FT: Derived PMKR1Name",
1715                                     sm->pmk_r1_name, WPA_PMK_NAME_LEN);
1716                         return;
1717                 }
1718         }
1719 #endif /* CONFIG_IEEE80211R */
1720
1721         sm->pending_1_of_4_timeout = 0;
1722         eloop_cancel_timeout(wpa_send_eapol_timeout, sm->wpa_auth, sm);
1723
1724         if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt)) {
1725                 /* PSK may have changed from the previous choice, so update
1726                  * state machine data based on whatever PSK was selected here.
1727                  */
1728                 os_memcpy(sm->PMK, pmk, PMK_LEN);
1729         }
1730
1731         sm->MICVerified = TRUE;
1732
1733         os_memcpy(&sm->PTK, &PTK, sizeof(PTK));
1734         sm->PTK_valid = TRUE;
1735 }
1736
1737
1738 SM_STATE(WPA_PTK, PTKCALCNEGOTIATING2)
1739 {
1740         SM_ENTRY_MA(WPA_PTK, PTKCALCNEGOTIATING2, wpa_ptk);
1741         sm->TimeoutCtr = 0;
1742 }
1743
1744
1745 #ifdef CONFIG_IEEE80211W
1746
1747 static int ieee80211w_kde_len(struct wpa_state_machine *sm)
1748 {
1749         if (sm->mgmt_frame_prot) {
1750                 return 2 + RSN_SELECTOR_LEN + sizeof(struct wpa_igtk_kde);
1751         }
1752
1753         return 0;
1754 }
1755
1756
1757 static u8 * ieee80211w_kde_add(struct wpa_state_machine *sm, u8 *pos)
1758 {
1759         struct wpa_igtk_kde igtk;
1760         struct wpa_group *gsm = sm->group;
1761
1762         if (!sm->mgmt_frame_prot)
1763                 return pos;
1764
1765         igtk.keyid[0] = gsm->GN_igtk;
1766         igtk.keyid[1] = 0;
1767         if (gsm->wpa_group_state != WPA_GROUP_SETKEYSDONE ||
1768             wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN_igtk, igtk.pn) < 0)
1769                 os_memset(igtk.pn, 0, sizeof(igtk.pn));
1770         os_memcpy(igtk.igtk, gsm->IGTK[gsm->GN_igtk - 4], WPA_IGTK_LEN);
1771         pos = wpa_add_kde(pos, RSN_KEY_DATA_IGTK,
1772                           (const u8 *) &igtk, sizeof(igtk), NULL, 0);
1773
1774         return pos;
1775 }
1776
1777 #else /* CONFIG_IEEE80211W */
1778
1779 static int ieee80211w_kde_len(struct wpa_state_machine *sm)
1780 {
1781         return 0;
1782 }
1783
1784
1785 static u8 * ieee80211w_kde_add(struct wpa_state_machine *sm, u8 *pos)
1786 {
1787         return pos;
1788 }
1789
1790 #endif /* CONFIG_IEEE80211W */
1791
1792
1793 SM_STATE(WPA_PTK, PTKINITNEGOTIATING)
1794 {
1795         u8 rsc[WPA_KEY_RSC_LEN], *_rsc, *gtk, *kde, *pos;
1796         size_t gtk_len, kde_len;
1797         struct wpa_group *gsm = sm->group;
1798         u8 *wpa_ie;
1799         int wpa_ie_len, secure, keyidx, encr = 0;
1800
1801         SM_ENTRY_MA(WPA_PTK, PTKINITNEGOTIATING, wpa_ptk);
1802         sm->TimeoutEvt = FALSE;
1803
1804         sm->TimeoutCtr++;
1805         if (sm->TimeoutCtr > (int) dot11RSNAConfigPairwiseUpdateCount) {
1806                 /* No point in sending the EAPOL-Key - we will disconnect
1807                  * immediately following this. */
1808                 return;
1809         }
1810
1811         /* Send EAPOL(1, 1, 1, Pair, P, RSC, ANonce, MIC(PTK), RSNIE, [MDIE],
1812            GTK[GN], IGTK, [FTIE], [TIE * 2])
1813          */
1814         os_memset(rsc, 0, WPA_KEY_RSC_LEN);
1815         wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN, rsc);
1816         /* If FT is used, wpa_auth->wpa_ie includes both RSNIE and MDIE */
1817         wpa_ie = sm->wpa_auth->wpa_ie;
1818         wpa_ie_len = sm->wpa_auth->wpa_ie_len;
1819         if (sm->wpa == WPA_VERSION_WPA &&
1820             (sm->wpa_auth->conf.wpa & WPA_PROTO_RSN) &&
1821             wpa_ie_len > wpa_ie[1] + 2 && wpa_ie[0] == WLAN_EID_RSN) {
1822                 /* WPA-only STA, remove RSN IE */
1823                 wpa_ie = wpa_ie + wpa_ie[1] + 2;
1824                 wpa_ie_len = wpa_ie[1] + 2;
1825         }
1826         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
1827                         "sending 3/4 msg of 4-Way Handshake");
1828         if (sm->wpa == WPA_VERSION_WPA2) {
1829                 /* WPA2 send GTK in the 4-way handshake */
1830                 secure = 1;
1831                 gtk = gsm->GTK[gsm->GN - 1];
1832                 gtk_len = gsm->GTK_len;
1833                 keyidx = gsm->GN;
1834                 _rsc = rsc;
1835                 encr = 1;
1836         } else {
1837                 /* WPA does not include GTK in msg 3/4 */
1838                 secure = 0;
1839                 gtk = NULL;
1840                 gtk_len = 0;
1841                 keyidx = 0;
1842                 _rsc = NULL;
1843         }
1844
1845         kde_len = wpa_ie_len + ieee80211w_kde_len(sm);
1846         if (gtk)
1847                 kde_len += 2 + RSN_SELECTOR_LEN + 2 + gtk_len;
1848 #ifdef CONFIG_IEEE80211R
1849         if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
1850                 kde_len += 2 + PMKID_LEN; /* PMKR1Name into RSN IE */
1851                 kde_len += 300; /* FTIE + 2 * TIE */
1852         }
1853 #endif /* CONFIG_IEEE80211R */
1854         kde = os_malloc(kde_len);
1855         if (kde == NULL)
1856                 return;
1857
1858         pos = kde;
1859         os_memcpy(pos, wpa_ie, wpa_ie_len);
1860         pos += wpa_ie_len;
1861 #ifdef CONFIG_IEEE80211R
1862         if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
1863                 int res = wpa_insert_pmkid(kde, pos - kde, sm->pmk_r1_name);
1864                 if (res < 0) {
1865                         wpa_printf(MSG_ERROR, "FT: Failed to insert "
1866                                    "PMKR1Name into RSN IE in EAPOL-Key data");
1867                         os_free(kde);
1868                         return;
1869                 }
1870                 pos += res;
1871         }
1872 #endif /* CONFIG_IEEE80211R */
1873         if (gtk) {
1874                 u8 hdr[2];
1875                 hdr[0] = keyidx & 0x03;
1876                 hdr[1] = 0;
1877                 pos = wpa_add_kde(pos, RSN_KEY_DATA_GROUPKEY, hdr, 2,
1878                                   gtk, gtk_len);
1879         }
1880         pos = ieee80211w_kde_add(sm, pos);
1881
1882 #ifdef CONFIG_IEEE80211R
1883         if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
1884                 int res;
1885                 struct wpa_auth_config *conf;
1886
1887                 conf = &sm->wpa_auth->conf;
1888                 res = wpa_write_ftie(conf, conf->r0_key_holder,
1889                                      conf->r0_key_holder_len,
1890                                      NULL, NULL, pos, kde + kde_len - pos,
1891                                      NULL, 0);
1892                 if (res < 0) {
1893                         wpa_printf(MSG_ERROR, "FT: Failed to insert FTIE "
1894                                    "into EAPOL-Key Key Data");
1895                         os_free(kde);
1896                         return;
1897                 }
1898                 pos += res;
1899
1900                 /* TIE[ReassociationDeadline] (TU) */
1901                 *pos++ = WLAN_EID_TIMEOUT_INTERVAL;
1902                 *pos++ = 5;
1903                 *pos++ = WLAN_TIMEOUT_REASSOC_DEADLINE;
1904                 WPA_PUT_LE32(pos, conf->reassociation_deadline);
1905                 pos += 4;
1906
1907                 /* TIE[KeyLifetime] (seconds) */
1908                 *pos++ = WLAN_EID_TIMEOUT_INTERVAL;
1909                 *pos++ = 5;
1910                 *pos++ = WLAN_TIMEOUT_KEY_LIFETIME;
1911                 WPA_PUT_LE32(pos, conf->r0_key_lifetime * 60);
1912                 pos += 4;
1913         }
1914 #endif /* CONFIG_IEEE80211R */
1915
1916         wpa_send_eapol(sm->wpa_auth, sm,
1917                        (secure ? WPA_KEY_INFO_SECURE : 0) | WPA_KEY_INFO_MIC |
1918                        WPA_KEY_INFO_ACK | WPA_KEY_INFO_INSTALL |
1919                        WPA_KEY_INFO_KEY_TYPE,
1920                        _rsc, sm->ANonce, kde, pos - kde, keyidx, encr);
1921         os_free(kde);
1922 }
1923
1924
1925 SM_STATE(WPA_PTK, PTKINITDONE)
1926 {
1927         SM_ENTRY_MA(WPA_PTK, PTKINITDONE, wpa_ptk);
1928         sm->EAPOLKeyReceived = FALSE;
1929         if (sm->Pair) {
1930                 enum wpa_alg alg;
1931                 int klen;
1932                 if (sm->pairwise == WPA_CIPHER_TKIP) {
1933                         alg = WPA_ALG_TKIP;
1934                         klen = 32;
1935                 } else {
1936                         alg = WPA_ALG_CCMP;
1937                         klen = 16;
1938                 }
1939                 if (wpa_auth_set_key(sm->wpa_auth, 0, alg, sm->addr, 0,
1940                                      sm->PTK.tk1, klen)) {
1941                         wpa_sta_disconnect(sm->wpa_auth, sm->addr);
1942                         return;
1943                 }
1944                 /* FIX: MLME-SetProtection.Request(TA, Tx_Rx) */
1945                 sm->pairwise_set = TRUE;
1946
1947                 if (sm->wpa_auth->conf.wpa_ptk_rekey) {
1948                         eloop_cancel_timeout(wpa_rekey_ptk, sm->wpa_auth, sm);
1949                         eloop_register_timeout(sm->wpa_auth->conf.
1950                                                wpa_ptk_rekey, 0, wpa_rekey_ptk,
1951                                                sm->wpa_auth, sm);
1952                 }
1953
1954                 if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt)) {
1955                         wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
1956                                            WPA_EAPOL_authorized, 1);
1957                 }
1958         }
1959
1960         if (0 /* IBSS == TRUE */) {
1961                 sm->keycount++;
1962                 if (sm->keycount == 2) {
1963                         wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
1964                                            WPA_EAPOL_portValid, 1);
1965                 }
1966         } else {
1967                 wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portValid,
1968                                    1);
1969         }
1970         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyAvailable, 0);
1971         wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyDone, 1);
1972         if (sm->wpa == WPA_VERSION_WPA)
1973                 sm->PInitAKeys = TRUE;
1974         else
1975                 sm->has_GTK = TRUE;
1976         wpa_auth_vlogger(sm->wpa_auth, sm->addr, LOGGER_INFO,
1977                          "pairwise key handshake completed (%s)",
1978                          sm->wpa == WPA_VERSION_WPA ? "WPA" : "RSN");
1979
1980 #ifdef CONFIG_IEEE80211R
1981         wpa_ft_push_pmk_r1(sm->wpa_auth, sm->addr);
1982 #endif /* CONFIG_IEEE80211R */
1983 }
1984
1985
1986 SM_STEP(WPA_PTK)
1987 {
1988         struct wpa_authenticator *wpa_auth = sm->wpa_auth;
1989
1990         if (sm->Init)
1991                 SM_ENTER(WPA_PTK, INITIALIZE);
1992         else if (sm->Disconnect
1993                  /* || FIX: dot11RSNAConfigSALifetime timeout */) {
1994                 wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG,
1995                                 "WPA_PTK: sm->Disconnect");
1996                 SM_ENTER(WPA_PTK, DISCONNECT);
1997         }
1998         else if (sm->DeauthenticationRequest)
1999                 SM_ENTER(WPA_PTK, DISCONNECTED);
2000         else if (sm->AuthenticationRequest)
2001                 SM_ENTER(WPA_PTK, AUTHENTICATION);
2002         else if (sm->ReAuthenticationRequest)
2003                 SM_ENTER(WPA_PTK, AUTHENTICATION2);
2004         else if (sm->PTKRequest)
2005                 SM_ENTER(WPA_PTK, PTKSTART);
2006         else switch (sm->wpa_ptk_state) {
2007         case WPA_PTK_INITIALIZE:
2008                 break;
2009         case WPA_PTK_DISCONNECT:
2010                 SM_ENTER(WPA_PTK, DISCONNECTED);
2011                 break;
2012         case WPA_PTK_DISCONNECTED:
2013                 SM_ENTER(WPA_PTK, INITIALIZE);
2014                 break;
2015         case WPA_PTK_AUTHENTICATION:
2016                 SM_ENTER(WPA_PTK, AUTHENTICATION2);
2017                 break;
2018         case WPA_PTK_AUTHENTICATION2:
2019                 if (wpa_key_mgmt_wpa_ieee8021x(sm->wpa_key_mgmt) &&
2020                     wpa_auth_get_eapol(sm->wpa_auth, sm->addr,
2021                                        WPA_EAPOL_keyRun) > 0)
2022                         SM_ENTER(WPA_PTK, INITPMK);
2023                 else if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt)
2024                          /* FIX: && 802.1X::keyRun */)
2025                         SM_ENTER(WPA_PTK, INITPSK);
2026                 break;
2027         case WPA_PTK_INITPMK:
2028                 if (wpa_auth_get_eapol(sm->wpa_auth, sm->addr,
2029                                        WPA_EAPOL_keyAvailable) > 0)
2030                         SM_ENTER(WPA_PTK, PTKSTART);
2031                 else {
2032                         wpa_auth->dot11RSNA4WayHandshakeFailures++;
2033                         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_INFO,
2034                                         "INITPMK - keyAvailable = false");
2035                         SM_ENTER(WPA_PTK, DISCONNECT);
2036                 }
2037                 break;
2038         case WPA_PTK_INITPSK:
2039                 if (wpa_auth_get_psk(sm->wpa_auth, sm->addr, NULL))
2040                         SM_ENTER(WPA_PTK, PTKSTART);
2041                 else {
2042                         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_INFO,
2043                                         "no PSK configured for the STA");
2044                         wpa_auth->dot11RSNA4WayHandshakeFailures++;
2045                         SM_ENTER(WPA_PTK, DISCONNECT);
2046                 }
2047                 break;
2048         case WPA_PTK_PTKSTART:
2049                 if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
2050                     sm->EAPOLKeyPairwise)
2051                         SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING);
2052                 else if (sm->TimeoutCtr >
2053                          (int) dot11RSNAConfigPairwiseUpdateCount) {
2054                         wpa_auth->dot11RSNA4WayHandshakeFailures++;
2055                         wpa_auth_vlogger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2056                                          "PTKSTART: Retry limit %d reached",
2057                                          dot11RSNAConfigPairwiseUpdateCount);
2058                         SM_ENTER(WPA_PTK, DISCONNECT);
2059                 } else if (sm->TimeoutEvt)
2060                         SM_ENTER(WPA_PTK, PTKSTART);
2061                 break;
2062         case WPA_PTK_PTKCALCNEGOTIATING:
2063                 if (sm->MICVerified)
2064                         SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING2);
2065                 else if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
2066                          sm->EAPOLKeyPairwise)
2067                         SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING);
2068                 else if (sm->TimeoutEvt)
2069                         SM_ENTER(WPA_PTK, PTKSTART);
2070                 break;
2071         case WPA_PTK_PTKCALCNEGOTIATING2:
2072                 SM_ENTER(WPA_PTK, PTKINITNEGOTIATING);
2073                 break;
2074         case WPA_PTK_PTKINITNEGOTIATING:
2075                 if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
2076                     sm->EAPOLKeyPairwise && sm->MICVerified)
2077                         SM_ENTER(WPA_PTK, PTKINITDONE);
2078                 else if (sm->TimeoutCtr >
2079                          (int) dot11RSNAConfigPairwiseUpdateCount) {
2080                         wpa_auth->dot11RSNA4WayHandshakeFailures++;
2081                         wpa_auth_vlogger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2082                                          "PTKINITNEGOTIATING: Retry limit %d "
2083                                          "reached",
2084                                          dot11RSNAConfigPairwiseUpdateCount);
2085                         SM_ENTER(WPA_PTK, DISCONNECT);
2086                 } else if (sm->TimeoutEvt)
2087                         SM_ENTER(WPA_PTK, PTKINITNEGOTIATING);
2088                 break;
2089         case WPA_PTK_PTKINITDONE:
2090                 break;
2091         }
2092 }
2093
2094
2095 SM_STATE(WPA_PTK_GROUP, IDLE)
2096 {
2097         SM_ENTRY_MA(WPA_PTK_GROUP, IDLE, wpa_ptk_group);
2098         if (sm->Init) {
2099                 /* Init flag is not cleared here, so avoid busy
2100                  * loop by claiming nothing changed. */
2101                 sm->changed = FALSE;
2102         }
2103         sm->GTimeoutCtr = 0;
2104 }
2105
2106
2107 SM_STATE(WPA_PTK_GROUP, REKEYNEGOTIATING)
2108 {
2109         u8 rsc[WPA_KEY_RSC_LEN];
2110         struct wpa_group *gsm = sm->group;
2111         u8 *kde, *pos, hdr[2];
2112         size_t kde_len;
2113
2114         SM_ENTRY_MA(WPA_PTK_GROUP, REKEYNEGOTIATING, wpa_ptk_group);
2115
2116         sm->GTimeoutCtr++;
2117         if (sm->GTimeoutCtr > (int) dot11RSNAConfigGroupUpdateCount) {
2118                 /* No point in sending the EAPOL-Key - we will disconnect
2119                  * immediately following this. */
2120                 return;
2121         }
2122
2123         if (sm->wpa == WPA_VERSION_WPA)
2124                 sm->PInitAKeys = FALSE;
2125         sm->TimeoutEvt = FALSE;
2126         /* Send EAPOL(1, 1, 1, !Pair, G, RSC, GNonce, MIC(PTK), GTK[GN]) */
2127         os_memset(rsc, 0, WPA_KEY_RSC_LEN);
2128         if (gsm->wpa_group_state == WPA_GROUP_SETKEYSDONE)
2129                 wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN, rsc);
2130         wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2131                         "sending 1/2 msg of Group Key Handshake");
2132
2133         if (sm->wpa == WPA_VERSION_WPA2) {
2134                 kde_len = 2 + RSN_SELECTOR_LEN + 2 + gsm->GTK_len +
2135                         ieee80211w_kde_len(sm);
2136                 kde = os_malloc(kde_len);
2137                 if (kde == NULL)
2138                         return;
2139
2140                 pos = kde;
2141                 hdr[0] = gsm->GN & 0x03;
2142                 hdr[1] = 0;
2143                 pos = wpa_add_kde(pos, RSN_KEY_DATA_GROUPKEY, hdr, 2,
2144                                   gsm->GTK[gsm->GN - 1], gsm->GTK_len);
2145                 pos = ieee80211w_kde_add(sm, pos);
2146         } else {
2147                 kde = gsm->GTK[gsm->GN - 1];
2148                 pos = kde + gsm->GTK_len;
2149         }
2150
2151         wpa_send_eapol(sm->wpa_auth, sm,
2152                        WPA_KEY_INFO_SECURE | WPA_KEY_INFO_MIC |
2153                        WPA_KEY_INFO_ACK |
2154                        (!sm->Pair ? WPA_KEY_INFO_INSTALL : 0),
2155                        rsc, gsm->GNonce, kde, pos - kde, gsm->GN, 1);
2156         if (sm->wpa == WPA_VERSION_WPA2)
2157                 os_free(kde);
2158 }
2159
2160
2161 SM_STATE(WPA_PTK_GROUP, REKEYESTABLISHED)
2162 {
2163         SM_ENTRY_MA(WPA_PTK_GROUP, REKEYESTABLISHED, wpa_ptk_group);
2164         sm->EAPOLKeyReceived = FALSE;
2165         if (sm->GUpdateStationKeys)
2166                 sm->group->GKeyDoneStations--;
2167         sm->GUpdateStationKeys = FALSE;
2168         sm->GTimeoutCtr = 0;
2169         /* FIX: MLME.SetProtection.Request(TA, Tx_Rx) */
2170         wpa_auth_vlogger(sm->wpa_auth, sm->addr, LOGGER_INFO,
2171                          "group key handshake completed (%s)",
2172                          sm->wpa == WPA_VERSION_WPA ? "WPA" : "RSN");
2173         sm->has_GTK = TRUE;
2174 }
2175
2176
2177 SM_STATE(WPA_PTK_GROUP, KEYERROR)
2178 {
2179         SM_ENTRY_MA(WPA_PTK_GROUP, KEYERROR, wpa_ptk_group);
2180         if (sm->GUpdateStationKeys)
2181                 sm->group->GKeyDoneStations--;
2182         sm->GUpdateStationKeys = FALSE;
2183         sm->Disconnect = TRUE;
2184 }
2185
2186
2187 SM_STEP(WPA_PTK_GROUP)
2188 {
2189         if (sm->Init || sm->PtkGroupInit) {
2190                 SM_ENTER(WPA_PTK_GROUP, IDLE);
2191                 sm->PtkGroupInit = FALSE;
2192         } else switch (sm->wpa_ptk_group_state) {
2193         case WPA_PTK_GROUP_IDLE:
2194                 if (sm->GUpdateStationKeys ||
2195                     (sm->wpa == WPA_VERSION_WPA && sm->PInitAKeys))
2196                         SM_ENTER(WPA_PTK_GROUP, REKEYNEGOTIATING);
2197                 break;
2198         case WPA_PTK_GROUP_REKEYNEGOTIATING:
2199                 if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
2200                     !sm->EAPOLKeyPairwise && sm->MICVerified)
2201                         SM_ENTER(WPA_PTK_GROUP, REKEYESTABLISHED);
2202                 else if (sm->GTimeoutCtr >
2203                          (int) dot11RSNAConfigGroupUpdateCount)
2204                         SM_ENTER(WPA_PTK_GROUP, KEYERROR);
2205                 else if (sm->TimeoutEvt)
2206                         SM_ENTER(WPA_PTK_GROUP, REKEYNEGOTIATING);
2207                 break;
2208         case WPA_PTK_GROUP_KEYERROR:
2209                 SM_ENTER(WPA_PTK_GROUP, IDLE);
2210                 break;
2211         case WPA_PTK_GROUP_REKEYESTABLISHED:
2212                 SM_ENTER(WPA_PTK_GROUP, IDLE);
2213                 break;
2214         }
2215 }
2216
2217
2218 static int wpa_gtk_update(struct wpa_authenticator *wpa_auth,
2219                           struct wpa_group *group)
2220 {
2221         int ret = 0;
2222
2223         os_memcpy(group->GNonce, group->Counter, WPA_NONCE_LEN);
2224         inc_byte_array(group->Counter, WPA_NONCE_LEN);
2225         if (wpa_gmk_to_gtk(group->GMK, "Group key expansion",
2226                            wpa_auth->addr, group->GNonce,
2227                            group->GTK[group->GN - 1], group->GTK_len) < 0)
2228                 ret = -1;
2229         wpa_hexdump_key(MSG_DEBUG, "GTK",
2230                         group->GTK[group->GN - 1], group->GTK_len);
2231
2232 #ifdef CONFIG_IEEE80211W
2233         if (wpa_auth->conf.ieee80211w != NO_MGMT_FRAME_PROTECTION) {
2234                 os_memcpy(group->GNonce, group->Counter, WPA_NONCE_LEN);
2235                 inc_byte_array(group->Counter, WPA_NONCE_LEN);
2236                 if (wpa_gmk_to_gtk(group->GMK, "IGTK key expansion",
2237                                    wpa_auth->addr, group->GNonce,
2238                                    group->IGTK[group->GN_igtk - 4],
2239                                    WPA_IGTK_LEN) < 0)
2240                         ret = -1;
2241                 wpa_hexdump_key(MSG_DEBUG, "IGTK",
2242                                 group->IGTK[group->GN_igtk - 4], WPA_IGTK_LEN);
2243         }
2244 #endif /* CONFIG_IEEE80211W */
2245
2246         return ret;
2247 }
2248
2249
2250 static void wpa_group_gtk_init(struct wpa_authenticator *wpa_auth,
2251                                struct wpa_group *group)
2252 {
2253         wpa_printf(MSG_DEBUG, "WPA: group state machine entering state "
2254                    "GTK_INIT (VLAN-ID %d)", group->vlan_id);
2255         group->changed = FALSE; /* GInit is not cleared here; avoid loop */
2256         group->wpa_group_state = WPA_GROUP_GTK_INIT;
2257
2258         /* GTK[0..N] = 0 */
2259         os_memset(group->GTK, 0, sizeof(group->GTK));
2260         group->GN = 1;
2261         group->GM = 2;
2262 #ifdef CONFIG_IEEE80211W
2263         group->GN_igtk = 4;
2264         group->GM_igtk = 5;
2265 #endif /* CONFIG_IEEE80211W */
2266         /* GTK[GN] = CalcGTK() */
2267         wpa_gtk_update(wpa_auth, group);
2268 }
2269
2270
2271 static int wpa_group_update_sta(struct wpa_state_machine *sm, void *ctx)
2272 {
2273         if (sm->wpa_ptk_state != WPA_PTK_PTKINITDONE) {
2274                 wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2275                                 "Not in PTKINITDONE; skip Group Key update");
2276                 sm->GUpdateStationKeys = FALSE;
2277                 return 0;
2278         }
2279         if (sm->GUpdateStationKeys) {
2280                 /*
2281                  * This should not really happen, so add a debug log entry.
2282                  * Since we clear the GKeyDoneStations before the loop, the
2283                  * station needs to be counted here anyway.
2284                  */
2285                 wpa_auth_logger(sm->wpa_auth, sm->addr, LOGGER_DEBUG,
2286                                 "GUpdateStationKeys was already set when "
2287                                 "marking station for GTK rekeying");
2288         }
2289
2290         sm->group->GKeyDoneStations++;
2291         sm->GUpdateStationKeys = TRUE;
2292
2293         wpa_sm_step(sm);
2294         return 0;
2295 }
2296
2297
2298 static void wpa_group_setkeys(struct wpa_authenticator *wpa_auth,
2299                               struct wpa_group *group)
2300 {
2301         int tmp;
2302
2303         wpa_printf(MSG_DEBUG, "WPA: group state machine entering state "
2304                    "SETKEYS (VLAN-ID %d)", group->vlan_id);
2305         group->changed = TRUE;
2306         group->wpa_group_state = WPA_GROUP_SETKEYS;
2307         group->GTKReKey = FALSE;
2308         tmp = group->GM;
2309         group->GM = group->GN;
2310         group->GN = tmp;
2311 #ifdef CONFIG_IEEE80211W
2312         tmp = group->GM_igtk;
2313         group->GM_igtk = group->GN_igtk;
2314         group->GN_igtk = tmp;
2315 #endif /* CONFIG_IEEE80211W */
2316         /* "GKeyDoneStations = GNoStations" is done in more robust way by
2317          * counting the STAs that are marked with GUpdateStationKeys instead of
2318          * including all STAs that could be in not-yet-completed state. */
2319         wpa_gtk_update(wpa_auth, group);
2320
2321         if (group->GKeyDoneStations) {
2322                 wpa_printf(MSG_DEBUG, "wpa_group_setkeys: Unexpected "
2323                            "GKeyDoneStations=%d when starting new GTK rekey",
2324                            group->GKeyDoneStations);
2325                 group->GKeyDoneStations = 0;
2326         }
2327         wpa_auth_for_each_sta(wpa_auth, wpa_group_update_sta, NULL);
2328         wpa_printf(MSG_DEBUG, "wpa_group_setkeys: GKeyDoneStations=%d",
2329                    group->GKeyDoneStations);
2330 }
2331
2332
2333 static int wpa_group_config_group_keys(struct wpa_authenticator *wpa_auth,
2334                                        struct wpa_group *group)
2335 {
2336         int ret = 0;
2337
2338         if (wpa_auth_set_key(wpa_auth, group->vlan_id,
2339                              wpa_alg_enum(wpa_auth->conf.wpa_group),
2340                              broadcast_ether_addr, group->GN,
2341                              group->GTK[group->GN - 1], group->GTK_len) < 0)
2342                 ret = -1;
2343
2344 #ifdef CONFIG_IEEE80211W
2345         if (wpa_auth->conf.ieee80211w != NO_MGMT_FRAME_PROTECTION &&
2346             wpa_auth_set_key(wpa_auth, group->vlan_id, WPA_ALG_IGTK,
2347                              broadcast_ether_addr, group->GN_igtk,
2348                              group->IGTK[group->GN_igtk - 4],
2349                              WPA_IGTK_LEN) < 0)
2350                 ret = -1;
2351 #endif /* CONFIG_IEEE80211W */
2352
2353         return ret;
2354 }
2355
2356
2357 static int wpa_group_setkeysdone(struct wpa_authenticator *wpa_auth,
2358                                  struct wpa_group *group)
2359 {
2360         wpa_printf(MSG_DEBUG, "WPA: group state machine entering state "
2361                    "SETKEYSDONE (VLAN-ID %d)", group->vlan_id);
2362         group->changed = TRUE;
2363         group->wpa_group_state = WPA_GROUP_SETKEYSDONE;
2364
2365         if (wpa_group_config_group_keys(wpa_auth, group) < 0)
2366                 return -1;
2367
2368         return 0;
2369 }
2370
2371
2372 static void wpa_group_sm_step(struct wpa_authenticator *wpa_auth,
2373                               struct wpa_group *group)
2374 {
2375         if (group->GInit) {
2376                 wpa_group_gtk_init(wpa_auth, group);
2377         } else if (group->wpa_group_state == WPA_GROUP_GTK_INIT &&
2378                    group->GTKAuthenticator) {
2379                 wpa_group_setkeysdone(wpa_auth, group);
2380         } else if (group->wpa_group_state == WPA_GROUP_SETKEYSDONE &&
2381                    group->GTKReKey) {
2382                 wpa_group_setkeys(wpa_auth, group);
2383         } else if (group->wpa_group_state == WPA_GROUP_SETKEYS) {
2384                 if (group->GKeyDoneStations == 0)
2385                         wpa_group_setkeysdone(wpa_auth, group);
2386                 else if (group->GTKReKey)
2387                         wpa_group_setkeys(wpa_auth, group);
2388         }
2389 }
2390
2391
2392 static int wpa_sm_step(struct wpa_state_machine *sm)
2393 {
2394         if (sm == NULL)
2395                 return 0;
2396
2397         if (sm->in_step_loop) {
2398                 /* This should not happen, but if it does, make sure we do not
2399                  * end up freeing the state machine too early by exiting the
2400                  * recursive call. */
2401                 wpa_printf(MSG_ERROR, "WPA: wpa_sm_step() called recursively");
2402                 return 0;
2403         }
2404
2405         sm->in_step_loop = 1;
2406         do {
2407                 if (sm->pending_deinit)
2408                         break;
2409
2410                 sm->changed = FALSE;
2411                 sm->wpa_auth->group->changed = FALSE;
2412
2413                 SM_STEP_RUN(WPA_PTK);
2414                 if (sm->pending_deinit)
2415                         break;
2416                 SM_STEP_RUN(WPA_PTK_GROUP);
2417                 if (sm->pending_deinit)
2418                         break;
2419                 wpa_group_sm_step(sm->wpa_auth, sm->group);
2420         } while (sm->changed || sm->wpa_auth->group->changed);
2421         sm->in_step_loop = 0;
2422
2423         if (sm->pending_deinit) {
2424                 wpa_printf(MSG_DEBUG, "WPA: Completing pending STA state "
2425                            "machine deinit for " MACSTR, MAC2STR(sm->addr));
2426                 wpa_free_sta_sm(sm);
2427                 return 1;
2428         }
2429         return 0;
2430 }
2431
2432
2433 static void wpa_sm_call_step(void *eloop_ctx, void *timeout_ctx)
2434 {
2435         struct wpa_state_machine *sm = eloop_ctx;
2436         wpa_sm_step(sm);
2437 }
2438
2439
2440 void wpa_auth_sm_notify(struct wpa_state_machine *sm)
2441 {
2442         if (sm == NULL)
2443                 return;
2444         eloop_register_timeout(0, 0, wpa_sm_call_step, sm, NULL);
2445 }
2446
2447
2448 void wpa_gtk_rekey(struct wpa_authenticator *wpa_auth)
2449 {
2450         int tmp, i;
2451         struct wpa_group *group;
2452
2453         if (wpa_auth == NULL)
2454                 return;
2455
2456         group = wpa_auth->group;
2457
2458         for (i = 0; i < 2; i++) {
2459                 tmp = group->GM;
2460                 group->GM = group->GN;
2461                 group->GN = tmp;
2462 #ifdef CONFIG_IEEE80211W
2463                 tmp = group->GM_igtk;
2464                 group->GM_igtk = group->GN_igtk;
2465                 group->GN_igtk = tmp;
2466 #endif /* CONFIG_IEEE80211W */
2467                 wpa_gtk_update(wpa_auth, group);
2468         }
2469 }
2470
2471
2472 static const char * wpa_bool_txt(int bool)
2473 {
2474         return bool ? "TRUE" : "FALSE";
2475 }
2476
2477
2478 static int wpa_cipher_bits(int cipher)
2479 {
2480         switch (cipher) {
2481         case WPA_CIPHER_CCMP:
2482                 return 128;
2483         case WPA_CIPHER_TKIP:
2484                 return 256;
2485         case WPA_CIPHER_WEP104:
2486                 return 104;
2487         case WPA_CIPHER_WEP40:
2488                 return 40;
2489         default:
2490                 return 0;
2491         }
2492 }
2493
2494
2495 #define RSN_SUITE "%02x-%02x-%02x-%d"
2496 #define RSN_SUITE_ARG(s) \
2497 ((s) >> 24) & 0xff, ((s) >> 16) & 0xff, ((s) >> 8) & 0xff, (s) & 0xff
2498
2499 int wpa_get_mib(struct wpa_authenticator *wpa_auth, char *buf, size_t buflen)
2500 {
2501         int len = 0, ret;
2502         char pmkid_txt[PMKID_LEN * 2 + 1];
2503 #ifdef CONFIG_RSN_PREAUTH
2504         const int preauth = 1;
2505 #else /* CONFIG_RSN_PREAUTH */
2506         const int preauth = 0;
2507 #endif /* CONFIG_RSN_PREAUTH */
2508
2509         if (wpa_auth == NULL)
2510                 return len;
2511
2512         ret = os_snprintf(buf + len, buflen - len,
2513                           "dot11RSNAOptionImplemented=TRUE\n"
2514                           "dot11RSNAPreauthenticationImplemented=%s\n"
2515                           "dot11RSNAEnabled=%s\n"
2516                           "dot11RSNAPreauthenticationEnabled=%s\n",
2517                           wpa_bool_txt(preauth),
2518                           wpa_bool_txt(wpa_auth->conf.wpa & WPA_PROTO_RSN),
2519                           wpa_bool_txt(wpa_auth->conf.rsn_preauth));
2520         if (ret < 0 || (size_t) ret >= buflen - len)
2521                 return len;
2522         len += ret;
2523
2524         wpa_snprintf_hex(pmkid_txt, sizeof(pmkid_txt),
2525                          wpa_auth->dot11RSNAPMKIDUsed, PMKID_LEN);
2526
2527         ret = os_snprintf(
2528                 buf + len, buflen - len,
2529                 "dot11RSNAConfigVersion=%u\n"
2530                 "dot11RSNAConfigPairwiseKeysSupported=9999\n"
2531                 /* FIX: dot11RSNAConfigGroupCipher */
2532                 /* FIX: dot11RSNAConfigGroupRekeyMethod */
2533                 /* FIX: dot11RSNAConfigGroupRekeyTime */
2534                 /* FIX: dot11RSNAConfigGroupRekeyPackets */
2535                 "dot11RSNAConfigGroupRekeyStrict=%u\n"
2536                 "dot11RSNAConfigGroupUpdateCount=%u\n"
2537                 "dot11RSNAConfigPairwiseUpdateCount=%u\n"
2538                 "dot11RSNAConfigGroupCipherSize=%u\n"
2539                 "dot11RSNAConfigPMKLifetime=%u\n"
2540                 "dot11RSNAConfigPMKReauthThreshold=%u\n"
2541                 "dot11RSNAConfigNumberOfPTKSAReplayCounters=0\n"
2542                 "dot11RSNAConfigSATimeout=%u\n"
2543                 "dot11RSNAAuthenticationSuiteSelected=" RSN_SUITE "\n"
2544                 "dot11RSNAPairwiseCipherSelected=" RSN_SUITE "\n"
2545                 "dot11RSNAGroupCipherSelected=" RSN_SUITE "\n"
2546                 "dot11RSNAPMKIDUsed=%s\n"
2547                 "dot11RSNAAuthenticationSuiteRequested=" RSN_SUITE "\n"
2548                 "dot11RSNAPairwiseCipherRequested=" RSN_SUITE "\n"
2549                 "dot11RSNAGroupCipherRequested=" RSN_SUITE "\n"
2550                 "dot11RSNATKIPCounterMeasuresInvoked=%u\n"
2551                 "dot11RSNA4WayHandshakeFailures=%u\n"
2552                 "dot11RSNAConfigNumberOfGTKSAReplayCounters=0\n",
2553                 RSN_VERSION,
2554                 !!wpa_auth->conf.wpa_strict_rekey,
2555                 dot11RSNAConfigGroupUpdateCount,
2556                 dot11RSNAConfigPairwiseUpdateCount,
2557                 wpa_cipher_bits(wpa_auth->conf.wpa_group),
2558                 dot11RSNAConfigPMKLifetime,
2559                 dot11RSNAConfigPMKReauthThreshold,
2560                 dot11RSNAConfigSATimeout,
2561                 RSN_SUITE_ARG(wpa_auth->dot11RSNAAuthenticationSuiteSelected),
2562                 RSN_SUITE_ARG(wpa_auth->dot11RSNAPairwiseCipherSelected),
2563                 RSN_SUITE_ARG(wpa_auth->dot11RSNAGroupCipherSelected),
2564                 pmkid_txt,
2565                 RSN_SUITE_ARG(wpa_auth->dot11RSNAAuthenticationSuiteRequested),
2566                 RSN_SUITE_ARG(wpa_auth->dot11RSNAPairwiseCipherRequested),
2567                 RSN_SUITE_ARG(wpa_auth->dot11RSNAGroupCipherRequested),
2568                 wpa_auth->dot11RSNATKIPCounterMeasuresInvoked,
2569                 wpa_auth->dot11RSNA4WayHandshakeFailures);
2570         if (ret < 0 || (size_t) ret >= buflen - len)
2571                 return len;
2572         len += ret;
2573
2574         /* TODO: dot11RSNAConfigPairwiseCiphersTable */
2575         /* TODO: dot11RSNAConfigAuthenticationSuitesTable */
2576
2577         /* Private MIB */
2578         ret = os_snprintf(buf + len, buflen - len, "hostapdWPAGroupState=%d\n",
2579                           wpa_auth->group->wpa_group_state);
2580         if (ret < 0 || (size_t) ret >= buflen - len)
2581                 return len;
2582         len += ret;
2583
2584         return len;
2585 }
2586
2587
2588 int wpa_get_mib_sta(struct wpa_state_machine *sm, char *buf, size_t buflen)
2589 {
2590         int len = 0, ret;
2591         u32 pairwise = 0;
2592
2593         if (sm == NULL)
2594                 return 0;
2595
2596         /* TODO: FF-FF-FF-FF-FF-FF entry for broadcast/multicast stats */
2597
2598         /* dot11RSNAStatsEntry */
2599
2600         if (sm->wpa == WPA_VERSION_WPA) {
2601                 if (sm->pairwise == WPA_CIPHER_CCMP)
2602                         pairwise = WPA_CIPHER_SUITE_CCMP;
2603                 else if (sm->pairwise == WPA_CIPHER_TKIP)
2604                         pairwise = WPA_CIPHER_SUITE_TKIP;
2605                 else if (sm->pairwise == WPA_CIPHER_WEP104)
2606                         pairwise = WPA_CIPHER_SUITE_WEP104;
2607                 else if (sm->pairwise == WPA_CIPHER_WEP40)
2608                         pairwise = WPA_CIPHER_SUITE_WEP40;
2609                 else if (sm->pairwise == WPA_CIPHER_NONE)
2610                         pairwise = WPA_CIPHER_SUITE_NONE;
2611         } else if (sm->wpa == WPA_VERSION_WPA2) {
2612                 if (sm->pairwise == WPA_CIPHER_CCMP)
2613                         pairwise = RSN_CIPHER_SUITE_CCMP;
2614                 else if (sm->pairwise == WPA_CIPHER_TKIP)
2615                         pairwise = RSN_CIPHER_SUITE_TKIP;
2616                 else if (sm->pairwise == WPA_CIPHER_WEP104)
2617                         pairwise = RSN_CIPHER_SUITE_WEP104;
2618                 else if (sm->pairwise == WPA_CIPHER_WEP40)
2619                         pairwise = RSN_CIPHER_SUITE_WEP40;
2620                 else if (sm->pairwise == WPA_CIPHER_NONE)
2621                         pairwise = RSN_CIPHER_SUITE_NONE;
2622         } else
2623                 return 0;
2624
2625         ret = os_snprintf(
2626                 buf + len, buflen - len,
2627                 /* TODO: dot11RSNAStatsIndex */
2628                 "dot11RSNAStatsSTAAddress=" MACSTR "\n"
2629                 "dot11RSNAStatsVersion=1\n"
2630                 "dot11RSNAStatsSelectedPairwiseCipher=" RSN_SUITE "\n"
2631                 /* TODO: dot11RSNAStatsTKIPICVErrors */
2632                 "dot11RSNAStatsTKIPLocalMICFailures=%u\n"
2633                 "dot11RSNAStatsTKIPRemoteMICFailures=%u\n"
2634                 /* TODO: dot11RSNAStatsCCMPReplays */
2635                 /* TODO: dot11RSNAStatsCCMPDecryptErrors */
2636                 /* TODO: dot11RSNAStatsTKIPReplays */,
2637                 MAC2STR(sm->addr),
2638                 RSN_SUITE_ARG(pairwise),
2639                 sm->dot11RSNAStatsTKIPLocalMICFailures,
2640                 sm->dot11RSNAStatsTKIPRemoteMICFailures);
2641         if (ret < 0 || (size_t) ret >= buflen - len)
2642                 return len;
2643         len += ret;
2644
2645         /* Private MIB */
2646         ret = os_snprintf(buf + len, buflen - len,
2647                           "hostapdWPAPTKState=%d\n"
2648                           "hostapdWPAPTKGroupState=%d\n",
2649                           sm->wpa_ptk_state,
2650                           sm->wpa_ptk_group_state);
2651         if (ret < 0 || (size_t) ret >= buflen - len)
2652                 return len;
2653         len += ret;
2654
2655         return len;
2656 }
2657
2658
2659 void wpa_auth_countermeasures_start(struct wpa_authenticator *wpa_auth)
2660 {
2661         if (wpa_auth)
2662                 wpa_auth->dot11RSNATKIPCounterMeasuresInvoked++;
2663 }
2664
2665
2666 int wpa_auth_pairwise_set(struct wpa_state_machine *sm)
2667 {
2668         return sm && sm->pairwise_set;
2669 }
2670
2671
2672 int wpa_auth_get_pairwise(struct wpa_state_machine *sm)
2673 {
2674         return sm->pairwise;
2675 }
2676
2677
2678 int wpa_auth_sta_key_mgmt(struct wpa_state_machine *sm)
2679 {
2680         if (sm == NULL)
2681                 return -1;
2682         return sm->wpa_key_mgmt;
2683 }
2684
2685
2686 int wpa_auth_sta_wpa_version(struct wpa_state_machine *sm)
2687 {
2688         if (sm == NULL)
2689                 return 0;
2690         return sm->wpa;
2691 }
2692
2693
2694 int wpa_auth_sta_clear_pmksa(struct wpa_state_machine *sm,
2695                              struct rsn_pmksa_cache_entry *entry)
2696 {
2697         if (sm == NULL || sm->pmksa != entry)
2698                 return -1;
2699         sm->pmksa = NULL;
2700         return 0;
2701 }
2702
2703
2704 struct rsn_pmksa_cache_entry *
2705 wpa_auth_sta_get_pmksa(struct wpa_state_machine *sm)
2706 {
2707         return sm ? sm->pmksa : NULL;
2708 }
2709
2710
2711 void wpa_auth_sta_local_mic_failure_report(struct wpa_state_machine *sm)
2712 {
2713         if (sm)
2714                 sm->dot11RSNAStatsTKIPLocalMICFailures++;
2715 }
2716
2717
2718 const u8 * wpa_auth_get_wpa_ie(struct wpa_authenticator *wpa_auth, size_t *len)
2719 {
2720         if (wpa_auth == NULL)
2721                 return NULL;
2722         *len = wpa_auth->wpa_ie_len;
2723         return wpa_auth->wpa_ie;
2724 }
2725
2726
2727 int wpa_auth_pmksa_add(struct wpa_state_machine *sm, const u8 *pmk,
2728                        int session_timeout, struct eapol_state_machine *eapol)
2729 {
2730         if (sm == NULL || sm->wpa != WPA_VERSION_WPA2 ||
2731             sm->wpa_auth->conf.disable_pmksa_caching)
2732                 return -1;
2733
2734         if (pmksa_cache_auth_add(sm->wpa_auth->pmksa, pmk, PMK_LEN,
2735                                  sm->wpa_auth->addr, sm->addr, session_timeout,
2736                                  eapol, sm->wpa_key_mgmt))
2737                 return 0;
2738
2739         return -1;
2740 }
2741
2742
2743 int wpa_auth_pmksa_add_preauth(struct wpa_authenticator *wpa_auth,
2744                                const u8 *pmk, size_t len, const u8 *sta_addr,
2745                                int session_timeout,
2746                                struct eapol_state_machine *eapol)
2747 {
2748         if (wpa_auth == NULL)
2749                 return -1;
2750
2751         if (pmksa_cache_auth_add(wpa_auth->pmksa, pmk, len, wpa_auth->addr,
2752                                  sta_addr, session_timeout, eapol,
2753                                  WPA_KEY_MGMT_IEEE8021X))
2754                 return 0;
2755
2756         return -1;
2757 }
2758
2759
2760 static struct wpa_group *
2761 wpa_auth_add_group(struct wpa_authenticator *wpa_auth, int vlan_id)
2762 {
2763         struct wpa_group *group;
2764
2765         if (wpa_auth == NULL || wpa_auth->group == NULL)
2766                 return NULL;
2767
2768         wpa_printf(MSG_DEBUG, "WPA: Add group state machine for VLAN-ID %d",
2769                    vlan_id);
2770         group = wpa_group_init(wpa_auth, vlan_id);
2771         if (group == NULL)
2772                 return NULL;
2773
2774         group->next = wpa_auth->group->next;
2775         wpa_auth->group->next = group;
2776
2777         return group;
2778 }
2779
2780
2781 int wpa_auth_sta_set_vlan(struct wpa_state_machine *sm, int vlan_id)
2782 {
2783         struct wpa_group *group;
2784
2785         if (sm == NULL || sm->wpa_auth == NULL)
2786                 return 0;
2787
2788         group = sm->wpa_auth->group;
2789         while (group) {
2790                 if (group->vlan_id == vlan_id)
2791                         break;
2792                 group = group->next;
2793         }
2794
2795         if (group == NULL) {
2796                 group = wpa_auth_add_group(sm->wpa_auth, vlan_id);
2797                 if (group == NULL)
2798                         return -1;
2799         }
2800
2801         if (sm->group == group)
2802                 return 0;
2803
2804         wpa_printf(MSG_DEBUG, "WPA: Moving STA " MACSTR " to use group state "
2805                    "machine for VLAN ID %d", MAC2STR(sm->addr), vlan_id);
2806
2807         sm->group = group;
2808         return 0;
2809 }
2810
2811
2812 void wpa_auth_eapol_key_tx_status(struct wpa_authenticator *wpa_auth,
2813                                   struct wpa_state_machine *sm, int ack)
2814 {
2815         if (wpa_auth == NULL || sm == NULL)
2816                 return;
2817         wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key TX status for STA " MACSTR
2818                    " ack=%d", MAC2STR(sm->addr), ack);
2819         if (sm->pending_1_of_4_timeout && ack) {
2820                 /*
2821                  * Some deployed supplicant implementations update their SNonce
2822                  * for each EAPOL-Key 2/4 message even within the same 4-way
2823                  * handshake and then fail to use the first SNonce when
2824                  * deriving the PTK. This results in unsuccessful 4-way
2825                  * handshake whenever the relatively short initial timeout is
2826                  * reached and EAPOL-Key 1/4 is retransmitted. Try to work
2827                  * around this by increasing the timeout now that we know that
2828                  * the station has received the frame.
2829                  */
2830                 int timeout_ms = eapol_key_timeout_subseq;
2831                 wpa_printf(MSG_DEBUG, "WPA: Increase initial EAPOL-Key 1/4 "
2832                            "timeout by %u ms because of acknowledged frame",
2833                            timeout_ms);
2834                 eloop_cancel_timeout(wpa_send_eapol_timeout, wpa_auth, sm);
2835                 eloop_register_timeout(timeout_ms / 1000,
2836                                        (timeout_ms % 1000) * 1000,
2837                                        wpa_send_eapol_timeout, wpa_auth, sm);
2838         }
2839 }