OSDN Git Service

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