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