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