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