xref: /freebsd/contrib/wpa/src/ap/wpa_auth.c (revision 6549718b70f0e660a15685369afb4f9caf2215ce)
1 /*
2  * IEEE 802.11 RSN / WPA Authenticator
3  * Copyright (c) 2004-2022, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "utils/includes.h"
10 
11 #include "utils/common.h"
12 #include "utils/eloop.h"
13 #include "utils/state_machine.h"
14 #include "utils/bitfield.h"
15 #include "common/ieee802_11_defs.h"
16 #include "common/ocv.h"
17 #include "common/dpp.h"
18 #include "common/wpa_ctrl.h"
19 #include "crypto/aes.h"
20 #include "crypto/aes_wrap.h"
21 #include "crypto/aes_siv.h"
22 #include "crypto/crypto.h"
23 #include "crypto/sha1.h"
24 #include "crypto/sha256.h"
25 #include "crypto/sha384.h"
26 #include "crypto/sha512.h"
27 #include "crypto/random.h"
28 #include "eapol_auth/eapol_auth_sm.h"
29 #include "drivers/driver.h"
30 #include "ap_config.h"
31 #include "ieee802_11.h"
32 #include "sta_info.h"
33 #include "wpa_auth.h"
34 #include "pmksa_cache_auth.h"
35 #include "wpa_auth_i.h"
36 #include "wpa_auth_ie.h"
37 
38 #define STATE_MACHINE_DATA struct wpa_state_machine
39 #define STATE_MACHINE_DEBUG_PREFIX "WPA"
40 #define STATE_MACHINE_ADDR wpa_auth_get_spa(sm)
41 
42 
43 static void wpa_send_eapol_timeout(void *eloop_ctx, void *timeout_ctx);
44 static int wpa_sm_step(struct wpa_state_machine *sm);
45 static int wpa_verify_key_mic(int akmp, size_t pmk_len, struct wpa_ptk *PTK,
46 			      u8 *data, size_t data_len);
47 #ifdef CONFIG_FILS
48 static int wpa_aead_decrypt(struct wpa_state_machine *sm, struct wpa_ptk *ptk,
49 			    u8 *buf, size_t buf_len, u16 *_key_data_len);
50 static struct wpabuf * fils_prepare_plainbuf(struct wpa_state_machine *sm,
51 					     const struct wpabuf *hlp);
52 #endif /* CONFIG_FILS */
53 static void wpa_sm_call_step(void *eloop_ctx, void *timeout_ctx);
54 static void wpa_group_sm_step(struct wpa_authenticator *wpa_auth,
55 			      struct wpa_group *group);
56 static void wpa_request_new_ptk(struct wpa_state_machine *sm);
57 static int wpa_gtk_update(struct wpa_authenticator *wpa_auth,
58 			  struct wpa_group *group);
59 static int wpa_group_config_group_keys(struct wpa_authenticator *wpa_auth,
60 				       struct wpa_group *group);
61 static int wpa_derive_ptk(struct wpa_state_machine *sm, const u8 *snonce,
62 			  const u8 *pmk, unsigned int pmk_len,
63 			  struct wpa_ptk *ptk, int force_sha256,
64 			  u8 *pmk_r0, u8 *pmk_r1, u8 *pmk_r0_name,
65 			  size_t *key_len, bool no_kdk);
66 static void wpa_group_free(struct wpa_authenticator *wpa_auth,
67 			   struct wpa_group *group);
68 static void wpa_group_get(struct wpa_authenticator *wpa_auth,
69 			  struct wpa_group *group);
70 static void wpa_group_put(struct wpa_authenticator *wpa_auth,
71 			  struct wpa_group *group);
72 static int ieee80211w_kde_len(struct wpa_state_machine *sm);
73 static u8 * ieee80211w_kde_add(struct wpa_state_machine *sm, u8 *pos);
74 static void wpa_group_update_gtk(struct wpa_authenticator *wpa_auth,
75 				 struct wpa_group *group);
76 
77 
78 static const u32 eapol_key_timeout_first = 100; /* ms */
79 static const u32 eapol_key_timeout_subseq = 1000; /* ms */
80 static const u32 eapol_key_timeout_first_group = 500; /* ms */
81 static const u32 eapol_key_timeout_no_retrans = 4000; /* ms */
82 
83 /* TODO: make these configurable */
84 static const int dot11RSNAConfigPMKLifetime = 43200;
85 static const int dot11RSNAConfigPMKReauthThreshold = 70;
86 static const int dot11RSNAConfigSATimeout = 60;
87 
88 
89 static const u8 * wpa_auth_get_aa(const struct wpa_state_machine *sm)
90 {
91 #ifdef CONFIG_IEEE80211BE
92 	if (sm->mld_assoc_link_id >= 0)
93 		return sm->wpa_auth->mld_addr;
94 #endif /* CONFIG_IEEE80211BE */
95 	return sm->wpa_auth->addr;
96 }
97 
98 
99 static const u8 * wpa_auth_get_spa(const struct wpa_state_machine *sm)
100 {
101 #ifdef CONFIG_IEEE80211BE
102 	if (sm->mld_assoc_link_id >= 0)
103 		return sm->peer_mld_addr;
104 #endif /* CONFIG_IEEE80211BE */
105 	return sm->addr;
106 }
107 
108 
109 static void wpa_gkeydone_sta(struct wpa_state_machine *sm)
110 {
111 #ifdef CONFIG_IEEE80211BE
112 	int link_id;
113 #endif /* CONFIG_IEEE80211BE */
114 
115 	if (!sm->wpa_auth)
116 		return;
117 
118 	sm->wpa_auth->group->GKeyDoneStations--;
119 	sm->GUpdateStationKeys = false;
120 
121 #ifdef CONFIG_IEEE80211BE
122 	for_each_sm_auth(sm, link_id)
123 		sm->mld_links[link_id].wpa_auth->group->GKeyDoneStations--;
124 #endif /* CONFIG_IEEE80211BE */
125 }
126 
127 
128 #ifdef CONFIG_IEEE80211BE
129 
130 void wpa_release_link_auth_ref(struct wpa_state_machine *sm,
131 			       int release_link_id)
132 {
133 	int link_id;
134 
135 	if (!sm || release_link_id >= MAX_NUM_MLD_LINKS)
136 		return;
137 
138 	for_each_sm_auth(sm, link_id) {
139 		if (link_id == release_link_id) {
140 			wpa_group_put(sm->mld_links[link_id].wpa_auth,
141 				      sm->mld_links[link_id].wpa_auth->group);
142 			sm->mld_links[link_id].wpa_auth = NULL;
143 		}
144 	}
145 }
146 
147 
148 struct wpa_get_link_auth_ctx {
149 	const u8 *addr;
150 	const u8 *mld_addr;
151 	int link_id;
152 	struct wpa_authenticator *wpa_auth;
153 };
154 
155 static int wpa_get_link_sta_auth(struct wpa_authenticator *wpa_auth, void *data)
156 {
157 	struct wpa_get_link_auth_ctx *ctx = data;
158 
159 	if (!wpa_auth->is_ml)
160 		return 0;
161 
162 	if (ctx->mld_addr &&
163 	    !ether_addr_equal(wpa_auth->mld_addr, ctx->mld_addr))
164 		return 0;
165 
166 	if ((ctx->addr && ether_addr_equal(wpa_auth->addr, ctx->addr)) ||
167 	    (ctx->link_id > -1 && wpa_auth->is_ml &&
168 	     wpa_auth->link_id == ctx->link_id)) {
169 		ctx->wpa_auth = wpa_auth;
170 		return 1;
171 
172 	}
173 	return 0;
174 }
175 
176 
177 static struct wpa_authenticator *
178 wpa_get_link_auth(struct wpa_authenticator *wpa_auth, int link_id)
179 {
180 	struct wpa_get_link_auth_ctx ctx;
181 
182 	ctx.addr = NULL;
183 	ctx.mld_addr = wpa_auth->mld_addr;
184 	ctx.link_id = link_id;
185 	ctx.wpa_auth = NULL;
186 	wpa_auth_for_each_auth(wpa_auth, wpa_get_link_sta_auth, &ctx);
187 	return ctx.wpa_auth;
188 }
189 
190 
191 static int wpa_get_primary_auth_cb(struct wpa_authenticator *wpa_auth,
192 				   void *data)
193 {
194 	struct wpa_get_link_auth_ctx *ctx = data;
195 
196 	if (!wpa_auth->is_ml ||
197 	    !ether_addr_equal(wpa_auth->mld_addr, ctx->addr) ||
198 	    !wpa_auth->primary_auth)
199 		return 0;
200 
201 	ctx->wpa_auth = wpa_auth;
202 	return 1;
203 }
204 
205 #endif /* CONFIG_IEEE80211BE */
206 
207 
208 static struct wpa_authenticator *
209 wpa_get_primary_auth(struct wpa_authenticator *wpa_auth)
210 {
211 #ifdef CONFIG_IEEE80211BE
212 	struct wpa_get_link_auth_ctx ctx;
213 
214 	if (!wpa_auth || !wpa_auth->is_ml || wpa_auth->primary_auth)
215 		return wpa_auth;
216 
217 	ctx.addr = wpa_auth->mld_addr;
218 	ctx.wpa_auth = NULL;
219 	wpa_auth_for_each_auth(wpa_auth, wpa_get_primary_auth_cb, &ctx);
220 
221 	return ctx.wpa_auth;
222 #else /* CONFIG_IEEE80211BE */
223 	return wpa_auth;
224 #endif /* CONFIG_IEEE80211BE */
225 }
226 
227 
228 static inline int wpa_auth_mic_failure_report(
229 	struct wpa_authenticator *wpa_auth, const u8 *addr)
230 {
231 	if (wpa_auth->cb->mic_failure_report)
232 		return wpa_auth->cb->mic_failure_report(wpa_auth->cb_ctx, addr);
233 	return 0;
234 }
235 
236 
237 static inline void wpa_auth_psk_failure_report(
238 	struct wpa_authenticator *wpa_auth, const u8 *addr)
239 {
240 	if (wpa_auth->cb->psk_failure_report)
241 		wpa_auth->cb->psk_failure_report(wpa_auth->cb_ctx, addr);
242 }
243 
244 
245 static inline void wpa_auth_set_eapol(struct wpa_authenticator *wpa_auth,
246 				      const u8 *addr, wpa_eapol_variable var,
247 				      int value)
248 {
249 	if (wpa_auth->cb->set_eapol)
250 		wpa_auth->cb->set_eapol(wpa_auth->cb_ctx, addr, var, value);
251 }
252 
253 
254 static inline int wpa_auth_get_eapol(struct wpa_authenticator *wpa_auth,
255 				     const u8 *addr, wpa_eapol_variable var)
256 {
257 	if (!wpa_auth->cb->get_eapol)
258 		return -1;
259 	return wpa_auth->cb->get_eapol(wpa_auth->cb_ctx, addr, var);
260 }
261 
262 
263 static inline const u8 * wpa_auth_get_psk(struct wpa_authenticator *wpa_auth,
264 					  const u8 *addr,
265 					  const u8 *p2p_dev_addr,
266 					  const u8 *prev_psk, size_t *psk_len,
267 					  int *vlan_id)
268 {
269 	if (!wpa_auth->cb->get_psk)
270 		return NULL;
271 	return wpa_auth->cb->get_psk(wpa_auth->cb_ctx, addr, p2p_dev_addr,
272 				     prev_psk, psk_len, vlan_id);
273 }
274 
275 
276 static inline int wpa_auth_get_msk(struct wpa_authenticator *wpa_auth,
277 				   const u8 *addr, u8 *msk, size_t *len)
278 {
279 	if (!wpa_auth->cb->get_msk)
280 		return -1;
281 	return wpa_auth->cb->get_msk(wpa_auth->cb_ctx, addr, msk, len);
282 }
283 
284 
285 static inline int wpa_auth_set_key(struct wpa_authenticator *wpa_auth,
286 				   int vlan_id,
287 				   enum wpa_alg alg, const u8 *addr, int idx,
288 				   u8 *key, size_t key_len,
289 				   enum key_flag key_flag)
290 {
291 	if (!wpa_auth->cb->set_key)
292 		return -1;
293 	return wpa_auth->cb->set_key(wpa_auth->cb_ctx, vlan_id, alg, addr, idx,
294 				     key, key_len, key_flag);
295 }
296 
297 
298 #ifdef CONFIG_PASN
299 static inline int wpa_auth_set_ltf_keyseed(struct wpa_authenticator *wpa_auth,
300 					   const u8 *peer_addr,
301 					   const u8 *ltf_keyseed,
302 					   size_t ltf_keyseed_len)
303 {
304 	if (!wpa_auth->cb->set_ltf_keyseed)
305 		return -1;
306 	return wpa_auth->cb->set_ltf_keyseed(wpa_auth->cb_ctx, peer_addr,
307 					     ltf_keyseed, ltf_keyseed_len);
308 }
309 #endif /* CONFIG_PASN */
310 
311 
312 static inline int wpa_auth_get_seqnum(struct wpa_authenticator *wpa_auth,
313 				      const u8 *addr, int idx, u8 *seq)
314 {
315 	int res;
316 
317 	if (!wpa_auth->cb->get_seqnum)
318 		return -1;
319 #ifdef CONFIG_TESTING_OPTIONS
320 	os_memset(seq, 0, WPA_KEY_RSC_LEN);
321 #endif /* CONFIG_TESTING_OPTIONS */
322 	res = wpa_auth->cb->get_seqnum(wpa_auth->cb_ctx, addr, idx, seq);
323 #ifdef CONFIG_TESTING_OPTIONS
324 	if (!addr && idx < 4 && wpa_auth->conf.gtk_rsc_override_set) {
325 		wpa_printf(MSG_DEBUG,
326 			   "TESTING: Override GTK RSC %016llx --> %016llx",
327 			   (long long unsigned) WPA_GET_LE64(seq),
328 			   (long long unsigned)
329 			   WPA_GET_LE64(wpa_auth->conf.gtk_rsc_override));
330 		os_memcpy(seq, wpa_auth->conf.gtk_rsc_override,
331 			  WPA_KEY_RSC_LEN);
332 	}
333 	if (!addr && idx >= 4 && idx <= 5 &&
334 	    wpa_auth->conf.igtk_rsc_override_set) {
335 		wpa_printf(MSG_DEBUG,
336 			   "TESTING: Override IGTK RSC %016llx --> %016llx",
337 			   (long long unsigned) WPA_GET_LE64(seq),
338 			   (long long unsigned)
339 			   WPA_GET_LE64(wpa_auth->conf.igtk_rsc_override));
340 		os_memcpy(seq, wpa_auth->conf.igtk_rsc_override,
341 			  WPA_KEY_RSC_LEN);
342 	}
343 #endif /* CONFIG_TESTING_OPTIONS */
344 	return res;
345 }
346 
347 
348 static inline int
349 wpa_auth_send_eapol(struct wpa_authenticator *wpa_auth, const u8 *addr,
350 		    const u8 *data, size_t data_len, int encrypt)
351 {
352 	if (!wpa_auth->cb->send_eapol)
353 		return -1;
354 	return wpa_auth->cb->send_eapol(wpa_auth->cb_ctx, addr, data, data_len,
355 					encrypt);
356 }
357 
358 
359 #ifdef CONFIG_MESH
360 static inline int wpa_auth_start_ampe(struct wpa_authenticator *wpa_auth,
361 				      const u8 *addr)
362 {
363 	if (!wpa_auth->cb->start_ampe)
364 		return -1;
365 	return wpa_auth->cb->start_ampe(wpa_auth->cb_ctx, addr);
366 }
367 #endif /* CONFIG_MESH */
368 
369 
370 int wpa_auth_for_each_sta(struct wpa_authenticator *wpa_auth,
371 			  int (*cb)(struct wpa_state_machine *sm, void *ctx),
372 			  void *cb_ctx)
373 {
374 	if (!wpa_auth->cb->for_each_sta)
375 		return 0;
376 	return wpa_auth->cb->for_each_sta(wpa_auth->cb_ctx, cb, cb_ctx);
377 }
378 
379 
380 int wpa_auth_for_each_auth(struct wpa_authenticator *wpa_auth,
381 			   int (*cb)(struct wpa_authenticator *a, void *ctx),
382 			   void *cb_ctx)
383 {
384 	if (!wpa_auth->cb->for_each_auth)
385 		return 0;
386 	return wpa_auth->cb->for_each_auth(wpa_auth->cb_ctx, cb, cb_ctx);
387 }
388 
389 
390 void wpa_auth_store_ptksa(struct wpa_authenticator *wpa_auth,
391 			  const u8 *addr, int cipher,
392 			  u32 life_time, const struct wpa_ptk *ptk)
393 {
394 	if (wpa_auth->cb->store_ptksa)
395 		wpa_auth->cb->store_ptksa(wpa_auth->cb_ctx, addr, cipher,
396 					  life_time, ptk);
397 }
398 
399 
400 static void wpa_auth_remove_ptksa(struct wpa_authenticator *wpa_auth,
401 				  const u8 *addr, int cipher)
402 {
403 	if (wpa_auth->cb->clear_ptksa)
404 		wpa_auth->cb->clear_ptksa(wpa_auth->cb_ctx, addr, cipher);
405 }
406 
407 
408 void wpa_auth_logger(struct wpa_authenticator *wpa_auth, const u8 *addr,
409 		     logger_level level, const char *txt)
410 {
411 	if (!wpa_auth->cb->logger)
412 		return;
413 	wpa_auth->cb->logger(wpa_auth->cb_ctx, addr, level, txt);
414 }
415 
416 
417 void wpa_auth_vlogger(struct wpa_authenticator *wpa_auth, const u8 *addr,
418 		      logger_level level, const char *fmt, ...)
419 {
420 	char *format;
421 	int maxlen;
422 	va_list ap;
423 
424 	if (!wpa_auth->cb->logger)
425 		return;
426 
427 	maxlen = os_strlen(fmt) + 100;
428 	format = os_malloc(maxlen);
429 	if (!format)
430 		return;
431 
432 	va_start(ap, fmt);
433 	vsnprintf(format, maxlen, fmt, ap);
434 	va_end(ap);
435 
436 	wpa_auth_logger(wpa_auth, addr, level, format);
437 
438 	os_free(format);
439 }
440 
441 
442 static void wpa_sta_disconnect(struct wpa_authenticator *wpa_auth,
443 			       const u8 *addr, u16 reason)
444 {
445 	if (!wpa_auth->cb->disconnect)
446 		return;
447 	wpa_printf(MSG_DEBUG, "wpa_sta_disconnect STA " MACSTR " (reason %u)",
448 		   MAC2STR(addr), reason);
449 	wpa_auth->cb->disconnect(wpa_auth->cb_ctx, addr, reason);
450 }
451 
452 
453 #ifdef CONFIG_OCV
454 static int wpa_channel_info(struct wpa_authenticator *wpa_auth,
455 			    struct wpa_channel_info *ci)
456 {
457 	if (!wpa_auth->cb->channel_info)
458 		return -1;
459 	return wpa_auth->cb->channel_info(wpa_auth->cb_ctx, ci);
460 }
461 #endif /* CONFIG_OCV */
462 
463 
464 static int wpa_auth_update_vlan(struct wpa_authenticator *wpa_auth,
465 				const u8 *addr, int vlan_id)
466 {
467 	if (!wpa_auth->cb->update_vlan)
468 		return -1;
469 	return wpa_auth->cb->update_vlan(wpa_auth->cb_ctx, addr, vlan_id);
470 }
471 
472 
473 static void wpa_rekey_gmk(void *eloop_ctx, void *timeout_ctx)
474 {
475 	struct wpa_authenticator *wpa_auth = eloop_ctx;
476 
477 	if (random_get_bytes(wpa_auth->group->GMK, WPA_GMK_LEN)) {
478 		wpa_printf(MSG_ERROR,
479 			   "Failed to get random data for WPA initialization.");
480 	} else {
481 		wpa_auth_logger(wpa_auth, NULL, LOGGER_DEBUG, "GMK rekeyd");
482 		wpa_hexdump_key(MSG_DEBUG, "GMK",
483 				wpa_auth->group->GMK, WPA_GMK_LEN);
484 	}
485 
486 	if (wpa_auth->conf.wpa_gmk_rekey) {
487 		eloop_register_timeout(wpa_auth->conf.wpa_gmk_rekey, 0,
488 				       wpa_rekey_gmk, wpa_auth, NULL);
489 	}
490 }
491 
492 
493 static void wpa_rekey_all_groups(struct wpa_authenticator *wpa_auth)
494 {
495 	struct wpa_group *group, *next;
496 
497 	wpa_auth_logger(wpa_auth, NULL, LOGGER_DEBUG, "rekeying GTK");
498 	group = wpa_auth->group;
499 	while (group) {
500 		wpa_printf(MSG_DEBUG, "GTK rekey start for authenticator ("
501 			   MACSTR "), group vlan %d",
502 			   MAC2STR(wpa_auth->addr), group->vlan_id);
503 		wpa_group_get(wpa_auth, group);
504 
505 		group->GTKReKey = true;
506 		do {
507 			group->changed = false;
508 			wpa_group_sm_step(wpa_auth, group);
509 		} while (group->changed);
510 
511 		next = group->next;
512 		wpa_group_put(wpa_auth, group);
513 		group = next;
514 	}
515 }
516 
517 
518 #ifdef CONFIG_IEEE80211BE
519 
520 static void wpa_update_all_gtks(struct wpa_authenticator *wpa_auth)
521 {
522 	struct wpa_group *group, *next;
523 
524 	group = wpa_auth->group;
525 	while (group) {
526 		wpa_group_get(wpa_auth, group);
527 
528 		wpa_group_update_gtk(wpa_auth, group);
529 		next = group->next;
530 		wpa_group_put(wpa_auth, group);
531 		group = next;
532 	}
533 }
534 
535 
536 static int wpa_update_all_gtks_cb(struct wpa_authenticator *wpa_auth, void *ctx)
537 {
538 	const u8 *mld_addr = ctx;
539 
540 	if (!ether_addr_equal(wpa_auth->mld_addr, mld_addr))
541 		return 0;
542 
543 	wpa_update_all_gtks(wpa_auth);
544 	return 0;
545 }
546 
547 
548 static int wpa_rekey_all_groups_cb(struct wpa_authenticator *wpa_auth,
549 				   void *ctx)
550 {
551 	const u8 *mld_addr = ctx;
552 
553 	if (!ether_addr_equal(wpa_auth->mld_addr, mld_addr))
554 		return 0;
555 
556 	wpa_rekey_all_groups(wpa_auth);
557 	return 0;
558 }
559 
560 #endif /* CONFIG_IEEE80211BE */
561 
562 
563 static void wpa_rekey_gtk(void *eloop_ctx, void *timeout_ctx)
564 {
565 	struct wpa_authenticator *wpa_auth = eloop_ctx;
566 
567 #ifdef CONFIG_IEEE80211BE
568 	if (wpa_auth->is_ml) {
569 		/* Non-primary ML authenticator eloop timer for group rekey is
570 		 * never started and shouldn't fire. Check and warn just in
571 		 * case. */
572 		if (!wpa_auth->primary_auth) {
573 			wpa_printf(MSG_DEBUG,
574 				   "RSN: Cannot start GTK rekey on non-primary ML authenticator");
575 			return;
576 		}
577 
578 		/* Generate all the new group keys */
579 		wpa_auth_for_each_auth(wpa_auth, wpa_update_all_gtks_cb,
580 				       wpa_auth->mld_addr);
581 
582 		/* Send all the generated group keys to the respective stations
583 		 * with group key handshake. */
584 		wpa_auth_for_each_auth(wpa_auth, wpa_rekey_all_groups_cb,
585 				       wpa_auth->mld_addr);
586 	} else {
587 		wpa_rekey_all_groups(wpa_auth);
588 	}
589 #else /* CONFIG_IEEE80211BE */
590 	wpa_rekey_all_groups(wpa_auth);
591 #endif /* CONFIG_IEEE80211BE */
592 
593 	if (wpa_auth->conf.wpa_group_rekey) {
594 		eloop_register_timeout(wpa_auth->conf.wpa_group_rekey,
595 				       0, wpa_rekey_gtk, wpa_auth, NULL);
596 	}
597 }
598 
599 
600 static void wpa_rekey_ptk(void *eloop_ctx, void *timeout_ctx)
601 {
602 	struct wpa_authenticator *wpa_auth = eloop_ctx;
603 	struct wpa_state_machine *sm = timeout_ctx;
604 
605 	wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
606 			"rekeying PTK");
607 	wpa_request_new_ptk(sm);
608 	wpa_sm_step(sm);
609 }
610 
611 
612 void wpa_auth_set_ptk_rekey_timer(struct wpa_state_machine *sm)
613 {
614 	if (sm && sm->wpa_auth->conf.wpa_ptk_rekey) {
615 		wpa_printf(MSG_DEBUG, "WPA: Start PTK rekeying timer for "
616 			   MACSTR " (%d seconds)",
617 			   MAC2STR(wpa_auth_get_spa(sm)),
618 			   sm->wpa_auth->conf.wpa_ptk_rekey);
619 		eloop_cancel_timeout(wpa_rekey_ptk, sm->wpa_auth, sm);
620 		eloop_register_timeout(sm->wpa_auth->conf.wpa_ptk_rekey, 0,
621 				       wpa_rekey_ptk, sm->wpa_auth, sm);
622 	}
623 }
624 
625 
626 static int wpa_auth_pmksa_clear_cb(struct wpa_state_machine *sm, void *ctx)
627 {
628 	if (sm->pmksa == ctx)
629 		sm->pmksa = NULL;
630 	return 0;
631 }
632 
633 
634 static void wpa_auth_pmksa_free_cb(struct rsn_pmksa_cache_entry *entry,
635 				   void *ctx)
636 {
637 	struct wpa_authenticator *wpa_auth = ctx;
638 	wpa_auth_for_each_sta(wpa_auth, wpa_auth_pmksa_clear_cb, entry);
639 }
640 
641 
642 static int wpa_group_init_gmk_and_counter(struct wpa_authenticator *wpa_auth,
643 					  struct wpa_group *group)
644 {
645 	u8 buf[ETH_ALEN + 8 + sizeof(unsigned long)];
646 	u8 rkey[32];
647 	unsigned long ptr;
648 
649 	if (random_get_bytes(group->GMK, WPA_GMK_LEN) < 0)
650 		return -1;
651 	wpa_hexdump_key(MSG_DEBUG, "GMK", group->GMK, WPA_GMK_LEN);
652 
653 	/*
654 	 * Counter = PRF-256(Random number, "Init Counter",
655 	 *                   Local MAC Address || Time)
656 	 */
657 	os_memcpy(buf, wpa_auth->addr, ETH_ALEN);
658 	wpa_get_ntp_timestamp(buf + ETH_ALEN);
659 	ptr = (unsigned long) group;
660 	os_memcpy(buf + ETH_ALEN + 8, &ptr, sizeof(ptr));
661 #ifdef TEST_FUZZ
662 	os_memset(buf + ETH_ALEN, 0xab, 8);
663 	os_memset(buf + ETH_ALEN + 8, 0xcd, sizeof(ptr));
664 #endif /* TEST_FUZZ */
665 	if (random_get_bytes(rkey, sizeof(rkey)) < 0)
666 		return -1;
667 
668 	if (sha1_prf(rkey, sizeof(rkey), "Init Counter", buf, sizeof(buf),
669 		     group->Counter, WPA_NONCE_LEN) < 0)
670 		return -1;
671 	wpa_hexdump_key(MSG_DEBUG, "Key Counter",
672 			group->Counter, WPA_NONCE_LEN);
673 
674 	return 0;
675 }
676 
677 
678 static struct wpa_group * wpa_group_init(struct wpa_authenticator *wpa_auth,
679 					 int vlan_id, int delay_init)
680 {
681 	struct wpa_group *group;
682 
683 	group = os_zalloc(sizeof(struct wpa_group));
684 	if (!group)
685 		return NULL;
686 
687 	group->GTKAuthenticator = true;
688 	group->vlan_id = vlan_id;
689 	group->GTK_len = wpa_cipher_key_len(wpa_auth->conf.wpa_group);
690 
691 	if (random_pool_ready() != 1) {
692 		wpa_printf(MSG_INFO,
693 			   "WPA: Not enough entropy in random pool for secure operations - update keys later when the first station connects");
694 	}
695 
696 	/*
697 	 * Set initial GMK/Counter value here. The actual values that will be
698 	 * used in negotiations will be set once the first station tries to
699 	 * connect. This allows more time for collecting additional randomness
700 	 * on embedded devices.
701 	 */
702 	if (wpa_group_init_gmk_and_counter(wpa_auth, group) < 0) {
703 		wpa_printf(MSG_ERROR,
704 			   "Failed to get random data for WPA initialization.");
705 		os_free(group);
706 		return NULL;
707 	}
708 
709 	group->GInit = true;
710 	if (delay_init) {
711 		wpa_printf(MSG_DEBUG,
712 			   "WPA: Delay group state machine start until Beacon frames have been configured");
713 		/* Initialization is completed in wpa_init_keys(). */
714 	} else {
715 		wpa_group_sm_step(wpa_auth, group);
716 		group->GInit = false;
717 		wpa_group_sm_step(wpa_auth, group);
718 	}
719 
720 	return group;
721 }
722 
723 
724 /**
725  * wpa_init - Initialize WPA authenticator
726  * @addr: Authenticator address
727  * @conf: Configuration for WPA authenticator
728  * @cb: Callback functions for WPA authenticator
729  * Returns: Pointer to WPA authenticator data or %NULL on failure
730  */
731 struct wpa_authenticator * wpa_init(const u8 *addr,
732 				    struct wpa_auth_config *conf,
733 				    const struct wpa_auth_callbacks *cb,
734 				    void *cb_ctx)
735 {
736 	struct wpa_authenticator *wpa_auth;
737 
738 	wpa_auth = os_zalloc(sizeof(struct wpa_authenticator));
739 	if (!wpa_auth)
740 		return NULL;
741 
742 	os_memcpy(wpa_auth->addr, addr, ETH_ALEN);
743 	os_memcpy(&wpa_auth->conf, conf, sizeof(*conf));
744 
745 #ifdef CONFIG_IEEE80211BE
746 	if (conf->mld_addr) {
747 		wpa_auth->is_ml = true;
748 		wpa_auth->link_id = conf->link_id;
749 		wpa_auth->primary_auth = !conf->first_link_auth;
750 		os_memcpy(wpa_auth->mld_addr, conf->mld_addr, ETH_ALEN);
751 	}
752 #endif /* CONFIG_IEEE80211BE */
753 
754 	wpa_auth->cb = cb;
755 	wpa_auth->cb_ctx = cb_ctx;
756 
757 	if (wpa_auth_gen_wpa_ie(wpa_auth)) {
758 		wpa_printf(MSG_ERROR, "Could not generate WPA IE.");
759 		os_free(wpa_auth);
760 		return NULL;
761 	}
762 
763 	wpa_auth->group = wpa_group_init(wpa_auth, 0, 1);
764 	if (!wpa_auth->group) {
765 		os_free(wpa_auth->wpa_ie);
766 		os_free(wpa_auth);
767 		return NULL;
768 	}
769 
770 	wpa_auth->pmksa = pmksa_cache_auth_init(wpa_auth_pmksa_free_cb,
771 						wpa_auth);
772 	if (!wpa_auth->pmksa) {
773 		wpa_printf(MSG_ERROR, "PMKSA cache initialization failed.");
774 		os_free(wpa_auth->group);
775 		os_free(wpa_auth->wpa_ie);
776 		os_free(wpa_auth);
777 		return NULL;
778 	}
779 
780 #ifdef CONFIG_IEEE80211R_AP
781 	wpa_auth->ft_pmk_cache = wpa_ft_pmk_cache_init();
782 	if (!wpa_auth->ft_pmk_cache) {
783 		wpa_printf(MSG_ERROR, "FT PMK cache initialization failed.");
784 		os_free(wpa_auth->group);
785 		os_free(wpa_auth->wpa_ie);
786 		pmksa_cache_auth_deinit(wpa_auth->pmksa);
787 		os_free(wpa_auth);
788 		return NULL;
789 	}
790 #endif /* CONFIG_IEEE80211R_AP */
791 
792 	if (wpa_auth->conf.wpa_gmk_rekey) {
793 		eloop_register_timeout(wpa_auth->conf.wpa_gmk_rekey, 0,
794 				       wpa_rekey_gmk, wpa_auth, NULL);
795 	}
796 
797 #ifdef CONFIG_IEEE80211BE
798 	/* For AP MLD, run group rekey timer only on one link (first) and
799 	 * whenever it fires do rekey on all associated ML links in one shot.
800 	 */
801 	if ((!wpa_auth->is_ml || !conf->first_link_auth) &&
802 	    wpa_auth->conf.wpa_group_rekey) {
803 #else /* CONFIG_IEEE80211BE */
804 	if (wpa_auth->conf.wpa_group_rekey) {
805 #endif /* CONFIG_IEEE80211BE */
806 		eloop_register_timeout(wpa_auth->conf.wpa_group_rekey, 0,
807 				       wpa_rekey_gtk, wpa_auth, NULL);
808 	}
809 
810 #ifdef CONFIG_P2P
811 	if (WPA_GET_BE32(conf->ip_addr_start)) {
812 		int count = WPA_GET_BE32(conf->ip_addr_end) -
813 			WPA_GET_BE32(conf->ip_addr_start) + 1;
814 		if (count > 1000)
815 			count = 1000;
816 		if (count > 0)
817 			wpa_auth->ip_pool = bitfield_alloc(count);
818 	}
819 #endif /* CONFIG_P2P */
820 
821 	if (conf->tx_bss_auth && conf->beacon_prot) {
822 		conf->tx_bss_auth->non_tx_beacon_prot = true;
823 		if (!conf->tx_bss_auth->conf.beacon_prot)
824 			conf->tx_bss_auth->conf.beacon_prot = true;
825 		if (!conf->tx_bss_auth->conf.group_mgmt_cipher)
826 			conf->tx_bss_auth->conf.group_mgmt_cipher =
827 				conf->group_mgmt_cipher;
828 	}
829 
830 	return wpa_auth;
831 }
832 
833 
834 int wpa_init_keys(struct wpa_authenticator *wpa_auth)
835 {
836 	struct wpa_group *group = wpa_auth->group;
837 
838 	wpa_printf(MSG_DEBUG,
839 		   "WPA: Start group state machine to set initial keys");
840 	wpa_group_sm_step(wpa_auth, group);
841 	group->GInit = false;
842 	wpa_group_sm_step(wpa_auth, group);
843 	if (group->wpa_group_state == WPA_GROUP_FATAL_FAILURE)
844 		return -1;
845 	return 0;
846 }
847 
848 
849 static void wpa_auth_free_conf(struct wpa_auth_config *conf)
850 {
851 #ifdef CONFIG_TESTING_OPTIONS
852 	wpabuf_free(conf->eapol_m1_elements);
853 	conf->eapol_m1_elements = NULL;
854 	wpabuf_free(conf->eapol_m3_elements);
855 	conf->eapol_m3_elements = NULL;
856 #endif /* CONFIG_TESTING_OPTIONS */
857 }
858 
859 
860 /**
861  * wpa_deinit - Deinitialize WPA authenticator
862  * @wpa_auth: Pointer to WPA authenticator data from wpa_init()
863  */
864 void wpa_deinit(struct wpa_authenticator *wpa_auth)
865 {
866 	struct wpa_group *group, *prev;
867 
868 	eloop_cancel_timeout(wpa_rekey_gmk, wpa_auth, NULL);
869 
870 	/* TODO: Assign ML primary authenticator to next link authenticator and
871 	 * start rekey timer. */
872 	eloop_cancel_timeout(wpa_rekey_gtk, wpa_auth, NULL);
873 
874 	pmksa_cache_auth_deinit(wpa_auth->pmksa);
875 
876 #ifdef CONFIG_IEEE80211R_AP
877 	wpa_ft_pmk_cache_deinit(wpa_auth->ft_pmk_cache);
878 	wpa_auth->ft_pmk_cache = NULL;
879 	wpa_ft_deinit(wpa_auth);
880 #endif /* CONFIG_IEEE80211R_AP */
881 
882 #ifdef CONFIG_P2P
883 	bitfield_free(wpa_auth->ip_pool);
884 #endif /* CONFIG_P2P */
885 
886 
887 	os_free(wpa_auth->wpa_ie);
888 
889 	group = wpa_auth->group;
890 	while (group) {
891 		prev = group;
892 		group = group->next;
893 		bin_clear_free(prev, sizeof(*prev));
894 	}
895 
896 	wpa_auth_free_conf(&wpa_auth->conf);
897 	os_free(wpa_auth);
898 }
899 
900 
901 /**
902  * wpa_reconfig - Update WPA authenticator configuration
903  * @wpa_auth: Pointer to WPA authenticator data from wpa_init()
904  * @conf: Configuration for WPA authenticator
905  */
906 int wpa_reconfig(struct wpa_authenticator *wpa_auth,
907 		 struct wpa_auth_config *conf)
908 {
909 	struct wpa_group *group;
910 
911 	if (!wpa_auth)
912 		return 0;
913 
914 	wpa_auth_free_conf(&wpa_auth->conf);
915 	os_memcpy(&wpa_auth->conf, conf, sizeof(*conf));
916 	if (wpa_auth_gen_wpa_ie(wpa_auth)) {
917 		wpa_printf(MSG_ERROR, "Could not generate WPA IE.");
918 		return -1;
919 	}
920 
921 	/*
922 	 * Reinitialize GTK to make sure it is suitable for the new
923 	 * configuration.
924 	 */
925 	group = wpa_auth->group;
926 	group->GTK_len = wpa_cipher_key_len(wpa_auth->conf.wpa_group);
927 	group->GInit = true;
928 	wpa_group_sm_step(wpa_auth, group);
929 	group->GInit = false;
930 	wpa_group_sm_step(wpa_auth, group);
931 
932 	return 0;
933 }
934 
935 
936 struct wpa_state_machine *
937 wpa_auth_sta_init(struct wpa_authenticator *wpa_auth, const u8 *addr,
938 		  const u8 *p2p_dev_addr)
939 {
940 	struct wpa_state_machine *sm;
941 
942 	if (wpa_auth->group->wpa_group_state == WPA_GROUP_FATAL_FAILURE)
943 		return NULL;
944 
945 	sm = os_zalloc(sizeof(struct wpa_state_machine));
946 	if (!sm)
947 		return NULL;
948 	os_memcpy(sm->addr, addr, ETH_ALEN);
949 	if (p2p_dev_addr)
950 		os_memcpy(sm->p2p_dev_addr, p2p_dev_addr, ETH_ALEN);
951 
952 	sm->wpa_auth = wpa_auth;
953 	sm->group = wpa_auth->group;
954 	wpa_group_get(sm->wpa_auth, sm->group);
955 #ifdef CONFIG_IEEE80211BE
956 	sm->mld_assoc_link_id = -1;
957 #endif /* CONFIG_IEEE80211BE */
958 
959 	return sm;
960 }
961 
962 
963 int wpa_auth_sta_associated(struct wpa_authenticator *wpa_auth,
964 			    struct wpa_state_machine *sm)
965 {
966 	if (!wpa_auth || !wpa_auth->conf.wpa || !sm)
967 		return -1;
968 
969 #ifdef CONFIG_IEEE80211R_AP
970 	if (sm->ft_completed) {
971 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
972 				"FT authentication already completed - do not start 4-way handshake");
973 		/* Go to PTKINITDONE state to allow GTK rekeying */
974 		sm->wpa_ptk_state = WPA_PTK_PTKINITDONE;
975 		sm->Pair = true;
976 		return 0;
977 	}
978 #endif /* CONFIG_IEEE80211R_AP */
979 
980 #ifdef CONFIG_FILS
981 	if (sm->fils_completed) {
982 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
983 				"FILS authentication already completed - do not start 4-way handshake");
984 		/* Go to PTKINITDONE state to allow GTK rekeying */
985 		sm->wpa_ptk_state = WPA_PTK_PTKINITDONE;
986 		sm->Pair = true;
987 		return 0;
988 	}
989 #endif /* CONFIG_FILS */
990 
991 	if (sm->started) {
992 		os_memset(&sm->key_replay, 0, sizeof(sm->key_replay));
993 		sm->ReAuthenticationRequest = true;
994 		return wpa_sm_step(sm);
995 	}
996 
997 	wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
998 			"start authentication");
999 	sm->started = 1;
1000 
1001 	sm->Init = true;
1002 	if (wpa_sm_step(sm) == 1)
1003 		return 1; /* should not really happen */
1004 	sm->Init = false;
1005 	sm->AuthenticationRequest = true;
1006 	return wpa_sm_step(sm);
1007 }
1008 
1009 
1010 void wpa_auth_sta_no_wpa(struct wpa_state_machine *sm)
1011 {
1012 	/* WPA/RSN was not used - clear WPA state. This is needed if the STA
1013 	 * reassociates back to the same AP while the previous entry for the
1014 	 * STA has not yet been removed. */
1015 	if (!sm)
1016 		return;
1017 
1018 	sm->wpa_key_mgmt = 0;
1019 }
1020 
1021 
1022 static void wpa_free_sta_sm(struct wpa_state_machine *sm)
1023 {
1024 #ifdef CONFIG_IEEE80211BE
1025 	int link_id;
1026 #endif /* CONFIG_IEEE80211BE */
1027 
1028 #ifdef CONFIG_P2P
1029 	if (WPA_GET_BE32(sm->ip_addr)) {
1030 		wpa_printf(MSG_DEBUG,
1031 			   "P2P: Free assigned IP address %u.%u.%u.%u from "
1032 			   MACSTR " (bit %u)",
1033 			   sm->ip_addr[0], sm->ip_addr[1],
1034 			   sm->ip_addr[2], sm->ip_addr[3],
1035 			   MAC2STR(wpa_auth_get_spa(sm)),
1036 			   sm->ip_addr_bit);
1037 		bitfield_clear(sm->wpa_auth->ip_pool, sm->ip_addr_bit);
1038 	}
1039 #endif /* CONFIG_P2P */
1040 	if (sm->GUpdateStationKeys)
1041 		wpa_gkeydone_sta(sm);
1042 #ifdef CONFIG_IEEE80211R_AP
1043 	os_free(sm->assoc_resp_ftie);
1044 	wpabuf_free(sm->ft_pending_req_ies);
1045 #endif /* CONFIG_IEEE80211R_AP */
1046 	os_free(sm->last_rx_eapol_key);
1047 	os_free(sm->wpa_ie);
1048 	os_free(sm->rsnxe);
1049 #ifdef CONFIG_IEEE80211BE
1050 	for_each_sm_auth(sm, link_id) {
1051 		wpa_group_put(sm->mld_links[link_id].wpa_auth,
1052 			      sm->mld_links[link_id].wpa_auth->group);
1053 		sm->mld_links[link_id].wpa_auth = NULL;
1054 	}
1055 #endif /* CONFIG_IEEE80211BE */
1056 	wpa_group_put(sm->wpa_auth, sm->group);
1057 #ifdef CONFIG_DPP2
1058 	wpabuf_clear_free(sm->dpp_z);
1059 #endif /* CONFIG_DPP2 */
1060 	bin_clear_free(sm, sizeof(*sm));
1061 }
1062 
1063 
1064 void wpa_auth_sta_deinit(struct wpa_state_machine *sm)
1065 {
1066 	struct wpa_authenticator *wpa_auth;
1067 
1068 	if (!sm)
1069 		return;
1070 
1071 	wpa_auth = sm->wpa_auth;
1072 	if (wpa_auth->conf.wpa_strict_rekey && sm->has_GTK) {
1073 		struct wpa_authenticator *primary_auth = wpa_auth;
1074 
1075 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
1076 				"strict rekeying - force GTK rekey since STA is leaving");
1077 
1078 #ifdef CONFIG_IEEE80211BE
1079 		if (wpa_auth->is_ml && !wpa_auth->primary_auth)
1080 			primary_auth = wpa_get_primary_auth(wpa_auth);
1081 #endif /* CONFIG_IEEE80211BE */
1082 
1083 		if (eloop_deplete_timeout(0, 500000, wpa_rekey_gtk,
1084 					  primary_auth, NULL) == -1)
1085 			eloop_register_timeout(0, 500000, wpa_rekey_gtk,
1086 					       primary_auth, NULL);
1087 	}
1088 
1089 	eloop_cancel_timeout(wpa_send_eapol_timeout, wpa_auth, sm);
1090 	sm->pending_1_of_4_timeout = 0;
1091 	eloop_cancel_timeout(wpa_sm_call_step, sm, NULL);
1092 	eloop_cancel_timeout(wpa_rekey_ptk, wpa_auth, sm);
1093 #ifdef CONFIG_IEEE80211R_AP
1094 	wpa_ft_sta_deinit(sm);
1095 #endif /* CONFIG_IEEE80211R_AP */
1096 	if (sm->in_step_loop) {
1097 		/* Must not free state machine while wpa_sm_step() is running.
1098 		 * Freeing will be completed in the end of wpa_sm_step(). */
1099 		wpa_printf(MSG_DEBUG,
1100 			   "WPA: Registering pending STA state machine deinit for "
1101 			   MACSTR, MAC2STR(wpa_auth_get_spa(sm)));
1102 		sm->pending_deinit = 1;
1103 	} else
1104 		wpa_free_sta_sm(sm);
1105 }
1106 
1107 
1108 static void wpa_request_new_ptk(struct wpa_state_machine *sm)
1109 {
1110 	if (!sm)
1111 		return;
1112 
1113 	if (!sm->use_ext_key_id && sm->wpa_auth->conf.wpa_deny_ptk0_rekey) {
1114 		wpa_printf(MSG_INFO,
1115 			   "WPA: PTK0 rekey not allowed, disconnect " MACSTR,
1116 			   MAC2STR(wpa_auth_get_spa(sm)));
1117 		sm->Disconnect = true;
1118 		/* Try to encourage the STA to reconnect */
1119 		sm->disconnect_reason =
1120 			WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA;
1121 	} else {
1122 		if (sm->use_ext_key_id)
1123 			sm->keyidx_active ^= 1; /* flip Key ID */
1124 		sm->PTKRequest = true;
1125 		sm->PTK_valid = 0;
1126 	}
1127 }
1128 
1129 
1130 static int wpa_replay_counter_valid(struct wpa_key_replay_counter *ctr,
1131 				    const u8 *replay_counter)
1132 {
1133 	int i;
1134 	for (i = 0; i < RSNA_MAX_EAPOL_RETRIES; i++) {
1135 		if (!ctr[i].valid)
1136 			break;
1137 		if (os_memcmp(replay_counter, ctr[i].counter,
1138 			      WPA_REPLAY_COUNTER_LEN) == 0)
1139 			return 1;
1140 	}
1141 	return 0;
1142 }
1143 
1144 
1145 static void wpa_replay_counter_mark_invalid(struct wpa_key_replay_counter *ctr,
1146 					    const u8 *replay_counter)
1147 {
1148 	int i;
1149 	for (i = 0; i < RSNA_MAX_EAPOL_RETRIES; i++) {
1150 		if (ctr[i].valid &&
1151 		    (!replay_counter ||
1152 		     os_memcmp(replay_counter, ctr[i].counter,
1153 			       WPA_REPLAY_COUNTER_LEN) == 0))
1154 			ctr[i].valid = false;
1155 	}
1156 }
1157 
1158 
1159 #ifdef CONFIG_IEEE80211R_AP
1160 static int ft_check_msg_2_of_4(struct wpa_authenticator *wpa_auth,
1161 			       struct wpa_state_machine *sm,
1162 			       struct wpa_eapol_ie_parse *kde)
1163 {
1164 	struct wpa_ie_data ie, assoc_ie;
1165 	struct rsn_mdie *mdie;
1166 	unsigned int i, j;
1167 	bool found = false;
1168 
1169 	/* Verify that PMKR1Name from EAPOL-Key message 2/4 matches the value
1170 	 * we derived. */
1171 
1172 	if (wpa_parse_wpa_ie_rsn(kde->rsn_ie, kde->rsn_ie_len, &ie) < 0 ||
1173 	    ie.num_pmkid < 1 || !ie.pmkid) {
1174 		wpa_printf(MSG_DEBUG,
1175 			   "FT: No PMKR1Name in FT 4-way handshake message 2/4");
1176 		return -1;
1177 	}
1178 
1179 	if (wpa_parse_wpa_ie_rsn(sm->wpa_ie, sm->wpa_ie_len, &assoc_ie) < 0) {
1180 		wpa_printf(MSG_DEBUG,
1181 			   "FT: Could not parse (Re)Association Request frame RSNE");
1182 		os_memset(&assoc_ie, 0, sizeof(assoc_ie));
1183 		/* Continue to allow PMKR1Name matching to be done to cover the
1184 		 * case where it is the only listed PMKID. */
1185 	}
1186 
1187 	for (i = 0; i < ie.num_pmkid; i++) {
1188 		const u8 *pmkid = ie.pmkid + i * PMKID_LEN;
1189 
1190 		if (os_memcmp_const(pmkid, sm->pmk_r1_name,
1191 				    WPA_PMK_NAME_LEN) == 0) {
1192 			wpa_printf(MSG_DEBUG,
1193 				   "FT: RSNE[PMKID[%u]] from supplicant matches PMKR1Name",
1194 				   i);
1195 			found = true;
1196 		} else {
1197 			for (j = 0; j < assoc_ie.num_pmkid; j++) {
1198 				if (os_memcmp(pmkid,
1199 					      assoc_ie.pmkid + j * PMKID_LEN,
1200 					      PMKID_LEN) == 0)
1201 					break;
1202 			}
1203 
1204 			if (j == assoc_ie.num_pmkid) {
1205 				wpa_printf(MSG_DEBUG,
1206 					   "FT: RSNE[PMKID[%u]] from supplicant is neither PMKR1Name nor included in AssocReq",
1207 					   i);
1208 				found = false;
1209 				break;
1210 			}
1211 			wpa_printf(MSG_DEBUG,
1212 				   "FT: RSNE[PMKID[%u]] from supplicant is not PMKR1Name, but matches a PMKID in AssocReq",
1213 				   i);
1214 		}
1215 	}
1216 
1217 	if (!found) {
1218 		wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm),
1219 				LOGGER_DEBUG,
1220 				"PMKR1Name mismatch in FT 4-way handshake");
1221 		wpa_hexdump(MSG_DEBUG,
1222 			    "FT: PMKIDs/PMKR1Name from Supplicant",
1223 			    ie.pmkid, ie.num_pmkid * PMKID_LEN);
1224 		wpa_hexdump(MSG_DEBUG, "FT: Derived PMKR1Name",
1225 			    sm->pmk_r1_name, WPA_PMK_NAME_LEN);
1226 		return -1;
1227 	}
1228 
1229 	if (!kde->mdie || !kde->ftie) {
1230 		wpa_printf(MSG_DEBUG,
1231 			   "FT: No %s in FT 4-way handshake message 2/4",
1232 			   kde->mdie ? "FTIE" : "MDIE");
1233 		return -1;
1234 	}
1235 
1236 	mdie = (struct rsn_mdie *) (kde->mdie + 2);
1237 	if (kde->mdie[1] < sizeof(struct rsn_mdie) ||
1238 	    os_memcmp(wpa_auth->conf.mobility_domain, mdie->mobility_domain,
1239 		      MOBILITY_DOMAIN_ID_LEN) != 0) {
1240 		wpa_printf(MSG_DEBUG, "FT: MDIE mismatch");
1241 		return -1;
1242 	}
1243 
1244 	if (sm->assoc_resp_ftie &&
1245 	    (kde->ftie[1] != sm->assoc_resp_ftie[1] ||
1246 	     os_memcmp(kde->ftie, sm->assoc_resp_ftie,
1247 		       2 + sm->assoc_resp_ftie[1]) != 0)) {
1248 		wpa_printf(MSG_DEBUG, "FT: FTIE mismatch");
1249 		wpa_hexdump(MSG_DEBUG, "FT: FTIE in EAPOL-Key msg 2/4",
1250 			    kde->ftie, kde->ftie_len);
1251 		wpa_hexdump(MSG_DEBUG, "FT: FTIE in (Re)AssocResp",
1252 			    sm->assoc_resp_ftie, 2 + sm->assoc_resp_ftie[1]);
1253 		return -1;
1254 	}
1255 
1256 	return 0;
1257 }
1258 #endif /* CONFIG_IEEE80211R_AP */
1259 
1260 
1261 static int wpa_receive_error_report(struct wpa_authenticator *wpa_auth,
1262 				    struct wpa_state_machine *sm, int group)
1263 {
1264 	/* Supplicant reported a Michael MIC error */
1265 	wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
1266 			 "received EAPOL-Key Error Request (STA detected Michael MIC failure (group=%d))",
1267 			 group);
1268 
1269 	if (group && wpa_auth->conf.wpa_group != WPA_CIPHER_TKIP) {
1270 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
1271 				"ignore Michael MIC failure report since group cipher is not TKIP");
1272 	} else if (!group && sm->pairwise != WPA_CIPHER_TKIP) {
1273 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
1274 				"ignore Michael MIC failure report since pairwise cipher is not TKIP");
1275 	} else {
1276 		if (wpa_auth_mic_failure_report(wpa_auth,
1277 						wpa_auth_get_spa(sm)) > 0)
1278 			return 1; /* STA entry was removed */
1279 		sm->dot11RSNAStatsTKIPRemoteMICFailures++;
1280 		wpa_auth->dot11RSNAStatsTKIPRemoteMICFailures++;
1281 	}
1282 
1283 	/*
1284 	 * Error report is not a request for a new key handshake, but since
1285 	 * Authenticator may do it, let's change the keys now anyway.
1286 	 */
1287 	wpa_request_new_ptk(sm);
1288 	return 0;
1289 }
1290 
1291 
1292 static int wpa_try_alt_snonce(struct wpa_state_machine *sm, u8 *data,
1293 			      size_t data_len)
1294 {
1295 	struct wpa_ptk PTK;
1296 	int ok = 0;
1297 	const u8 *pmk = NULL;
1298 	size_t pmk_len;
1299 	int vlan_id = 0;
1300 	u8 pmk_r0[PMK_LEN_MAX], pmk_r0_name[WPA_PMK_NAME_LEN];
1301 	u8 pmk_r1[PMK_LEN_MAX];
1302 	size_t key_len;
1303 	int ret = -1;
1304 
1305 	os_memset(&PTK, 0, sizeof(PTK));
1306 	for (;;) {
1307 		if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) &&
1308 		    !wpa_key_mgmt_sae(sm->wpa_key_mgmt)) {
1309 			pmk = wpa_auth_get_psk(sm->wpa_auth, sm->addr,
1310 					       sm->p2p_dev_addr, pmk, &pmk_len,
1311 					       &vlan_id);
1312 			if (!pmk)
1313 				break;
1314 #ifdef CONFIG_IEEE80211R_AP
1315 			if (wpa_key_mgmt_ft_psk(sm->wpa_key_mgmt)) {
1316 				os_memcpy(sm->xxkey, pmk, pmk_len);
1317 				sm->xxkey_len = pmk_len;
1318 			}
1319 #endif /* CONFIG_IEEE80211R_AP */
1320 		} else {
1321 			pmk = sm->PMK;
1322 			pmk_len = sm->pmk_len;
1323 		}
1324 
1325 		if (wpa_derive_ptk(sm, sm->alt_SNonce, pmk, pmk_len, &PTK, 0,
1326 				   pmk_r0, pmk_r1, pmk_r0_name, &key_len,
1327 				   false) < 0)
1328 			break;
1329 
1330 		if (wpa_verify_key_mic(sm->wpa_key_mgmt, pmk_len, &PTK,
1331 				       data, data_len) == 0) {
1332 			if (sm->PMK != pmk) {
1333 				os_memcpy(sm->PMK, pmk, pmk_len);
1334 				sm->pmk_len = pmk_len;
1335 			}
1336 			ok = 1;
1337 			break;
1338 		}
1339 
1340 		if (!wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) ||
1341 		    wpa_key_mgmt_sae(sm->wpa_key_mgmt))
1342 			break;
1343 	}
1344 
1345 	if (!ok) {
1346 		wpa_printf(MSG_DEBUG,
1347 			   "WPA: Earlier SNonce did not result in matching MIC");
1348 		goto fail;
1349 	}
1350 
1351 	wpa_printf(MSG_DEBUG,
1352 		   "WPA: Earlier SNonce resulted in matching MIC");
1353 	sm->alt_snonce_valid = 0;
1354 
1355 	if (vlan_id && wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) &&
1356 	    wpa_auth_update_vlan(sm->wpa_auth, sm->addr, vlan_id) < 0)
1357 		goto fail;
1358 
1359 #ifdef CONFIG_IEEE80211R_AP
1360 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt) && !sm->ft_completed) {
1361 		wpa_printf(MSG_DEBUG, "FT: Store PMK-R0/PMK-R1");
1362 		wpa_auth_ft_store_keys(sm, pmk_r0, pmk_r1, pmk_r0_name,
1363 				       key_len);
1364 	}
1365 #endif /* CONFIG_IEEE80211R_AP */
1366 
1367 	os_memcpy(sm->SNonce, sm->alt_SNonce, WPA_NONCE_LEN);
1368 	os_memcpy(&sm->PTK, &PTK, sizeof(PTK));
1369 	forced_memzero(&PTK, sizeof(PTK));
1370 	sm->PTK_valid = true;
1371 
1372 	ret = 0;
1373 fail:
1374 	forced_memzero(pmk_r0, sizeof(pmk_r0));
1375 	forced_memzero(pmk_r1, sizeof(pmk_r1));
1376 	return ret;
1377 }
1378 
1379 
1380 static bool wpa_auth_gtk_rekey_in_process(struct wpa_authenticator *wpa_auth)
1381 {
1382 	struct wpa_group *group;
1383 
1384 	for (group = wpa_auth->group; group; group = group->next) {
1385 		if (group->GKeyDoneStations)
1386 			return true;
1387 	}
1388 	return false;
1389 }
1390 
1391 
1392 enum eapol_key_msg { PAIRWISE_2, PAIRWISE_4, GROUP_2, REQUEST };
1393 
1394 static bool wpa_auth_valid_key_desc_ver(struct wpa_authenticator *wpa_auth,
1395 					struct wpa_state_machine *sm, u16 ver)
1396 {
1397 	if (ver > WPA_KEY_INFO_TYPE_AES_128_CMAC) {
1398 		wpa_printf(MSG_INFO, "RSN: " MACSTR
1399 			   " used undefined Key Descriptor Version %d",
1400 			   MAC2STR(wpa_auth_get_spa(sm)), ver);
1401 		return false;
1402 	}
1403 
1404 	if (!wpa_use_akm_defined(sm->wpa_key_mgmt) &&
1405 	    wpa_use_cmac(sm->wpa_key_mgmt) &&
1406 	    ver != WPA_KEY_INFO_TYPE_AES_128_CMAC) {
1407 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1408 				LOGGER_WARNING,
1409 				"advertised support for AES-128-CMAC, but did not use it");
1410 		return false;
1411 	}
1412 
1413 	if (sm->pairwise != WPA_CIPHER_TKIP &&
1414 	    !wpa_use_akm_defined(sm->wpa_key_mgmt) &&
1415 	    !wpa_use_cmac(sm->wpa_key_mgmt) &&
1416 	    ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1417 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1418 				LOGGER_WARNING,
1419 				"did not use HMAC-SHA1-AES with CCMP/GCMP");
1420 		return false;
1421 	}
1422 
1423 	if (wpa_use_akm_defined(sm->wpa_key_mgmt) &&
1424 	    ver != WPA_KEY_INFO_TYPE_AKM_DEFINED) {
1425 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1426 				LOGGER_WARNING,
1427 				"did not use EAPOL-Key descriptor version 0 as required for AKM-defined cases");
1428 		return false;
1429 	}
1430 
1431 	return true;
1432 }
1433 
1434 
1435 static bool wpa_auth_valid_request_counter(struct wpa_authenticator *wpa_auth,
1436 					   struct wpa_state_machine *sm,
1437 					   const u8 *replay_counter)
1438 {
1439 
1440 	if (sm->req_replay_counter_used &&
1441 	    os_memcmp(replay_counter, sm->req_replay_counter,
1442 		      WPA_REPLAY_COUNTER_LEN) <= 0) {
1443 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1444 				LOGGER_WARNING,
1445 				"received EAPOL-Key request with replayed counter");
1446 		return false;
1447 	}
1448 
1449 	return true;
1450 }
1451 
1452 
1453 static bool wpa_auth_valid_counter(struct wpa_authenticator *wpa_auth,
1454 				   struct wpa_state_machine *sm,
1455 				   const struct wpa_eapol_key *key,
1456 				   enum eapol_key_msg msg,
1457 				   const char *msgtxt)
1458 {
1459 	int i;
1460 
1461 	if (msg == REQUEST)
1462 		return wpa_auth_valid_request_counter(wpa_auth, sm,
1463 						      key->replay_counter);
1464 
1465 	if (wpa_replay_counter_valid(sm->key_replay, key->replay_counter))
1466 		return true;
1467 
1468 	if (msg == PAIRWISE_2 &&
1469 	    wpa_replay_counter_valid(sm->prev_key_replay,
1470 				     key->replay_counter) &&
1471 	    sm->wpa_ptk_state == WPA_PTK_PTKINITNEGOTIATING &&
1472 	    os_memcmp(sm->SNonce, key->key_nonce, WPA_NONCE_LEN) != 0) {
1473 		/*
1474 		 * Some supplicant implementations (e.g., Windows XP
1475 		 * WZC) update SNonce for each EAPOL-Key 2/4. This
1476 		 * breaks the workaround on accepting any of the
1477 		 * pending requests, so allow the SNonce to be updated
1478 		 * even if we have already sent out EAPOL-Key 3/4.
1479 		 */
1480 		wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
1481 				 LOGGER_DEBUG,
1482 				 "Process SNonce update from STA based on retransmitted EAPOL-Key 1/4");
1483 		sm->update_snonce = 1;
1484 		os_memcpy(sm->alt_SNonce, sm->SNonce, WPA_NONCE_LEN);
1485 		sm->alt_snonce_valid = true;
1486 		os_memcpy(sm->alt_replay_counter,
1487 			  sm->key_replay[0].counter,
1488 			  WPA_REPLAY_COUNTER_LEN);
1489 		return true;
1490 	}
1491 
1492 	if (msg == PAIRWISE_4 && sm->alt_snonce_valid &&
1493 	    sm->wpa_ptk_state == WPA_PTK_PTKINITNEGOTIATING &&
1494 	    os_memcmp(key->replay_counter, sm->alt_replay_counter,
1495 		      WPA_REPLAY_COUNTER_LEN) == 0) {
1496 		/*
1497 		 * Supplicant may still be using the old SNonce since
1498 		 * there was two EAPOL-Key 2/4 messages and they had
1499 		 * different SNonce values.
1500 		 */
1501 		wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
1502 				 LOGGER_DEBUG,
1503 				 "Try to process received EAPOL-Key 4/4 based on old Replay Counter and SNonce from an earlier EAPOL-Key 1/4");
1504 		return true;
1505 	}
1506 
1507 	if (msg == PAIRWISE_2 &&
1508 	    wpa_replay_counter_valid(sm->prev_key_replay,
1509 				     key->replay_counter) &&
1510 	    sm->wpa_ptk_state == WPA_PTK_PTKINITNEGOTIATING) {
1511 		wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
1512 				 LOGGER_DEBUG,
1513 				 "ignore retransmitted EAPOL-Key %s - SNonce did not change",
1514 				 msgtxt);
1515 	} else {
1516 		wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
1517 				 LOGGER_DEBUG,
1518 				 "received EAPOL-Key %s with unexpected replay counter",
1519 				 msgtxt);
1520 	}
1521 	for (i = 0; i < RSNA_MAX_EAPOL_RETRIES; i++) {
1522 		if (!sm->key_replay[i].valid)
1523 			break;
1524 		wpa_hexdump(MSG_DEBUG, "pending replay counter",
1525 			    sm->key_replay[i].counter,
1526 			    WPA_REPLAY_COUNTER_LEN);
1527 	}
1528 	wpa_hexdump(MSG_DEBUG, "received replay counter",
1529 		    key->replay_counter, WPA_REPLAY_COUNTER_LEN);
1530 	return false;
1531 }
1532 
1533 
1534 void wpa_receive(struct wpa_authenticator *wpa_auth,
1535 		 struct wpa_state_machine *sm,
1536 		 u8 *data, size_t data_len)
1537 {
1538 	struct ieee802_1x_hdr *hdr;
1539 	struct wpa_eapol_key *key;
1540 	u16 key_info, ver, key_data_length;
1541 	enum eapol_key_msg msg;
1542 	const char *msgtxt;
1543 	const u8 *key_data;
1544 	size_t keyhdrlen, mic_len;
1545 	u8 *mic;
1546 	u8 *key_data_buf = NULL;
1547 	size_t key_data_buf_len = 0;
1548 
1549 	if (!wpa_auth || !wpa_auth->conf.wpa || !sm)
1550 		return;
1551 
1552 	wpa_hexdump(MSG_MSGDUMP, "WPA: RX EAPOL data", data, data_len);
1553 
1554 	mic_len = wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len);
1555 	keyhdrlen = sizeof(*key) + mic_len + 2;
1556 
1557 	if (data_len < sizeof(*hdr) + keyhdrlen) {
1558 		wpa_printf(MSG_DEBUG, "WPA: Ignore too short EAPOL-Key frame");
1559 		return;
1560 	}
1561 
1562 	hdr = (struct ieee802_1x_hdr *) data;
1563 	key = (struct wpa_eapol_key *) (hdr + 1);
1564 	mic = (u8 *) (key + 1);
1565 	key_info = WPA_GET_BE16(key->key_info);
1566 	key_data = mic + mic_len + 2;
1567 	key_data_length = WPA_GET_BE16(mic + mic_len);
1568 	wpa_printf(MSG_DEBUG, "WPA: Received EAPOL-Key from " MACSTR
1569 		   " key_info=0x%x type=%u mic_len=%zu key_data_length=%u",
1570 		   MAC2STR(wpa_auth_get_spa(sm)), key_info, key->type,
1571 		   mic_len, key_data_length);
1572 	wpa_hexdump(MSG_MSGDUMP,
1573 		    "WPA: EAPOL-Key header (ending before Key MIC)",
1574 		    key, sizeof(*key));
1575 	wpa_hexdump(MSG_MSGDUMP, "WPA: EAPOL-Key Key MIC",
1576 		    mic, mic_len);
1577 	if (key_data_length > data_len - sizeof(*hdr) - keyhdrlen) {
1578 		wpa_printf(MSG_INFO,
1579 			   "WPA: Invalid EAPOL-Key frame - key_data overflow (%d > %zu)",
1580 			   key_data_length,
1581 			   data_len - sizeof(*hdr) - keyhdrlen);
1582 		return;
1583 	}
1584 
1585 	if (sm->wpa == WPA_VERSION_WPA2) {
1586 		if (key->type == EAPOL_KEY_TYPE_WPA) {
1587 			/*
1588 			 * Some deployed station implementations seem to send
1589 			 * msg 4/4 with incorrect type value in WPA2 mode.
1590 			 */
1591 			wpa_printf(MSG_DEBUG,
1592 				   "Workaround: Allow EAPOL-Key with unexpected WPA type in RSN mode");
1593 		} else if (key->type != EAPOL_KEY_TYPE_RSN) {
1594 			wpa_printf(MSG_DEBUG,
1595 				   "Ignore EAPOL-Key with unexpected type %d in RSN mode",
1596 				   key->type);
1597 			return;
1598 		}
1599 	} else {
1600 		if (key->type != EAPOL_KEY_TYPE_WPA) {
1601 			wpa_printf(MSG_DEBUG,
1602 				   "Ignore EAPOL-Key with unexpected type %d in WPA mode",
1603 				   key->type);
1604 			return;
1605 		}
1606 	}
1607 
1608 	wpa_hexdump(MSG_DEBUG, "WPA: Received Key Nonce", key->key_nonce,
1609 		    WPA_NONCE_LEN);
1610 	wpa_hexdump(MSG_DEBUG, "WPA: Received Replay Counter",
1611 		    key->replay_counter, WPA_REPLAY_COUNTER_LEN);
1612 
1613 	/* FIX: verify that the EAPOL-Key frame was encrypted if pairwise keys
1614 	 * are set */
1615 
1616 	if (key_info & WPA_KEY_INFO_SMK_MESSAGE) {
1617 		wpa_printf(MSG_DEBUG, "WPA: Ignore SMK message");
1618 		return;
1619 	}
1620 
1621 	ver = key_info & WPA_KEY_INFO_TYPE_MASK;
1622 	if (!wpa_auth_valid_key_desc_ver(wpa_auth, sm, ver))
1623 		goto out;
1624 	if (mic_len > 0 && (key_info & WPA_KEY_INFO_ENCR_KEY_DATA) &&
1625 	    sm->PTK_valid &&
1626 	    (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES ||
1627 	     ver == WPA_KEY_INFO_TYPE_AES_128_CMAC ||
1628 	     wpa_use_aes_key_wrap(sm->wpa_key_mgmt)) &&
1629 	    key_data_length >= 8 && key_data_length % 8 == 0) {
1630 		key_data_length -= 8; /* AES-WRAP adds 8 bytes */
1631 		key_data_buf = os_malloc(key_data_length);
1632 		if (!key_data_buf)
1633 			goto out;
1634 		key_data_buf_len = key_data_length;
1635 		if (aes_unwrap(sm->PTK.kek, sm->PTK.kek_len,
1636 			       key_data_length / 8, key_data, key_data_buf)) {
1637 			wpa_printf(MSG_INFO,
1638 				   "RSN: AES unwrap failed - could not decrypt EAPOL-Key key data");
1639 			goto out;
1640 		}
1641 		key_data = key_data_buf;
1642 		wpa_hexdump_key(MSG_DEBUG, "RSN: Decrypted EAPOL-Key Key Data",
1643 				key_data, key_data_length);
1644 	}
1645 
1646 	if (key_info & WPA_KEY_INFO_REQUEST) {
1647 		msg = REQUEST;
1648 		msgtxt = "Request";
1649 	} else if (!(key_info & WPA_KEY_INFO_KEY_TYPE)) {
1650 		msg = GROUP_2;
1651 		msgtxt = "2/2 Group";
1652 	} else if (key_data_length == 0 ||
1653 		   (sm->wpa == WPA_VERSION_WPA2 &&
1654 		    (!(key_info & WPA_KEY_INFO_ENCR_KEY_DATA) ||
1655 		     key_data_buf) &&
1656 		    (key_info & WPA_KEY_INFO_SECURE) &&
1657 		    !get_ie(key_data, key_data_length, WLAN_EID_RSN)) ||
1658 		   (mic_len == 0 && (key_info & WPA_KEY_INFO_ENCR_KEY_DATA) &&
1659 		    key_data_length == AES_BLOCK_SIZE)) {
1660 		msg = PAIRWISE_4;
1661 		msgtxt = "4/4 Pairwise";
1662 	} else {
1663 		msg = PAIRWISE_2;
1664 		msgtxt = "2/4 Pairwise";
1665 	}
1666 
1667 	if (!wpa_auth_valid_counter(wpa_auth, sm, key, msg, msgtxt))
1668 		goto out;
1669 
1670 #ifdef CONFIG_FILS
1671 	if (sm->wpa == WPA_VERSION_WPA2 && mic_len == 0 &&
1672 	    !(key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
1673 		wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
1674 				 "WPA: Encr Key Data bit not set even though AEAD cipher is supposed to be used - drop frame");
1675 		goto out;
1676 	}
1677 #endif /* CONFIG_FILS */
1678 
1679 	switch (msg) {
1680 	case PAIRWISE_2:
1681 		if (sm->wpa_ptk_state != WPA_PTK_PTKSTART &&
1682 		    sm->wpa_ptk_state != WPA_PTK_PTKCALCNEGOTIATING &&
1683 		    (!sm->update_snonce ||
1684 		     sm->wpa_ptk_state != WPA_PTK_PTKINITNEGOTIATING)) {
1685 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
1686 					 LOGGER_INFO,
1687 					 "received EAPOL-Key msg 2/4 in invalid state (%d) - dropped",
1688 					 sm->wpa_ptk_state);
1689 			goto out;
1690 		}
1691 		random_add_randomness(key->key_nonce, WPA_NONCE_LEN);
1692 		if (sm->group->reject_4way_hs_for_entropy) {
1693 			/*
1694 			 * The system did not have enough entropy to generate
1695 			 * strong random numbers. Reject the first 4-way
1696 			 * handshake(s) and collect some entropy based on the
1697 			 * information from it. Once enough entropy is
1698 			 * available, the next atempt will trigger GMK/Key
1699 			 * Counter update and the station will be allowed to
1700 			 * continue.
1701 			 */
1702 			wpa_printf(MSG_DEBUG,
1703 				   "WPA: Reject 4-way handshake to collect more entropy for random number generation");
1704 			random_mark_pool_ready();
1705 			wpa_sta_disconnect(wpa_auth, sm->addr,
1706 					   WLAN_REASON_PREV_AUTH_NOT_VALID);
1707 			goto out;
1708 		}
1709 		break;
1710 	case PAIRWISE_4:
1711 		if (sm->wpa_ptk_state != WPA_PTK_PTKINITNEGOTIATING ||
1712 		    !sm->PTK_valid) {
1713 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
1714 					 LOGGER_INFO,
1715 					 "received EAPOL-Key msg 4/4 in invalid state (%d) - dropped",
1716 					 sm->wpa_ptk_state);
1717 			goto out;
1718 		}
1719 		break;
1720 	case GROUP_2:
1721 		if (sm->wpa_ptk_group_state != WPA_PTK_GROUP_REKEYNEGOTIATING
1722 		    || !sm->PTK_valid) {
1723 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
1724 					 LOGGER_INFO,
1725 					 "received EAPOL-Key msg 2/2 in invalid state (%d) - dropped",
1726 					 sm->wpa_ptk_group_state);
1727 			goto out;
1728 		}
1729 		break;
1730 	case REQUEST:
1731 		if (sm->wpa_ptk_state == WPA_PTK_PTKSTART ||
1732 		    sm->wpa_ptk_state == WPA_PTK_PTKCALCNEGOTIATING ||
1733 		    sm->wpa_ptk_state == WPA_PTK_PTKCALCNEGOTIATING2 ||
1734 		    sm->wpa_ptk_state == WPA_PTK_PTKINITNEGOTIATING) {
1735 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
1736 					 LOGGER_INFO,
1737 					 "received EAPOL-Key Request in invalid state (%d) - dropped",
1738 					 sm->wpa_ptk_state);
1739 			goto out;
1740 		}
1741 		break;
1742 	}
1743 
1744 	wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
1745 			 "received EAPOL-Key frame (%s)", msgtxt);
1746 
1747 	if (key_info & WPA_KEY_INFO_ACK) {
1748 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
1749 				"received invalid EAPOL-Key: Key Ack set");
1750 		goto out;
1751 	}
1752 
1753 	if (!wpa_key_mgmt_fils(sm->wpa_key_mgmt) &&
1754 	    !(key_info & WPA_KEY_INFO_MIC)) {
1755 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
1756 				"received invalid EAPOL-Key: Key MIC not set");
1757 		goto out;
1758 	}
1759 
1760 #ifdef CONFIG_FILS
1761 	if (wpa_key_mgmt_fils(sm->wpa_key_mgmt) &&
1762 	    (key_info & WPA_KEY_INFO_MIC)) {
1763 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
1764 				"received invalid EAPOL-Key: Key MIC set");
1765 		goto out;
1766 	}
1767 #endif /* CONFIG_FILS */
1768 
1769 	sm->MICVerified = false;
1770 	if (sm->PTK_valid && !sm->update_snonce) {
1771 		if (mic_len &&
1772 		    wpa_verify_key_mic(sm->wpa_key_mgmt, sm->pmk_len, &sm->PTK,
1773 				       data, data_len) &&
1774 		    (msg != PAIRWISE_4 || !sm->alt_snonce_valid ||
1775 		     wpa_try_alt_snonce(sm, data, data_len))) {
1776 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1777 					LOGGER_INFO,
1778 					"received EAPOL-Key with invalid MIC");
1779 #ifdef TEST_FUZZ
1780 			wpa_printf(MSG_INFO,
1781 				   "TEST: Ignore Key MIC failure for fuzz testing");
1782 			goto continue_fuzz;
1783 #endif /* TEST_FUZZ */
1784 			goto out;
1785 		}
1786 #ifdef CONFIG_FILS
1787 		if (!mic_len &&
1788 		    wpa_aead_decrypt(sm, &sm->PTK, data, data_len,
1789 				     &key_data_length) < 0) {
1790 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1791 					LOGGER_INFO,
1792 					"received EAPOL-Key with invalid MIC");
1793 #ifdef TEST_FUZZ
1794 			wpa_printf(MSG_INFO,
1795 				   "TEST: Ignore Key MIC failure for fuzz testing");
1796 			goto continue_fuzz;
1797 #endif /* TEST_FUZZ */
1798 			goto out;
1799 		}
1800 #endif /* CONFIG_FILS */
1801 #ifdef TEST_FUZZ
1802 	continue_fuzz:
1803 #endif /* TEST_FUZZ */
1804 		sm->MICVerified = true;
1805 		eloop_cancel_timeout(wpa_send_eapol_timeout, wpa_auth, sm);
1806 		sm->pending_1_of_4_timeout = 0;
1807 	}
1808 
1809 	if (key_info & WPA_KEY_INFO_REQUEST) {
1810 		if (!(key_info & WPA_KEY_INFO_SECURE)) {
1811 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1812 					LOGGER_INFO,
1813 					"received EAPOL-Key request without Secure=1");
1814 			goto out;
1815 		}
1816 		if (sm->MICVerified) {
1817 			sm->req_replay_counter_used = 1;
1818 			os_memcpy(sm->req_replay_counter, key->replay_counter,
1819 				  WPA_REPLAY_COUNTER_LEN);
1820 		} else {
1821 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1822 					LOGGER_INFO,
1823 					"received EAPOL-Key request with invalid MIC");
1824 			goto out;
1825 		}
1826 
1827 		if (key_info & WPA_KEY_INFO_ERROR) {
1828 			if (wpa_receive_error_report(
1829 				    wpa_auth, sm,
1830 				    !(key_info & WPA_KEY_INFO_KEY_TYPE)) > 0)
1831 				goto out; /* STA entry was removed */
1832 		} else if (key_info & WPA_KEY_INFO_KEY_TYPE) {
1833 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1834 					LOGGER_INFO,
1835 					"received EAPOL-Key Request for new 4-Way Handshake");
1836 			wpa_request_new_ptk(sm);
1837 		} else {
1838 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
1839 					LOGGER_INFO,
1840 					"received EAPOL-Key Request for GTK rekeying");
1841 
1842 			eloop_cancel_timeout(wpa_rekey_gtk,
1843 					     wpa_get_primary_auth(wpa_auth),
1844 					     NULL);
1845 			if (wpa_auth_gtk_rekey_in_process(wpa_auth))
1846 				wpa_auth_logger(wpa_auth, NULL, LOGGER_DEBUG,
1847 						"skip new GTK rekey - already in process");
1848 			else
1849 				wpa_rekey_gtk(wpa_get_primary_auth(wpa_auth),
1850 					      NULL);
1851 		}
1852 	} else {
1853 		/* Do not allow the same key replay counter to be reused. */
1854 		wpa_replay_counter_mark_invalid(sm->key_replay,
1855 						key->replay_counter);
1856 
1857 		if (msg == PAIRWISE_2) {
1858 			/*
1859 			 * Maintain a copy of the pending EAPOL-Key frames in
1860 			 * case the EAPOL-Key frame was retransmitted. This is
1861 			 * needed to allow EAPOL-Key msg 2/4 reply to another
1862 			 * pending msg 1/4 to update the SNonce to work around
1863 			 * unexpected supplicant behavior.
1864 			 */
1865 			os_memcpy(sm->prev_key_replay, sm->key_replay,
1866 				  sizeof(sm->key_replay));
1867 		} else {
1868 			os_memset(sm->prev_key_replay, 0,
1869 				  sizeof(sm->prev_key_replay));
1870 		}
1871 
1872 		/*
1873 		 * Make sure old valid counters are not accepted anymore and
1874 		 * do not get copied again.
1875 		 */
1876 		wpa_replay_counter_mark_invalid(sm->key_replay, NULL);
1877 	}
1878 
1879 	os_free(sm->last_rx_eapol_key);
1880 	sm->last_rx_eapol_key = os_memdup(data, data_len);
1881 	if (!sm->last_rx_eapol_key)
1882 		goto out;
1883 	sm->last_rx_eapol_key_len = data_len;
1884 
1885 	sm->rx_eapol_key_secure = !!(key_info & WPA_KEY_INFO_SECURE);
1886 	sm->EAPOLKeyReceived = true;
1887 	sm->EAPOLKeyPairwise = !!(key_info & WPA_KEY_INFO_KEY_TYPE);
1888 	sm->EAPOLKeyRequest = !!(key_info & WPA_KEY_INFO_REQUEST);
1889 	os_memcpy(sm->SNonce, key->key_nonce, WPA_NONCE_LEN);
1890 	wpa_sm_step(sm);
1891 
1892 out:
1893 	bin_clear_free(key_data_buf, key_data_buf_len);
1894 }
1895 
1896 
1897 static int wpa_gmk_to_gtk(const u8 *gmk, const char *label, const u8 *addr,
1898 			  const u8 *gnonce, u8 *gtk, size_t gtk_len)
1899 {
1900 	u8 data[ETH_ALEN + WPA_NONCE_LEN + 8 + WPA_GTK_MAX_LEN];
1901 	u8 *pos;
1902 	int ret = 0;
1903 
1904 	/* GTK = PRF-X(GMK, "Group key expansion",
1905 	 *	AA || GNonce || Time || random data)
1906 	 * The example described in the IEEE 802.11 standard uses only AA and
1907 	 * GNonce as inputs here. Add some more entropy since this derivation
1908 	 * is done only at the Authenticator and as such, does not need to be
1909 	 * exactly same.
1910 	 */
1911 	os_memset(data, 0, sizeof(data));
1912 	os_memcpy(data, addr, ETH_ALEN);
1913 	os_memcpy(data + ETH_ALEN, gnonce, WPA_NONCE_LEN);
1914 	pos = data + ETH_ALEN + WPA_NONCE_LEN;
1915 	wpa_get_ntp_timestamp(pos);
1916 #ifdef TEST_FUZZ
1917 	os_memset(pos, 0xef, 8);
1918 #endif /* TEST_FUZZ */
1919 	pos += 8;
1920 	if (random_get_bytes(pos, gtk_len) < 0)
1921 		ret = -1;
1922 
1923 #ifdef CONFIG_SHA384
1924 	if (sha384_prf(gmk, WPA_GMK_LEN, label, data, sizeof(data),
1925 		       gtk, gtk_len) < 0)
1926 		ret = -1;
1927 #else /* CONFIG_SHA384 */
1928 #ifdef CONFIG_SHA256
1929 	if (sha256_prf(gmk, WPA_GMK_LEN, label, data, sizeof(data),
1930 		       gtk, gtk_len) < 0)
1931 		ret = -1;
1932 #else /* CONFIG_SHA256 */
1933 	if (sha1_prf(gmk, WPA_GMK_LEN, label, data, sizeof(data),
1934 		     gtk, gtk_len) < 0)
1935 		ret = -1;
1936 #endif /* CONFIG_SHA256 */
1937 #endif /* CONFIG_SHA384 */
1938 
1939 	forced_memzero(data, sizeof(data));
1940 
1941 	return ret;
1942 }
1943 
1944 
1945 static void wpa_send_eapol_timeout(void *eloop_ctx, void *timeout_ctx)
1946 {
1947 	struct wpa_authenticator *wpa_auth = eloop_ctx;
1948 	struct wpa_state_machine *sm = timeout_ctx;
1949 
1950 	if (sm->waiting_radius_psk) {
1951 		wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG,
1952 				"Ignore EAPOL-Key timeout while waiting for RADIUS PSK");
1953 		return;
1954 	}
1955 
1956 	sm->pending_1_of_4_timeout = 0;
1957 	wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
1958 			"EAPOL-Key timeout");
1959 	sm->TimeoutEvt = true;
1960 	wpa_sm_step(sm);
1961 }
1962 
1963 
1964 void __wpa_send_eapol(struct wpa_authenticator *wpa_auth,
1965 		      struct wpa_state_machine *sm, int key_info,
1966 		      const u8 *key_rsc, const u8 *nonce,
1967 		      const u8 *kde, size_t kde_len,
1968 		      int keyidx, int encr, int force_version)
1969 {
1970 	struct wpa_auth_config *conf = &wpa_auth->conf;
1971 	struct ieee802_1x_hdr *hdr;
1972 	struct wpa_eapol_key *key;
1973 	size_t len, mic_len, keyhdrlen;
1974 	int alg;
1975 	int key_data_len, pad_len = 0;
1976 	u8 *buf, *pos;
1977 	int version, pairwise;
1978 	int i;
1979 	u8 *key_mic, *key_data;
1980 
1981 	mic_len = wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len);
1982 	keyhdrlen = sizeof(*key) + mic_len + 2;
1983 
1984 	len = sizeof(struct ieee802_1x_hdr) + keyhdrlen;
1985 
1986 	if (force_version)
1987 		version = force_version;
1988 	else if (wpa_use_akm_defined(sm->wpa_key_mgmt))
1989 		version = WPA_KEY_INFO_TYPE_AKM_DEFINED;
1990 	else if (wpa_use_cmac(sm->wpa_key_mgmt))
1991 		version = WPA_KEY_INFO_TYPE_AES_128_CMAC;
1992 	else if (sm->pairwise != WPA_CIPHER_TKIP)
1993 		version = WPA_KEY_INFO_TYPE_HMAC_SHA1_AES;
1994 	else
1995 		version = WPA_KEY_INFO_TYPE_HMAC_MD5_RC4;
1996 
1997 	pairwise = !!(key_info & WPA_KEY_INFO_KEY_TYPE);
1998 
1999 	wpa_printf(MSG_DEBUG,
2000 		   "WPA: Send EAPOL(version=%d secure=%d mic=%d ack=%d install=%d pairwise=%d kde_len=%zu keyidx=%d encr=%d)",
2001 		   version,
2002 		   (key_info & WPA_KEY_INFO_SECURE) ? 1 : 0,
2003 		   (key_info & WPA_KEY_INFO_MIC) ? 1 : 0,
2004 		   (key_info & WPA_KEY_INFO_ACK) ? 1 : 0,
2005 		   (key_info & WPA_KEY_INFO_INSTALL) ? 1 : 0,
2006 		   pairwise, kde_len, keyidx, encr);
2007 
2008 	key_data_len = kde_len;
2009 
2010 	if ((version == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES ||
2011 	     wpa_use_aes_key_wrap(sm->wpa_key_mgmt) ||
2012 	     version == WPA_KEY_INFO_TYPE_AES_128_CMAC) && encr) {
2013 		pad_len = key_data_len % 8;
2014 		if (pad_len)
2015 			pad_len = 8 - pad_len;
2016 		key_data_len += pad_len + 8;
2017 	}
2018 
2019 	len += key_data_len;
2020 	if (!mic_len && encr)
2021 		len += AES_BLOCK_SIZE;
2022 
2023 	hdr = os_zalloc(len);
2024 	if (!hdr)
2025 		return;
2026 	hdr->version = conf->eapol_version;
2027 	hdr->type = IEEE802_1X_TYPE_EAPOL_KEY;
2028 	hdr->length = host_to_be16(len  - sizeof(*hdr));
2029 	key = (struct wpa_eapol_key *) (hdr + 1);
2030 	key_mic = (u8 *) (key + 1);
2031 	key_data = ((u8 *) (hdr + 1)) + keyhdrlen;
2032 
2033 	key->type = sm->wpa == WPA_VERSION_WPA2 ?
2034 		EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
2035 	key_info |= version;
2036 	if (encr && sm->wpa == WPA_VERSION_WPA2)
2037 		key_info |= WPA_KEY_INFO_ENCR_KEY_DATA;
2038 	if (sm->wpa != WPA_VERSION_WPA2)
2039 		key_info |= keyidx << WPA_KEY_INFO_KEY_INDEX_SHIFT;
2040 	WPA_PUT_BE16(key->key_info, key_info);
2041 
2042 	alg = pairwise ? sm->pairwise : conf->wpa_group;
2043 	if (sm->wpa == WPA_VERSION_WPA2 && !pairwise)
2044 		WPA_PUT_BE16(key->key_length, 0);
2045 	else
2046 		WPA_PUT_BE16(key->key_length, wpa_cipher_key_len(alg));
2047 
2048 	for (i = RSNA_MAX_EAPOL_RETRIES - 1; i > 0; i--) {
2049 		sm->key_replay[i].valid = sm->key_replay[i - 1].valid;
2050 		os_memcpy(sm->key_replay[i].counter,
2051 			  sm->key_replay[i - 1].counter,
2052 			  WPA_REPLAY_COUNTER_LEN);
2053 	}
2054 	inc_byte_array(sm->key_replay[0].counter, WPA_REPLAY_COUNTER_LEN);
2055 	os_memcpy(key->replay_counter, sm->key_replay[0].counter,
2056 		  WPA_REPLAY_COUNTER_LEN);
2057 	wpa_hexdump(MSG_DEBUG, "WPA: Replay Counter",
2058 		    key->replay_counter, WPA_REPLAY_COUNTER_LEN);
2059 	sm->key_replay[0].valid = true;
2060 
2061 	if (nonce)
2062 		os_memcpy(key->key_nonce, nonce, WPA_NONCE_LEN);
2063 
2064 	if (key_rsc)
2065 		os_memcpy(key->key_rsc, key_rsc, WPA_KEY_RSC_LEN);
2066 
2067 	if (kde && !encr) {
2068 		os_memcpy(key_data, kde, kde_len);
2069 		WPA_PUT_BE16(key_mic + mic_len, kde_len);
2070 #ifdef CONFIG_FILS
2071 	} else if (!mic_len && kde) {
2072 		const u8 *aad[1];
2073 		size_t aad_len[1];
2074 
2075 		WPA_PUT_BE16(key_mic, AES_BLOCK_SIZE + kde_len);
2076 		wpa_hexdump_key(MSG_DEBUG, "Plaintext EAPOL-Key Key Data",
2077 				kde, kde_len);
2078 
2079 		wpa_hexdump_key(MSG_DEBUG, "WPA: KEK",
2080 				sm->PTK.kek, sm->PTK.kek_len);
2081 		/* AES-SIV AAD from EAPOL protocol version field (inclusive) to
2082 		 * to Key Data (exclusive). */
2083 		aad[0] = (u8 *) hdr;
2084 		aad_len[0] = key_mic + 2 - (u8 *) hdr;
2085 		if (aes_siv_encrypt(sm->PTK.kek, sm->PTK.kek_len, kde, kde_len,
2086 				    1, aad, aad_len, key_mic + 2) < 0) {
2087 			wpa_printf(MSG_DEBUG, "WPA: AES-SIV encryption failed");
2088 			return;
2089 		}
2090 
2091 		wpa_hexdump(MSG_DEBUG, "WPA: Encrypted Key Data from SIV",
2092 			    key_mic + 2, AES_BLOCK_SIZE + kde_len);
2093 #endif /* CONFIG_FILS */
2094 	} else if (encr && kde) {
2095 		buf = os_zalloc(key_data_len);
2096 		if (!buf) {
2097 			os_free(hdr);
2098 			return;
2099 		}
2100 		pos = buf;
2101 		os_memcpy(pos, kde, kde_len);
2102 		pos += kde_len;
2103 
2104 		if (pad_len)
2105 			*pos++ = 0xdd;
2106 
2107 		wpa_hexdump_key(MSG_DEBUG,
2108 				"Plaintext EAPOL-Key Key Data (+ padding)",
2109 				buf, key_data_len);
2110 		if (version == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES ||
2111 		    wpa_use_aes_key_wrap(sm->wpa_key_mgmt) ||
2112 		    version == WPA_KEY_INFO_TYPE_AES_128_CMAC) {
2113 			wpa_hexdump_key(MSG_DEBUG, "RSN: AES-WRAP using KEK",
2114 					sm->PTK.kek, sm->PTK.kek_len);
2115 			if (aes_wrap(sm->PTK.kek, sm->PTK.kek_len,
2116 				     (key_data_len - 8) / 8, buf, key_data)) {
2117 				os_free(hdr);
2118 				bin_clear_free(buf, key_data_len);
2119 				return;
2120 			}
2121 			wpa_hexdump(MSG_DEBUG,
2122 				    "RSN: Encrypted Key Data from AES-WRAP",
2123 				    key_data, key_data_len);
2124 			WPA_PUT_BE16(key_mic + mic_len, key_data_len);
2125 #if !defined(CONFIG_NO_RC4) && !defined(CONFIG_FIPS)
2126 		} else if (sm->PTK.kek_len == 16) {
2127 			u8 ek[32];
2128 
2129 			wpa_printf(MSG_DEBUG,
2130 				   "WPA: Encrypt Key Data using RC4");
2131 			os_memcpy(key->key_iv,
2132 				  sm->group->Counter + WPA_NONCE_LEN - 16, 16);
2133 			inc_byte_array(sm->group->Counter, WPA_NONCE_LEN);
2134 			os_memcpy(ek, key->key_iv, 16);
2135 			os_memcpy(ek + 16, sm->PTK.kek, sm->PTK.kek_len);
2136 			os_memcpy(key_data, buf, key_data_len);
2137 			rc4_skip(ek, 32, 256, key_data, key_data_len);
2138 			WPA_PUT_BE16(key_mic + mic_len, key_data_len);
2139 #endif /* !(CONFIG_NO_RC4 || CONFIG_FIPS) */
2140 		} else {
2141 			os_free(hdr);
2142 			bin_clear_free(buf, key_data_len);
2143 			return;
2144 		}
2145 		bin_clear_free(buf, key_data_len);
2146 	}
2147 
2148 	if (key_info & WPA_KEY_INFO_MIC) {
2149 		if (!sm->PTK_valid || !mic_len) {
2150 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
2151 					LOGGER_DEBUG,
2152 					"PTK not valid when sending EAPOL-Key frame");
2153 			os_free(hdr);
2154 			return;
2155 		}
2156 
2157 		if (wpa_eapol_key_mic(sm->PTK.kck, sm->PTK.kck_len,
2158 				      sm->wpa_key_mgmt, version,
2159 				      (u8 *) hdr, len, key_mic) < 0) {
2160 			os_free(hdr);
2161 			return;
2162 		}
2163 #ifdef CONFIG_TESTING_OPTIONS
2164 		if (!pairwise &&
2165 		    conf->corrupt_gtk_rekey_mic_probability > 0.0 &&
2166 		    drand48() < conf->corrupt_gtk_rekey_mic_probability) {
2167 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
2168 					LOGGER_INFO,
2169 					"Corrupting group EAPOL-Key Key MIC");
2170 			key_mic[0]++;
2171 		}
2172 #endif /* CONFIG_TESTING_OPTIONS */
2173 	}
2174 
2175 	wpa_auth_set_eapol(wpa_auth, sm->addr, WPA_EAPOL_inc_EapolFramesTx, 1);
2176 	wpa_hexdump(MSG_DEBUG, "Send EAPOL-Key msg", hdr, len);
2177 	wpa_auth_send_eapol(wpa_auth, sm->addr, (u8 *) hdr, len,
2178 			    sm->pairwise_set);
2179 	os_free(hdr);
2180 }
2181 
2182 
2183 static int wpa_auth_get_sta_count(struct wpa_authenticator *wpa_auth)
2184 {
2185 	if (!wpa_auth->cb->get_sta_count)
2186 		return -1;
2187 
2188 	return wpa_auth->cb->get_sta_count(wpa_auth->cb_ctx);
2189 }
2190 
2191 
2192 static void wpa_send_eapol(struct wpa_authenticator *wpa_auth,
2193 			   struct wpa_state_machine *sm, int key_info,
2194 			   const u8 *key_rsc, const u8 *nonce,
2195 			   const u8 *kde, size_t kde_len,
2196 			   int keyidx, int encr)
2197 {
2198 	int timeout_ms;
2199 	int pairwise = key_info & WPA_KEY_INFO_KEY_TYPE;
2200 	u32 ctr;
2201 
2202 	if (!sm)
2203 		return;
2204 
2205 	ctr = pairwise ? sm->TimeoutCtr : sm->GTimeoutCtr;
2206 
2207 #ifdef CONFIG_TESTING_OPTIONS
2208 	/* When delay_eapol_tx is true, delay the EAPOL-Key transmission by
2209 	 * sending it only on the last attempt after all timeouts for the prior
2210 	 * skipped attemps. */
2211 	if (wpa_auth->conf.delay_eapol_tx &&
2212 	    ctr != wpa_auth->conf.wpa_pairwise_update_count) {
2213 		wpa_msg(sm->wpa_auth->conf.msg_ctx, MSG_INFO,
2214 			"DELAY-EAPOL-TX-%d", ctr);
2215 		goto skip_tx;
2216 	}
2217 #endif /* CONFIG_TESTING_OPTIONS */
2218 	__wpa_send_eapol(wpa_auth, sm, key_info, key_rsc, nonce, kde, kde_len,
2219 			 keyidx, encr, 0);
2220 #ifdef CONFIG_TESTING_OPTIONS
2221 skip_tx:
2222 #endif /* CONFIG_TESTING_OPTIONS */
2223 
2224 	if (ctr == 1 && wpa_auth->conf.tx_status) {
2225 		if (pairwise)
2226 			timeout_ms = eapol_key_timeout_first;
2227 		else if (wpa_auth_get_sta_count(wpa_auth) > 100)
2228 			timeout_ms = eapol_key_timeout_first_group * 2;
2229 		else
2230 			timeout_ms = eapol_key_timeout_first_group;
2231 	} else {
2232 		timeout_ms = eapol_key_timeout_subseq;
2233 	}
2234 	if (wpa_auth->conf.wpa_disable_eapol_key_retries &&
2235 	    (!pairwise || (key_info & WPA_KEY_INFO_MIC)))
2236 		timeout_ms = eapol_key_timeout_no_retrans;
2237 	if (pairwise && ctr == 1 && !(key_info & WPA_KEY_INFO_MIC))
2238 		sm->pending_1_of_4_timeout = 1;
2239 #ifdef TEST_FUZZ
2240 	timeout_ms = 1;
2241 #endif /* TEST_FUZZ */
2242 	wpa_printf(MSG_DEBUG,
2243 		   "WPA: Use EAPOL-Key timeout of %u ms (retry counter %u)",
2244 		   timeout_ms, ctr);
2245 	eloop_register_timeout(timeout_ms / 1000, (timeout_ms % 1000) * 1000,
2246 			       wpa_send_eapol_timeout, wpa_auth, sm);
2247 }
2248 
2249 
2250 static int wpa_verify_key_mic(int akmp, size_t pmk_len, struct wpa_ptk *PTK,
2251 			      u8 *data, size_t data_len)
2252 {
2253 	struct ieee802_1x_hdr *hdr;
2254 	struct wpa_eapol_key *key;
2255 	u16 key_info;
2256 	int ret = 0;
2257 	u8 mic[WPA_EAPOL_KEY_MIC_MAX_LEN], *mic_pos;
2258 	size_t mic_len = wpa_mic_len(akmp, pmk_len);
2259 
2260 	if (data_len < sizeof(*hdr) + sizeof(*key))
2261 		return -1;
2262 
2263 	hdr = (struct ieee802_1x_hdr *) data;
2264 	key = (struct wpa_eapol_key *) (hdr + 1);
2265 	mic_pos = (u8 *) (key + 1);
2266 	key_info = WPA_GET_BE16(key->key_info);
2267 	os_memcpy(mic, mic_pos, mic_len);
2268 	os_memset(mic_pos, 0, mic_len);
2269 	if (wpa_eapol_key_mic(PTK->kck, PTK->kck_len, akmp,
2270 			      key_info & WPA_KEY_INFO_TYPE_MASK,
2271 			      data, data_len, mic_pos) ||
2272 	    os_memcmp_const(mic, mic_pos, mic_len) != 0)
2273 		ret = -1;
2274 	os_memcpy(mic_pos, mic, mic_len);
2275 	return ret;
2276 }
2277 
2278 
2279 void wpa_remove_ptk(struct wpa_state_machine *sm)
2280 {
2281 	sm->PTK_valid = false;
2282 	os_memset(&sm->PTK, 0, sizeof(sm->PTK));
2283 
2284 	wpa_auth_remove_ptksa(sm->wpa_auth, sm->addr, sm->pairwise);
2285 
2286 	if (wpa_auth_set_key(sm->wpa_auth, 0, WPA_ALG_NONE, sm->addr, 0, NULL,
2287 			     0, KEY_FLAG_PAIRWISE))
2288 		wpa_printf(MSG_DEBUG,
2289 			   "RSN: PTK removal from the driver failed");
2290 	if (sm->use_ext_key_id &&
2291 	    wpa_auth_set_key(sm->wpa_auth, 0, WPA_ALG_NONE, sm->addr, 1, NULL,
2292 			     0, KEY_FLAG_PAIRWISE))
2293 		wpa_printf(MSG_DEBUG,
2294 			   "RSN: PTK Key ID 1 removal from the driver failed");
2295 	sm->pairwise_set = false;
2296 	eloop_cancel_timeout(wpa_rekey_ptk, sm->wpa_auth, sm);
2297 }
2298 
2299 
2300 int wpa_auth_sm_event(struct wpa_state_machine *sm, enum wpa_event event)
2301 {
2302 	int remove_ptk = 1;
2303 
2304 	if (!sm)
2305 		return -1;
2306 
2307 	wpa_auth_vlogger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
2308 			 "event %d notification", event);
2309 
2310 	switch (event) {
2311 	case WPA_AUTH:
2312 #ifdef CONFIG_MESH
2313 		/* PTKs are derived through AMPE */
2314 		if (wpa_auth_start_ampe(sm->wpa_auth, sm->addr)) {
2315 			/* not mesh */
2316 			break;
2317 		}
2318 		return 0;
2319 #endif /* CONFIG_MESH */
2320 	case WPA_ASSOC:
2321 		break;
2322 	case WPA_DEAUTH:
2323 	case WPA_DISASSOC:
2324 		sm->DeauthenticationRequest = true;
2325 		os_memset(sm->PMK, 0, sizeof(sm->PMK));
2326 		sm->pmk_len = 0;
2327 #ifdef CONFIG_IEEE80211R_AP
2328 		os_memset(sm->xxkey, 0, sizeof(sm->xxkey));
2329 		sm->xxkey_len = 0;
2330 		os_memset(sm->pmk_r1, 0, sizeof(sm->pmk_r1));
2331 		sm->pmk_r1_len = 0;
2332 #endif /* CONFIG_IEEE80211R_AP */
2333 		break;
2334 	case WPA_REAUTH:
2335 	case WPA_REAUTH_EAPOL:
2336 		if (!sm->started) {
2337 			/*
2338 			 * When using WPS, we may end up here if the STA
2339 			 * manages to re-associate without the previous STA
2340 			 * entry getting removed. Consequently, we need to make
2341 			 * sure that the WPA state machines gets initialized
2342 			 * properly at this point.
2343 			 */
2344 			wpa_printf(MSG_DEBUG,
2345 				   "WPA state machine had not been started - initialize now");
2346 			sm->started = 1;
2347 			sm->Init = true;
2348 			if (wpa_sm_step(sm) == 1)
2349 				return 1; /* should not really happen */
2350 			sm->Init = false;
2351 			sm->AuthenticationRequest = true;
2352 			break;
2353 		}
2354 
2355 		if (sm->ptkstart_without_success > 3) {
2356 			wpa_printf(MSG_INFO,
2357 				   "WPA: Multiple EAP reauth attempts without 4-way handshake completion, disconnect "
2358 				   MACSTR, MAC2STR(sm->addr));
2359 			sm->Disconnect = true;
2360 			break;
2361 		}
2362 
2363 		if (!sm->use_ext_key_id &&
2364 		    sm->wpa_auth->conf.wpa_deny_ptk0_rekey) {
2365 			wpa_printf(MSG_INFO,
2366 				   "WPA: PTK0 rekey not allowed, disconnect "
2367 				   MACSTR, MAC2STR(wpa_auth_get_spa(sm)));
2368 			sm->Disconnect = true;
2369 			/* Try to encourage the STA to reconnect */
2370 			sm->disconnect_reason =
2371 				WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA;
2372 			break;
2373 		}
2374 
2375 		if (sm->use_ext_key_id)
2376 			sm->keyidx_active ^= 1; /* flip Key ID */
2377 
2378 		if (sm->GUpdateStationKeys) {
2379 			/*
2380 			 * Reauthentication cancels the pending group key
2381 			 * update for this STA.
2382 			 */
2383 			wpa_gkeydone_sta(sm);
2384 			sm->PtkGroupInit = true;
2385 		}
2386 		sm->ReAuthenticationRequest = true;
2387 		break;
2388 	case WPA_ASSOC_FT:
2389 #ifdef CONFIG_IEEE80211R_AP
2390 		wpa_printf(MSG_DEBUG,
2391 			   "FT: Retry PTK configuration after association");
2392 		wpa_ft_install_ptk(sm, 1);
2393 
2394 		/* Using FT protocol, not WPA auth state machine */
2395 		sm->ft_completed = 1;
2396 		wpa_auth_set_ptk_rekey_timer(sm);
2397 		return 0;
2398 #else /* CONFIG_IEEE80211R_AP */
2399 		break;
2400 #endif /* CONFIG_IEEE80211R_AP */
2401 	case WPA_ASSOC_FILS:
2402 #ifdef CONFIG_FILS
2403 		wpa_printf(MSG_DEBUG,
2404 			   "FILS: TK configuration after association");
2405 		fils_set_tk(sm);
2406 		sm->fils_completed = 1;
2407 		return 0;
2408 #else /* CONFIG_FILS */
2409 		break;
2410 #endif /* CONFIG_FILS */
2411 	case WPA_DRV_STA_REMOVED:
2412 		sm->tk_already_set = false;
2413 		return 0;
2414 	}
2415 
2416 #ifdef CONFIG_IEEE80211R_AP
2417 	sm->ft_completed = 0;
2418 #endif /* CONFIG_IEEE80211R_AP */
2419 
2420 	if (sm->mgmt_frame_prot && event == WPA_AUTH)
2421 		remove_ptk = 0;
2422 #ifdef CONFIG_FILS
2423 	if (wpa_key_mgmt_fils(sm->wpa_key_mgmt) &&
2424 	    (event == WPA_AUTH || event == WPA_ASSOC))
2425 		remove_ptk = 0;
2426 #endif /* CONFIG_FILS */
2427 
2428 	if (remove_ptk) {
2429 		sm->PTK_valid = false;
2430 		os_memset(&sm->PTK, 0, sizeof(sm->PTK));
2431 
2432 		if (event != WPA_REAUTH_EAPOL)
2433 			wpa_remove_ptk(sm);
2434 	}
2435 
2436 	if (sm->in_step_loop) {
2437 		/*
2438 		 * wpa_sm_step() is already running - avoid recursive call to
2439 		 * it by making the existing loop process the new update.
2440 		 */
2441 		sm->changed = true;
2442 		return 0;
2443 	}
2444 	return wpa_sm_step(sm);
2445 }
2446 
2447 
2448 SM_STATE(WPA_PTK, INITIALIZE)
2449 {
2450 	SM_ENTRY_MA(WPA_PTK, INITIALIZE, wpa_ptk);
2451 	if (sm->Init) {
2452 		/* Init flag is not cleared here, so avoid busy
2453 		 * loop by claiming nothing changed. */
2454 		sm->changed = false;
2455 	}
2456 
2457 	sm->keycount = 0;
2458 	if (sm->GUpdateStationKeys)
2459 		wpa_gkeydone_sta(sm);
2460 	if (sm->wpa == WPA_VERSION_WPA)
2461 		sm->PInitAKeys = false;
2462 	if (1 /* Unicast cipher supported AND (ESS OR ((IBSS or WDS) and
2463 	       * Local AA > Remote AA)) */) {
2464 		sm->Pair = true;
2465 	}
2466 	wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portEnabled, 0);
2467 	wpa_remove_ptk(sm);
2468 	wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portValid, 0);
2469 	sm->TimeoutCtr = 0;
2470 	if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) ||
2471 	    sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP ||
2472 	    sm->wpa_key_mgmt == WPA_KEY_MGMT_OWE) {
2473 		wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
2474 				   WPA_EAPOL_authorized, 0);
2475 	}
2476 }
2477 
2478 
2479 SM_STATE(WPA_PTK, DISCONNECT)
2480 {
2481 	u16 reason = sm->disconnect_reason;
2482 
2483 	SM_ENTRY_MA(WPA_PTK, DISCONNECT, wpa_ptk);
2484 	sm->Disconnect = false;
2485 	sm->disconnect_reason = 0;
2486 	if (!reason)
2487 		reason = WLAN_REASON_PREV_AUTH_NOT_VALID;
2488 	wpa_sta_disconnect(sm->wpa_auth, sm->addr, reason);
2489 }
2490 
2491 
2492 SM_STATE(WPA_PTK, DISCONNECTED)
2493 {
2494 	SM_ENTRY_MA(WPA_PTK, DISCONNECTED, wpa_ptk);
2495 	sm->DeauthenticationRequest = false;
2496 }
2497 
2498 
2499 SM_STATE(WPA_PTK, AUTHENTICATION)
2500 {
2501 	SM_ENTRY_MA(WPA_PTK, AUTHENTICATION, wpa_ptk);
2502 	os_memset(&sm->PTK, 0, sizeof(sm->PTK));
2503 	sm->PTK_valid = false;
2504 	wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portControl_Auto,
2505 			   1);
2506 	wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portEnabled, 1);
2507 	sm->AuthenticationRequest = false;
2508 }
2509 
2510 
2511 static void wpa_group_ensure_init(struct wpa_authenticator *wpa_auth,
2512 				  struct wpa_group *group)
2513 {
2514 	if (group->first_sta_seen)
2515 		return;
2516 	/*
2517 	 * System has run bit further than at the time hostapd was started
2518 	 * potentially very early during boot up. This provides better chances
2519 	 * of collecting more randomness on embedded systems. Re-initialize the
2520 	 * GMK and Counter here to improve their strength if there was not
2521 	 * enough entropy available immediately after system startup.
2522 	 */
2523 	wpa_printf(MSG_DEBUG,
2524 		   "WPA: Re-initialize GMK/Counter on first station");
2525 	if (random_pool_ready() != 1) {
2526 		wpa_printf(MSG_INFO,
2527 			   "WPA: Not enough entropy in random pool to proceed - reject first 4-way handshake");
2528 		group->reject_4way_hs_for_entropy = true;
2529 	} else {
2530 		group->first_sta_seen = true;
2531 		group->reject_4way_hs_for_entropy = false;
2532 	}
2533 
2534 	if (wpa_group_init_gmk_and_counter(wpa_auth, group) < 0 ||
2535 	    wpa_gtk_update(wpa_auth, group) < 0 ||
2536 	    wpa_group_config_group_keys(wpa_auth, group) < 0) {
2537 		wpa_printf(MSG_INFO, "WPA: GMK/GTK setup failed");
2538 		group->first_sta_seen = false;
2539 		group->reject_4way_hs_for_entropy = true;
2540 	}
2541 }
2542 
2543 
2544 SM_STATE(WPA_PTK, AUTHENTICATION2)
2545 {
2546 	SM_ENTRY_MA(WPA_PTK, AUTHENTICATION2, wpa_ptk);
2547 
2548 	wpa_group_ensure_init(sm->wpa_auth, sm->group);
2549 	sm->ReAuthenticationRequest = false;
2550 
2551 	/*
2552 	 * Definition of ANonce selection in IEEE Std 802.11i-2004 is somewhat
2553 	 * ambiguous. The Authenticator state machine uses a counter that is
2554 	 * incremented by one for each 4-way handshake. However, the security
2555 	 * analysis of 4-way handshake points out that unpredictable nonces
2556 	 * help in preventing precomputation attacks. Instead of the state
2557 	 * machine definition, use an unpredictable nonce value here to provide
2558 	 * stronger protection against potential precomputation attacks.
2559 	 */
2560 	if (random_get_bytes(sm->ANonce, WPA_NONCE_LEN)) {
2561 		wpa_printf(MSG_ERROR,
2562 			   "WPA: Failed to get random data for ANonce.");
2563 		sm->Disconnect = true;
2564 		return;
2565 	}
2566 	wpa_hexdump(MSG_DEBUG, "WPA: Assign ANonce", sm->ANonce,
2567 		    WPA_NONCE_LEN);
2568 	/* IEEE 802.11i does not clear TimeoutCtr here, but this is more
2569 	 * logical place than INITIALIZE since AUTHENTICATION2 can be
2570 	 * re-entered on ReAuthenticationRequest without going through
2571 	 * INITIALIZE. */
2572 	sm->TimeoutCtr = 0;
2573 }
2574 
2575 
2576 static int wpa_auth_sm_ptk_update(struct wpa_state_machine *sm)
2577 {
2578 	if (random_get_bytes(sm->ANonce, WPA_NONCE_LEN)) {
2579 		wpa_printf(MSG_ERROR,
2580 			   "WPA: Failed to get random data for ANonce");
2581 		sm->Disconnect = true;
2582 		return -1;
2583 	}
2584 	wpa_hexdump(MSG_DEBUG, "WPA: Assign new ANonce", sm->ANonce,
2585 		    WPA_NONCE_LEN);
2586 	sm->TimeoutCtr = 0;
2587 	return 0;
2588 }
2589 
2590 
2591 SM_STATE(WPA_PTK, INITPMK)
2592 {
2593 	u8 msk[2 * PMK_LEN];
2594 	size_t len = 2 * PMK_LEN;
2595 
2596 	SM_ENTRY_MA(WPA_PTK, INITPMK, wpa_ptk);
2597 #ifdef CONFIG_IEEE80211R_AP
2598 	sm->xxkey_len = 0;
2599 #endif /* CONFIG_IEEE80211R_AP */
2600 	if (sm->pmksa) {
2601 		wpa_printf(MSG_DEBUG, "WPA: PMK from PMKSA cache");
2602 		os_memcpy(sm->PMK, sm->pmksa->pmk, sm->pmksa->pmk_len);
2603 		sm->pmk_len = sm->pmksa->pmk_len;
2604 #ifdef CONFIG_DPP
2605 	} else if (sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP) {
2606 		wpa_printf(MSG_DEBUG,
2607 			   "DPP: No PMKSA cache entry for STA - reject connection");
2608 		sm->Disconnect = true;
2609 		sm->disconnect_reason = WLAN_REASON_INVALID_PMKID;
2610 		return;
2611 #endif /* CONFIG_DPP */
2612 	} else if (wpa_auth_get_msk(sm->wpa_auth, wpa_auth_get_spa(sm),
2613 				    msk, &len) == 0) {
2614 		unsigned int pmk_len;
2615 
2616 		if (wpa_key_mgmt_sha384(sm->wpa_key_mgmt))
2617 			pmk_len = PMK_LEN_SUITE_B_192;
2618 		else
2619 			pmk_len = PMK_LEN;
2620 		wpa_printf(MSG_DEBUG,
2621 			   "WPA: PMK from EAPOL state machine (MSK len=%zu PMK len=%u)",
2622 			   len, pmk_len);
2623 		if (len < pmk_len) {
2624 			wpa_printf(MSG_DEBUG,
2625 				   "WPA: MSK not long enough (%zu) to create PMK (%u)",
2626 				   len, pmk_len);
2627 			sm->Disconnect = true;
2628 			return;
2629 		}
2630 		os_memcpy(sm->PMK, msk, pmk_len);
2631 		sm->pmk_len = pmk_len;
2632 #ifdef CONFIG_IEEE80211R_AP
2633 		if (len >= 2 * PMK_LEN) {
2634 			if (wpa_key_mgmt_sha384(sm->wpa_key_mgmt)) {
2635 				os_memcpy(sm->xxkey, msk, SHA384_MAC_LEN);
2636 				sm->xxkey_len = SHA384_MAC_LEN;
2637 			} else {
2638 				os_memcpy(sm->xxkey, msk + PMK_LEN, PMK_LEN);
2639 				sm->xxkey_len = PMK_LEN;
2640 			}
2641 		}
2642 #endif /* CONFIG_IEEE80211R_AP */
2643 	} else {
2644 		wpa_printf(MSG_DEBUG, "WPA: Could not get PMK, get_msk: %p",
2645 			   sm->wpa_auth->cb->get_msk);
2646 		sm->Disconnect = true;
2647 		return;
2648 	}
2649 	forced_memzero(msk, sizeof(msk));
2650 
2651 	sm->req_replay_counter_used = 0;
2652 	/* IEEE 802.11i does not set keyRun to false, but not doing this
2653 	 * will break reauthentication since EAPOL state machines may not be
2654 	 * get into AUTHENTICATING state that clears keyRun before WPA state
2655 	 * machine enters AUTHENTICATION2 state and goes immediately to INITPMK
2656 	 * state and takes PMK from the previously used AAA Key. This will
2657 	 * eventually fail in 4-Way Handshake because Supplicant uses PMK
2658 	 * derived from the new AAA Key. Setting keyRun = false here seems to
2659 	 * be good workaround for this issue. */
2660 	wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyRun, false);
2661 }
2662 
2663 
2664 SM_STATE(WPA_PTK, INITPSK)
2665 {
2666 	const u8 *psk;
2667 	size_t psk_len;
2668 
2669 	SM_ENTRY_MA(WPA_PTK, INITPSK, wpa_ptk);
2670 	psk = wpa_auth_get_psk(sm->wpa_auth, sm->addr, sm->p2p_dev_addr, NULL,
2671 			       &psk_len, NULL);
2672 	if (psk) {
2673 		os_memcpy(sm->PMK, psk, psk_len);
2674 		sm->pmk_len = psk_len;
2675 #ifdef CONFIG_IEEE80211R_AP
2676 		sm->xxkey_len = PMK_LEN;
2677 #ifdef CONFIG_SAE
2678 		if (sm->wpa_key_mgmt == WPA_KEY_MGMT_FT_SAE_EXT_KEY &&
2679 		    (psk_len == SHA512_MAC_LEN || psk_len == SHA384_MAC_LEN ||
2680 		     psk_len == SHA256_MAC_LEN))
2681 			sm->xxkey_len = psk_len;
2682 #endif /* CONFIG_SAE */
2683 		os_memcpy(sm->xxkey, psk, sm->xxkey_len);
2684 #endif /* CONFIG_IEEE80211R_AP */
2685 	}
2686 #ifdef CONFIG_SAE
2687 	if (wpa_auth_uses_sae(sm) && sm->pmksa) {
2688 		wpa_printf(MSG_DEBUG, "SAE: PMK from PMKSA cache (len=%zu)",
2689 			   sm->pmksa->pmk_len);
2690 		os_memcpy(sm->PMK, sm->pmksa->pmk, sm->pmksa->pmk_len);
2691 		sm->pmk_len = sm->pmksa->pmk_len;
2692 #ifdef CONFIG_IEEE80211R_AP
2693 		os_memcpy(sm->xxkey, sm->pmksa->pmk, sm->pmksa->pmk_len);
2694 		sm->xxkey_len = sm->pmksa->pmk_len;
2695 #endif /* CONFIG_IEEE80211R_AP */
2696 	}
2697 #endif /* CONFIG_SAE */
2698 	sm->req_replay_counter_used = 0;
2699 }
2700 
2701 
2702 SM_STATE(WPA_PTK, PTKSTART)
2703 {
2704 	u8 *buf;
2705 	size_t buf_len = 2 + RSN_SELECTOR_LEN + PMKID_LEN;
2706 	u8 *pmkid = NULL;
2707 	size_t kde_len = 0;
2708 	u16 key_info;
2709 #ifdef CONFIG_TESTING_OPTIONS
2710 	struct wpa_auth_config *conf = &sm->wpa_auth->conf;
2711 #endif /* CONFIG_TESTING_OPTIONS */
2712 
2713 	SM_ENTRY_MA(WPA_PTK, PTKSTART, wpa_ptk);
2714 	sm->PTKRequest = false;
2715 	sm->TimeoutEvt = false;
2716 	sm->alt_snonce_valid = false;
2717 	sm->ptkstart_without_success++;
2718 
2719 	sm->TimeoutCtr++;
2720 	if (sm->TimeoutCtr > sm->wpa_auth->conf.wpa_pairwise_update_count) {
2721 		/* No point in sending the EAPOL-Key - we will disconnect
2722 		 * immediately following this. */
2723 		return;
2724 	}
2725 
2726 #ifdef CONFIG_IEEE80211BE
2727 	if (sm->mld_assoc_link_id >= 0)
2728 		buf_len += 2 + RSN_SELECTOR_LEN + ETH_ALEN;
2729 #endif /* CONFIG_IEEE80211BE */
2730 #ifdef CONFIG_TESTING_OPTIONS
2731 	if (conf->eapol_m1_elements)
2732 		buf_len += wpabuf_len(conf->eapol_m1_elements);
2733 #endif /* CONFIG_TESTING_OPTIONS */
2734 
2735 	buf = os_zalloc(buf_len);
2736 	if (!buf)
2737 		return;
2738 
2739 	wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
2740 			"sending 1/4 msg of 4-Way Handshake");
2741 	/*
2742 	 * For infrastructure BSS cases, it is better for the AP not to include
2743 	 * the PMKID KDE in EAPOL-Key msg 1/4 since it could be used to initiate
2744 	 * offline search for the passphrase/PSK without having to be able to
2745 	 * capture a 4-way handshake from a STA that has access to the network.
2746 	 *
2747 	 * For IBSS cases, addition of PMKID KDE could be considered even with
2748 	 * WPA2-PSK cases that use multiple PSKs, but only if there is a single
2749 	 * possible PSK for this STA. However, this should not be done unless
2750 	 * there is support for using that information on the supplicant side.
2751 	 * The concern about exposing PMKID unnecessarily in infrastructure BSS
2752 	 * cases would also apply here, but at least in the IBSS case, this
2753 	 * would cover a potential real use case.
2754 	 */
2755 	if (sm->wpa == WPA_VERSION_WPA2 &&
2756 	    (wpa_key_mgmt_wpa_ieee8021x(sm->wpa_key_mgmt) ||
2757 	     (sm->wpa_key_mgmt == WPA_KEY_MGMT_OWE && sm->pmksa) ||
2758 	     wpa_key_mgmt_sae(sm->wpa_key_mgmt)) &&
2759 	    sm->wpa_key_mgmt != WPA_KEY_MGMT_OSEN) {
2760 		pmkid = buf;
2761 		kde_len = 2 + RSN_SELECTOR_LEN + PMKID_LEN;
2762 		pmkid[0] = WLAN_EID_VENDOR_SPECIFIC;
2763 		pmkid[1] = RSN_SELECTOR_LEN + PMKID_LEN;
2764 		RSN_SELECTOR_PUT(&pmkid[2], RSN_KEY_DATA_PMKID);
2765 		if (sm->pmksa) {
2766 			wpa_hexdump(MSG_DEBUG,
2767 				    "RSN: Message 1/4 PMKID from PMKSA entry",
2768 				    sm->pmksa->pmkid, PMKID_LEN);
2769 			os_memcpy(&pmkid[2 + RSN_SELECTOR_LEN],
2770 				  sm->pmksa->pmkid, PMKID_LEN);
2771 		} else if (wpa_key_mgmt_suite_b(sm->wpa_key_mgmt)) {
2772 			/* No KCK available to derive PMKID */
2773 			wpa_printf(MSG_DEBUG,
2774 				   "RSN: No KCK available to derive PMKID for message 1/4");
2775 			pmkid = NULL;
2776 #ifdef CONFIG_FILS
2777 		} else if (wpa_key_mgmt_fils(sm->wpa_key_mgmt)) {
2778 			if (sm->pmkid_set) {
2779 				wpa_hexdump(MSG_DEBUG,
2780 					    "RSN: Message 1/4 PMKID from FILS/ERP",
2781 					    sm->pmkid, PMKID_LEN);
2782 				os_memcpy(&pmkid[2 + RSN_SELECTOR_LEN],
2783 					  sm->pmkid, PMKID_LEN);
2784 			} else {
2785 				/* No PMKID available */
2786 				wpa_printf(MSG_DEBUG,
2787 					   "RSN: No FILS/ERP PMKID available for message 1/4");
2788 				pmkid = NULL;
2789 			}
2790 #endif /* CONFIG_FILS */
2791 #ifdef CONFIG_IEEE80211R_AP
2792 		} else if (wpa_key_mgmt_ft(sm->wpa_key_mgmt) &&
2793 			   sm->ft_completed) {
2794 			wpa_printf(MSG_DEBUG,
2795 				   "FT: No PMKID in message 1/4 when using FT protocol");
2796 			pmkid = NULL;
2797 #endif /* CONFIG_IEEE80211R_AP */
2798 #ifdef CONFIG_SAE
2799 		} else if (wpa_key_mgmt_sae(sm->wpa_key_mgmt)) {
2800 			if (sm->pmkid_set) {
2801 				wpa_hexdump(MSG_DEBUG,
2802 					    "RSN: Message 1/4 PMKID from SAE",
2803 					    sm->pmkid, PMKID_LEN);
2804 				os_memcpy(&pmkid[2 + RSN_SELECTOR_LEN],
2805 					  sm->pmkid, PMKID_LEN);
2806 			} else {
2807 				/* No PMKID available */
2808 				wpa_printf(MSG_DEBUG,
2809 					   "RSN: No SAE PMKID available for message 1/4");
2810 				pmkid = NULL;
2811 			}
2812 #endif /* CONFIG_SAE */
2813 		} else {
2814 			/*
2815 			 * Calculate PMKID since no PMKSA cache entry was
2816 			 * available with pre-calculated PMKID.
2817 			 */
2818 			rsn_pmkid(sm->PMK, sm->pmk_len,
2819 				  wpa_auth_get_aa(sm),
2820 				  wpa_auth_get_spa(sm),
2821 				  &pmkid[2 + RSN_SELECTOR_LEN],
2822 				  sm->wpa_key_mgmt);
2823 			wpa_hexdump(MSG_DEBUG,
2824 				    "RSN: Message 1/4 PMKID derived from PMK",
2825 				    &pmkid[2 + RSN_SELECTOR_LEN], PMKID_LEN);
2826 		}
2827 	}
2828 	if (!pmkid)
2829 		kde_len = 0;
2830 
2831 #ifdef CONFIG_IEEE80211BE
2832 	if (sm->mld_assoc_link_id >= 0) {
2833 		wpa_printf(MSG_DEBUG,
2834 			   "RSN: MLD: Add MAC Address KDE: kde_len=%zu",
2835 			   kde_len);
2836 		wpa_add_kde(buf + kde_len, RSN_KEY_DATA_MAC_ADDR,
2837 			    sm->wpa_auth->mld_addr, ETH_ALEN, NULL, 0);
2838 		kde_len += 2 + RSN_SELECTOR_LEN + ETH_ALEN;
2839 	}
2840 #endif /* CONFIG_IEEE80211BE */
2841 
2842 #ifdef CONFIG_TESTING_OPTIONS
2843 	if (conf->eapol_m1_elements) {
2844 		os_memcpy(buf + kde_len, wpabuf_head(conf->eapol_m1_elements),
2845 			  wpabuf_len(conf->eapol_m1_elements));
2846 		kde_len += wpabuf_len(conf->eapol_m1_elements);
2847 	}
2848 #endif /* CONFIG_TESTING_OPTIONS */
2849 
2850 	key_info = WPA_KEY_INFO_ACK | WPA_KEY_INFO_KEY_TYPE;
2851 	if (sm->pairwise_set && sm->wpa != WPA_VERSION_WPA)
2852 		key_info |= WPA_KEY_INFO_SECURE;
2853 	wpa_send_eapol(sm->wpa_auth, sm, key_info, NULL,
2854 		       sm->ANonce, kde_len ? buf : NULL, kde_len, 0, 0);
2855 	os_free(buf);
2856 }
2857 
2858 
2859 static int wpa_derive_ptk(struct wpa_state_machine *sm, const u8 *snonce,
2860 			  const u8 *pmk, unsigned int pmk_len,
2861 			  struct wpa_ptk *ptk, int force_sha256,
2862 			  u8 *pmk_r0, u8 *pmk_r1, u8 *pmk_r0_name,
2863 			  size_t *key_len, bool no_kdk)
2864 {
2865 	const u8 *z = NULL;
2866 	size_t z_len = 0, kdk_len;
2867 	int akmp;
2868 	int ret;
2869 
2870 	if (sm->wpa_auth->conf.force_kdk_derivation ||
2871 	    (!no_kdk && sm->wpa_auth->conf.secure_ltf &&
2872 	     ieee802_11_rsnx_capab(sm->rsnxe, WLAN_RSNX_CAPAB_SECURE_LTF)))
2873 		kdk_len = WPA_KDK_MAX_LEN;
2874 	else
2875 		kdk_len = 0;
2876 
2877 #ifdef CONFIG_IEEE80211R_AP
2878 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
2879 		if (sm->ft_completed) {
2880 			u8 ptk_name[WPA_PMK_NAME_LEN];
2881 
2882 			ret = wpa_pmk_r1_to_ptk(sm->pmk_r1, sm->pmk_r1_len,
2883 						sm->SNonce, sm->ANonce,
2884 						wpa_auth_get_spa(sm),
2885 						wpa_auth_get_aa(sm),
2886 						sm->pmk_r1_name, ptk,
2887 						ptk_name, sm->wpa_key_mgmt,
2888 						sm->pairwise, kdk_len);
2889 		} else {
2890 			ret = wpa_auth_derive_ptk_ft(sm, ptk, pmk_r0, pmk_r1,
2891 						     pmk_r0_name, key_len,
2892 						     kdk_len);
2893 		}
2894 		if (ret) {
2895 			wpa_printf(MSG_ERROR, "FT: PTK derivation failed");
2896 			return ret;
2897 		}
2898 
2899 #ifdef CONFIG_PASN
2900 		if (!no_kdk && sm->wpa_auth->conf.secure_ltf &&
2901 		    ieee802_11_rsnx_capab(sm->rsnxe,
2902 					  WLAN_RSNX_CAPAB_SECURE_LTF)) {
2903 			ret = wpa_ltf_keyseed(ptk, sm->wpa_key_mgmt,
2904 					      sm->pairwise);
2905 			if (ret) {
2906 				wpa_printf(MSG_ERROR,
2907 					   "FT: LTF keyseed derivation failed");
2908 			}
2909 		}
2910 #endif /* CONFIG_PASN */
2911 		return ret;
2912 	}
2913 #endif /* CONFIG_IEEE80211R_AP */
2914 
2915 #ifdef CONFIG_DPP2
2916 	if (sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP && sm->dpp_z) {
2917 		z = wpabuf_head(sm->dpp_z);
2918 		z_len = wpabuf_len(sm->dpp_z);
2919 	}
2920 #endif /* CONFIG_DPP2 */
2921 
2922 	akmp = sm->wpa_key_mgmt;
2923 	if (force_sha256)
2924 		akmp |= WPA_KEY_MGMT_PSK_SHA256;
2925 	ret = wpa_pmk_to_ptk(pmk, pmk_len, "Pairwise key expansion",
2926 			     wpa_auth_get_aa(sm), wpa_auth_get_spa(sm),
2927 			     sm->ANonce, snonce, ptk, akmp,
2928 			     sm->pairwise, z, z_len, kdk_len);
2929 	if (ret) {
2930 		wpa_printf(MSG_DEBUG,
2931 			   "WPA: PTK derivation failed");
2932 		return ret;
2933 	}
2934 
2935 #ifdef CONFIG_PASN
2936 	if (!no_kdk && sm->wpa_auth->conf.secure_ltf &&
2937 	    ieee802_11_rsnx_capab(sm->rsnxe, WLAN_RSNX_CAPAB_SECURE_LTF)) {
2938 		ret = wpa_ltf_keyseed(ptk, sm->wpa_key_mgmt, sm->pairwise);
2939 		if (ret) {
2940 			wpa_printf(MSG_DEBUG,
2941 				   "WPA: LTF keyseed derivation failed");
2942 		}
2943 	}
2944 #endif /* CONFIG_PASN */
2945 	return ret;
2946 }
2947 
2948 
2949 #ifdef CONFIG_FILS
2950 
2951 int fils_auth_pmk_to_ptk(struct wpa_state_machine *sm, const u8 *pmk,
2952 			 size_t pmk_len, const u8 *snonce, const u8 *anonce,
2953 			 const u8 *dhss, size_t dhss_len,
2954 			 struct wpabuf *g_sta, struct wpabuf *g_ap)
2955 {
2956 	u8 ick[FILS_ICK_MAX_LEN];
2957 	size_t ick_len;
2958 	int res;
2959 	u8 fils_ft[FILS_FT_MAX_LEN];
2960 	size_t fils_ft_len = 0, kdk_len;
2961 
2962 	if (sm->wpa_auth->conf.force_kdk_derivation ||
2963 	    (sm->wpa_auth->conf.secure_ltf &&
2964 	     ieee802_11_rsnx_capab(sm->rsnxe, WLAN_RSNX_CAPAB_SECURE_LTF)))
2965 		kdk_len = WPA_KDK_MAX_LEN;
2966 	else
2967 		kdk_len = 0;
2968 
2969 	res = fils_pmk_to_ptk(pmk, pmk_len, wpa_auth_get_spa(sm),
2970 			      wpa_auth_get_aa(sm),
2971 			      snonce, anonce, dhss, dhss_len,
2972 			      &sm->PTK, ick, &ick_len,
2973 			      sm->wpa_key_mgmt, sm->pairwise,
2974 			      fils_ft, &fils_ft_len, kdk_len);
2975 	if (res < 0)
2976 		return res;
2977 
2978 #ifdef CONFIG_PASN
2979 	if (sm->wpa_auth->conf.secure_ltf &&
2980 	    ieee802_11_rsnx_capab(sm->rsnxe, WLAN_RSNX_CAPAB_SECURE_LTF)) {
2981 		res = wpa_ltf_keyseed(&sm->PTK, sm->wpa_key_mgmt, sm->pairwise);
2982 		if (res) {
2983 			wpa_printf(MSG_ERROR,
2984 				   "FILS: LTF keyseed derivation failed");
2985 			return res;
2986 		}
2987 	}
2988 #endif /* CONFIG_PASN */
2989 
2990 	sm->PTK_valid = true;
2991 	sm->tk_already_set = false;
2992 
2993 #ifdef CONFIG_IEEE80211R_AP
2994 	if (fils_ft_len) {
2995 		struct wpa_authenticator *wpa_auth = sm->wpa_auth;
2996 		struct wpa_auth_config *conf = &wpa_auth->conf;
2997 		u8 pmk_r0[PMK_LEN_MAX], pmk_r0_name[WPA_PMK_NAME_LEN];
2998 
2999 		if (wpa_derive_pmk_r0(fils_ft, fils_ft_len,
3000 				      conf->ssid, conf->ssid_len,
3001 				      conf->mobility_domain,
3002 				      conf->r0_key_holder,
3003 				      conf->r0_key_holder_len,
3004 				      wpa_auth_get_spa(sm), pmk_r0, pmk_r0_name,
3005 				      sm->wpa_key_mgmt) < 0)
3006 			return -1;
3007 
3008 		wpa_ft_store_pmk_fils(sm, pmk_r0, pmk_r0_name);
3009 		forced_memzero(fils_ft, sizeof(fils_ft));
3010 
3011 		res = wpa_derive_pmk_r1_name(pmk_r0_name, conf->r1_key_holder,
3012 					     wpa_auth_get_spa(sm),
3013 					     sm->pmk_r1_name,
3014 					     fils_ft_len);
3015 		forced_memzero(pmk_r0, PMK_LEN_MAX);
3016 		if (res < 0)
3017 			return -1;
3018 		wpa_hexdump(MSG_DEBUG, "FILS+FT: PMKR1Name", sm->pmk_r1_name,
3019 			    WPA_PMK_NAME_LEN);
3020 		sm->pmk_r1_name_valid = 1;
3021 	}
3022 #endif /* CONFIG_IEEE80211R_AP */
3023 
3024 	res = fils_key_auth_sk(ick, ick_len, snonce, anonce,
3025 			       wpa_auth_get_spa(sm),
3026 			       wpa_auth_get_aa(sm),
3027 			       g_sta ? wpabuf_head(g_sta) : NULL,
3028 			       g_sta ? wpabuf_len(g_sta) : 0,
3029 			       g_ap ? wpabuf_head(g_ap) : NULL,
3030 			       g_ap ? wpabuf_len(g_ap) : 0,
3031 			       sm->wpa_key_mgmt, sm->fils_key_auth_sta,
3032 			       sm->fils_key_auth_ap,
3033 			       &sm->fils_key_auth_len);
3034 	forced_memzero(ick, sizeof(ick));
3035 
3036 	/* Store nonces for (Re)Association Request/Response frame processing */
3037 	os_memcpy(sm->SNonce, snonce, FILS_NONCE_LEN);
3038 	os_memcpy(sm->ANonce, anonce, FILS_NONCE_LEN);
3039 
3040 	return res;
3041 }
3042 
3043 
3044 static int wpa_aead_decrypt(struct wpa_state_machine *sm, struct wpa_ptk *ptk,
3045 			    u8 *buf, size_t buf_len, u16 *_key_data_len)
3046 {
3047 	struct ieee802_1x_hdr *hdr;
3048 	struct wpa_eapol_key *key;
3049 	u8 *pos;
3050 	u16 key_data_len;
3051 	u8 *tmp;
3052 	const u8 *aad[1];
3053 	size_t aad_len[1];
3054 
3055 	hdr = (struct ieee802_1x_hdr *) buf;
3056 	key = (struct wpa_eapol_key *) (hdr + 1);
3057 	pos = (u8 *) (key + 1);
3058 	key_data_len = WPA_GET_BE16(pos);
3059 	if (key_data_len < AES_BLOCK_SIZE ||
3060 	    key_data_len > buf_len - sizeof(*hdr) - sizeof(*key) - 2) {
3061 		wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
3062 				"No room for AES-SIV data in the frame");
3063 		return -1;
3064 	}
3065 	pos += 2; /* Pointing at the Encrypted Key Data field */
3066 
3067 	tmp = os_malloc(key_data_len);
3068 	if (!tmp)
3069 		return -1;
3070 
3071 	/* AES-SIV AAD from EAPOL protocol version field (inclusive) to
3072 	 * to Key Data (exclusive). */
3073 	aad[0] = buf;
3074 	aad_len[0] = pos - buf;
3075 	if (aes_siv_decrypt(ptk->kek, ptk->kek_len, pos, key_data_len,
3076 			    1, aad, aad_len, tmp) < 0) {
3077 		wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
3078 				"Invalid AES-SIV data in the frame");
3079 		bin_clear_free(tmp, key_data_len);
3080 		return -1;
3081 	}
3082 
3083 	/* AEAD decryption and validation completed successfully */
3084 	key_data_len -= AES_BLOCK_SIZE;
3085 	wpa_hexdump_key(MSG_DEBUG, "WPA: Decrypted Key Data",
3086 			tmp, key_data_len);
3087 
3088 	/* Replace Key Data field with the decrypted version */
3089 	os_memcpy(pos, tmp, key_data_len);
3090 	pos -= 2; /* Key Data Length field */
3091 	WPA_PUT_BE16(pos, key_data_len);
3092 	bin_clear_free(tmp, key_data_len);
3093 	if (_key_data_len)
3094 		*_key_data_len = key_data_len;
3095 	return 0;
3096 }
3097 
3098 
3099 const u8 * wpa_fils_validate_fils_session(struct wpa_state_machine *sm,
3100 					  const u8 *ies, size_t ies_len,
3101 					  const u8 *fils_session)
3102 {
3103 	const u8 *ie, *end;
3104 	const u8 *session = NULL;
3105 
3106 	if (!wpa_key_mgmt_fils(sm->wpa_key_mgmt)) {
3107 		wpa_printf(MSG_DEBUG,
3108 			   "FILS: Not a FILS AKM - reject association");
3109 		return NULL;
3110 	}
3111 
3112 	/* Verify Session element */
3113 	ie = ies;
3114 	end = ((const u8 *) ie) + ies_len;
3115 	while (ie + 1 < end) {
3116 		if (ie + 2 + ie[1] > end)
3117 			break;
3118 		if (ie[0] == WLAN_EID_EXTENSION &&
3119 		    ie[1] >= 1 + FILS_SESSION_LEN &&
3120 		    ie[2] == WLAN_EID_EXT_FILS_SESSION) {
3121 			session = ie;
3122 			break;
3123 		}
3124 		ie += 2 + ie[1];
3125 	}
3126 
3127 	if (!session) {
3128 		wpa_printf(MSG_DEBUG,
3129 			   "FILS: %s: Could not find FILS Session element in Assoc Req - reject",
3130 			   __func__);
3131 		return NULL;
3132 	}
3133 
3134 	if (!fils_session) {
3135 		wpa_printf(MSG_DEBUG,
3136 			   "FILS: %s: Could not find FILS Session element in STA entry - reject",
3137 			   __func__);
3138 		return NULL;
3139 	}
3140 
3141 	if (os_memcmp(fils_session, session + 3, FILS_SESSION_LEN) != 0) {
3142 		wpa_printf(MSG_DEBUG, "FILS: Session mismatch");
3143 		wpa_hexdump(MSG_DEBUG, "FILS: Expected FILS Session",
3144 			    fils_session, FILS_SESSION_LEN);
3145 		wpa_hexdump(MSG_DEBUG, "FILS: Received FILS Session",
3146 			    session + 3, FILS_SESSION_LEN);
3147 		return NULL;
3148 	}
3149 	return session;
3150 }
3151 
3152 
3153 int wpa_fils_validate_key_confirm(struct wpa_state_machine *sm, const u8 *ies,
3154 				  size_t ies_len)
3155 {
3156 	struct ieee802_11_elems elems;
3157 
3158 	if (ieee802_11_parse_elems(ies, ies_len, &elems, 1) == ParseFailed) {
3159 		wpa_printf(MSG_DEBUG,
3160 			   "FILS: Failed to parse decrypted elements");
3161 		return -1;
3162 	}
3163 
3164 	if (!elems.fils_session) {
3165 		wpa_printf(MSG_DEBUG, "FILS: No FILS Session element");
3166 		return -1;
3167 	}
3168 
3169 	if (!elems.fils_key_confirm) {
3170 		wpa_printf(MSG_DEBUG, "FILS: No FILS Key Confirm element");
3171 		return -1;
3172 	}
3173 
3174 	if (elems.fils_key_confirm_len != sm->fils_key_auth_len) {
3175 		wpa_printf(MSG_DEBUG,
3176 			   "FILS: Unexpected Key-Auth length %d (expected %zu)",
3177 			   elems.fils_key_confirm_len,
3178 			   sm->fils_key_auth_len);
3179 		return -1;
3180 	}
3181 
3182 	if (os_memcmp(elems.fils_key_confirm, sm->fils_key_auth_sta,
3183 		      sm->fils_key_auth_len) != 0) {
3184 		wpa_printf(MSG_DEBUG, "FILS: Key-Auth mismatch");
3185 		wpa_hexdump(MSG_DEBUG, "FILS: Received Key-Auth",
3186 			    elems.fils_key_confirm, elems.fils_key_confirm_len);
3187 		wpa_hexdump(MSG_DEBUG, "FILS: Expected Key-Auth",
3188 			    sm->fils_key_auth_sta, sm->fils_key_auth_len);
3189 		return -1;
3190 	}
3191 
3192 	return 0;
3193 }
3194 
3195 
3196 int fils_decrypt_assoc(struct wpa_state_machine *sm, const u8 *fils_session,
3197 		       const struct ieee80211_mgmt *mgmt, size_t frame_len,
3198 		       u8 *pos, size_t left)
3199 {
3200 	u16 fc, stype;
3201 	const u8 *end, *ie_start, *ie, *session, *crypt;
3202 	const u8 *aad[5];
3203 	size_t aad_len[5];
3204 
3205 	if (!sm || !sm->PTK_valid) {
3206 		wpa_printf(MSG_DEBUG,
3207 			   "FILS: No KEK to decrypt Assocication Request frame");
3208 		return -1;
3209 	}
3210 
3211 	if (!wpa_key_mgmt_fils(sm->wpa_key_mgmt)) {
3212 		wpa_printf(MSG_DEBUG,
3213 			   "FILS: Not a FILS AKM - reject association");
3214 		return -1;
3215 	}
3216 
3217 	end = ((const u8 *) mgmt) + frame_len;
3218 	fc = le_to_host16(mgmt->frame_control);
3219 	stype = WLAN_FC_GET_STYPE(fc);
3220 	if (stype == WLAN_FC_STYPE_REASSOC_REQ)
3221 		ie_start = mgmt->u.reassoc_req.variable;
3222 	else
3223 		ie_start = mgmt->u.assoc_req.variable;
3224 	ie = ie_start;
3225 
3226 	/*
3227 	 * Find FILS Session element which is the last unencrypted element in
3228 	 * the frame.
3229 	 */
3230 	session = wpa_fils_validate_fils_session(sm, ie, end - ie,
3231 						 fils_session);
3232 	if (!session) {
3233 		wpa_printf(MSG_DEBUG, "FILS: Session validation failed");
3234 		return -1;
3235 	}
3236 
3237 	crypt = session + 2 + session[1];
3238 
3239 	if (end - crypt < AES_BLOCK_SIZE) {
3240 		wpa_printf(MSG_DEBUG,
3241 			   "FILS: Too short frame to include AES-SIV data");
3242 		return -1;
3243 	}
3244 
3245 	/* AES-SIV AAD vectors */
3246 
3247 	/* The STA's MAC address */
3248 	aad[0] = mgmt->sa;
3249 	aad_len[0] = ETH_ALEN;
3250 	/* The AP's BSSID */
3251 	aad[1] = mgmt->da;
3252 	aad_len[1] = ETH_ALEN;
3253 	/* The STA's nonce */
3254 	aad[2] = sm->SNonce;
3255 	aad_len[2] = FILS_NONCE_LEN;
3256 	/* The AP's nonce */
3257 	aad[3] = sm->ANonce;
3258 	aad_len[3] = FILS_NONCE_LEN;
3259 	/*
3260 	 * The (Re)Association Request frame from the Capability Information
3261 	 * field to the FILS Session element (both inclusive).
3262 	 */
3263 	aad[4] = (const u8 *) &mgmt->u.assoc_req.capab_info;
3264 	aad_len[4] = crypt - aad[4];
3265 
3266 	if (aes_siv_decrypt(sm->PTK.kek, sm->PTK.kek_len, crypt, end - crypt,
3267 			    5, aad, aad_len, pos + (crypt - ie_start)) < 0) {
3268 		wpa_printf(MSG_DEBUG,
3269 			   "FILS: Invalid AES-SIV data in the frame");
3270 		return -1;
3271 	}
3272 	wpa_hexdump(MSG_DEBUG, "FILS: Decrypted Association Request elements",
3273 		    pos, left - AES_BLOCK_SIZE);
3274 
3275 	if (wpa_fils_validate_key_confirm(sm, pos, left - AES_BLOCK_SIZE) < 0) {
3276 		wpa_printf(MSG_DEBUG, "FILS: Key Confirm validation failed");
3277 		return -1;
3278 	}
3279 
3280 	return left - AES_BLOCK_SIZE;
3281 }
3282 
3283 
3284 int fils_encrypt_assoc(struct wpa_state_machine *sm, u8 *buf,
3285 		       size_t current_len, size_t max_len,
3286 		       const struct wpabuf *hlp)
3287 {
3288 	u8 *end = buf + max_len;
3289 	u8 *pos = buf + current_len;
3290 	struct ieee80211_mgmt *mgmt;
3291 	struct wpabuf *plain;
3292 	const u8 *aad[5];
3293 	size_t aad_len[5];
3294 
3295 	if (!sm || !sm->PTK_valid)
3296 		return -1;
3297 
3298 	wpa_hexdump(MSG_DEBUG,
3299 		    "FILS: Association Response frame before FILS processing",
3300 		    buf, current_len);
3301 
3302 	mgmt = (struct ieee80211_mgmt *) buf;
3303 
3304 	/* AES-SIV AAD vectors */
3305 
3306 	/* The AP's BSSID */
3307 	aad[0] = mgmt->sa;
3308 	aad_len[0] = ETH_ALEN;
3309 	/* The STA's MAC address */
3310 	aad[1] = mgmt->da;
3311 	aad_len[1] = ETH_ALEN;
3312 	/* The AP's nonce */
3313 	aad[2] = sm->ANonce;
3314 	aad_len[2] = FILS_NONCE_LEN;
3315 	/* The STA's nonce */
3316 	aad[3] = sm->SNonce;
3317 	aad_len[3] = FILS_NONCE_LEN;
3318 	/*
3319 	 * The (Re)Association Response frame from the Capability Information
3320 	 * field (the same offset in both Association and Reassociation
3321 	 * Response frames) to the FILS Session element (both inclusive).
3322 	 */
3323 	aad[4] = (const u8 *) &mgmt->u.assoc_resp.capab_info;
3324 	aad_len[4] = pos - aad[4];
3325 
3326 	/* The following elements will be encrypted with AES-SIV */
3327 	plain = fils_prepare_plainbuf(sm, hlp);
3328 	if (!plain) {
3329 		wpa_printf(MSG_DEBUG, "FILS: Plain buffer prep failed");
3330 		return -1;
3331 	}
3332 
3333 	if (pos + wpabuf_len(plain) + AES_BLOCK_SIZE > end) {
3334 		wpa_printf(MSG_DEBUG,
3335 			   "FILS: Not enough room for FILS elements");
3336 		wpabuf_clear_free(plain);
3337 		return -1;
3338 	}
3339 
3340 	wpa_hexdump_buf_key(MSG_DEBUG, "FILS: Association Response plaintext",
3341 			    plain);
3342 
3343 	if (aes_siv_encrypt(sm->PTK.kek, sm->PTK.kek_len,
3344 			    wpabuf_head(plain), wpabuf_len(plain),
3345 			    5, aad, aad_len, pos) < 0) {
3346 		wpabuf_clear_free(plain);
3347 		return -1;
3348 	}
3349 
3350 	wpa_hexdump(MSG_DEBUG,
3351 		    "FILS: Encrypted Association Response elements",
3352 		    pos, AES_BLOCK_SIZE + wpabuf_len(plain));
3353 	current_len += wpabuf_len(plain) + AES_BLOCK_SIZE;
3354 	wpabuf_clear_free(plain);
3355 
3356 	sm->fils_completed = 1;
3357 
3358 	return current_len;
3359 }
3360 
3361 
3362 static struct wpabuf * fils_prepare_plainbuf(struct wpa_state_machine *sm,
3363 					     const struct wpabuf *hlp)
3364 {
3365 	struct wpabuf *plain;
3366 	u8 *len, *tmp, *tmp2;
3367 	u8 hdr[2];
3368 	u8 *gtk, stub_gtk[32];
3369 	size_t gtk_len;
3370 	struct wpa_group *gsm;
3371 	size_t plain_len;
3372 	struct wpa_auth_config *conf = &sm->wpa_auth->conf;
3373 
3374 	plain_len = 1000 + ieee80211w_kde_len(sm);
3375 	if (conf->transition_disable)
3376 		plain_len += 2 + RSN_SELECTOR_LEN + 1;
3377 	plain = wpabuf_alloc(plain_len);
3378 	if (!plain)
3379 		return NULL;
3380 
3381 	/* TODO: FILS Public Key */
3382 
3383 	/* FILS Key Confirmation */
3384 	wpabuf_put_u8(plain, WLAN_EID_EXTENSION); /* Element ID */
3385 	wpabuf_put_u8(plain, 1 + sm->fils_key_auth_len); /* Length */
3386 	/* Element ID Extension */
3387 	wpabuf_put_u8(plain, WLAN_EID_EXT_FILS_KEY_CONFIRM);
3388 	wpabuf_put_data(plain, sm->fils_key_auth_ap, sm->fils_key_auth_len);
3389 
3390 	/* FILS HLP Container */
3391 	if (hlp)
3392 		wpabuf_put_buf(plain, hlp);
3393 
3394 	/* TODO: FILS IP Address Assignment */
3395 
3396 	/* Key Delivery */
3397 	gsm = sm->group;
3398 	wpabuf_put_u8(plain, WLAN_EID_EXTENSION); /* Element ID */
3399 	len = wpabuf_put(plain, 1);
3400 	wpabuf_put_u8(plain, WLAN_EID_EXT_KEY_DELIVERY);
3401 	wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN,
3402 			    wpabuf_put(plain, WPA_KEY_RSC_LEN));
3403 	/* GTK KDE */
3404 	gtk = gsm->GTK[gsm->GN - 1];
3405 	gtk_len = gsm->GTK_len;
3406 	if (conf->disable_gtk || sm->wpa_key_mgmt == WPA_KEY_MGMT_OSEN) {
3407 		/*
3408 		 * Provide unique random GTK to each STA to prevent use
3409 		 * of GTK in the BSS.
3410 		 */
3411 		if (random_get_bytes(stub_gtk, gtk_len) < 0) {
3412 			wpabuf_clear_free(plain);
3413 			return NULL;
3414 		}
3415 		gtk = stub_gtk;
3416 	}
3417 	hdr[0] = gsm->GN & 0x03;
3418 	hdr[1] = 0;
3419 	tmp = wpabuf_put(plain, 0);
3420 	tmp2 = wpa_add_kde(tmp, RSN_KEY_DATA_GROUPKEY, hdr, 2,
3421 			   gtk, gtk_len);
3422 	wpabuf_put(plain, tmp2 - tmp);
3423 
3424 	/* IGTK KDE and BIGTK KDE */
3425 	tmp = wpabuf_put(plain, 0);
3426 	tmp2 = ieee80211w_kde_add(sm, tmp);
3427 	wpabuf_put(plain, tmp2 - tmp);
3428 
3429 	if (conf->transition_disable) {
3430 		tmp = wpabuf_put(plain, 0);
3431 		tmp2 = wpa_add_kde(tmp, WFA_KEY_DATA_TRANSITION_DISABLE,
3432 				   &conf->transition_disable, 1, NULL, 0);
3433 		wpabuf_put(plain, tmp2 - tmp);
3434 	}
3435 
3436 	*len = (u8 *) wpabuf_put(plain, 0) - len - 1;
3437 
3438 #ifdef CONFIG_OCV
3439 	if (wpa_auth_uses_ocv(sm)) {
3440 		struct wpa_channel_info ci;
3441 		u8 *pos;
3442 
3443 		if (wpa_channel_info(sm->wpa_auth, &ci) != 0) {
3444 			wpa_printf(MSG_WARNING,
3445 				   "FILS: Failed to get channel info for OCI element");
3446 			wpabuf_clear_free(plain);
3447 			return NULL;
3448 		}
3449 #ifdef CONFIG_TESTING_OPTIONS
3450 		if (conf->oci_freq_override_fils_assoc) {
3451 			wpa_printf(MSG_INFO,
3452 				   "TEST: Override OCI frequency %d -> %u MHz",
3453 				   ci.frequency,
3454 				   conf->oci_freq_override_fils_assoc);
3455 			ci.frequency = conf->oci_freq_override_fils_assoc;
3456 		}
3457 #endif /* CONFIG_TESTING_OPTIONS */
3458 
3459 		pos = wpabuf_put(plain, OCV_OCI_EXTENDED_LEN);
3460 		if (ocv_insert_extended_oci(&ci, pos) < 0) {
3461 			wpabuf_clear_free(plain);
3462 			return NULL;
3463 		}
3464 	}
3465 #endif /* CONFIG_OCV */
3466 
3467 	return plain;
3468 }
3469 
3470 
3471 int fils_set_tk(struct wpa_state_machine *sm)
3472 {
3473 	enum wpa_alg alg;
3474 	int klen;
3475 
3476 	if (!sm || !sm->PTK_valid) {
3477 		wpa_printf(MSG_DEBUG, "FILS: No valid PTK available to set TK");
3478 		return -1;
3479 	}
3480 	if (sm->tk_already_set) {
3481 		wpa_printf(MSG_DEBUG, "FILS: TK already set to the driver");
3482 		return -1;
3483 	}
3484 
3485 	alg = wpa_cipher_to_alg(sm->pairwise);
3486 	klen = wpa_cipher_key_len(sm->pairwise);
3487 
3488 	wpa_printf(MSG_DEBUG, "FILS: Configure TK to the driver");
3489 	if (wpa_auth_set_key(sm->wpa_auth, 0, alg, sm->addr, 0,
3490 			     sm->PTK.tk, klen, KEY_FLAG_PAIRWISE_RX_TX)) {
3491 		wpa_printf(MSG_DEBUG, "FILS: Failed to set TK to the driver");
3492 		return -1;
3493 	}
3494 
3495 #ifdef CONFIG_PASN
3496 	if (sm->wpa_auth->conf.secure_ltf &&
3497 	    ieee802_11_rsnx_capab(sm->rsnxe, WLAN_RSNX_CAPAB_SECURE_LTF) &&
3498 	    wpa_auth_set_ltf_keyseed(sm->wpa_auth, sm->addr,
3499 				     sm->PTK.ltf_keyseed,
3500 				     sm->PTK.ltf_keyseed_len)) {
3501 		wpa_printf(MSG_ERROR,
3502 			   "FILS: Failed to set LTF keyseed to driver");
3503 		return -1;
3504 	}
3505 #endif /* CONFIG_PASN */
3506 
3507 	sm->pairwise_set = true;
3508 	sm->tk_already_set = true;
3509 
3510 	wpa_auth_store_ptksa(sm->wpa_auth, sm->addr, sm->pairwise,
3511 			     dot11RSNAConfigPMKLifetime, &sm->PTK);
3512 
3513 	return 0;
3514 }
3515 
3516 
3517 u8 * hostapd_eid_assoc_fils_session(struct wpa_state_machine *sm, u8 *buf,
3518 				    const u8 *fils_session, struct wpabuf *hlp)
3519 {
3520 	struct wpabuf *plain;
3521 	u8 *pos = buf;
3522 
3523 	/* FILS Session */
3524 	*pos++ = WLAN_EID_EXTENSION; /* Element ID */
3525 	*pos++ = 1 + FILS_SESSION_LEN; /* Length */
3526 	*pos++ = WLAN_EID_EXT_FILS_SESSION; /* Element ID Extension */
3527 	os_memcpy(pos, fils_session, FILS_SESSION_LEN);
3528 	pos += FILS_SESSION_LEN;
3529 
3530 	plain = fils_prepare_plainbuf(sm, hlp);
3531 	if (!plain) {
3532 		wpa_printf(MSG_DEBUG, "FILS: Plain buffer prep failed");
3533 		return NULL;
3534 	}
3535 
3536 	os_memcpy(pos, wpabuf_head(plain), wpabuf_len(plain));
3537 	pos += wpabuf_len(plain);
3538 
3539 	wpa_printf(MSG_DEBUG, "%s: plain buf_len: %zu", __func__,
3540 		   wpabuf_len(plain));
3541 	wpabuf_clear_free(plain);
3542 	sm->fils_completed = 1;
3543 	return pos;
3544 }
3545 
3546 #endif /* CONFIG_FILS */
3547 
3548 
3549 #ifdef CONFIG_OCV
3550 int get_sta_tx_parameters(struct wpa_state_machine *sm, int ap_max_chanwidth,
3551 			  int ap_seg1_idx, int *bandwidth, int *seg1_idx)
3552 {
3553 	struct wpa_authenticator *wpa_auth = sm->wpa_auth;
3554 
3555 	if (!wpa_auth->cb->get_sta_tx_params)
3556 		return -1;
3557 	return wpa_auth->cb->get_sta_tx_params(wpa_auth->cb_ctx, sm->addr,
3558 					       ap_max_chanwidth, ap_seg1_idx,
3559 					       bandwidth, seg1_idx);
3560 }
3561 #endif /* CONFIG_OCV */
3562 
3563 
3564 static int wpa_auth_validate_ml_kdes_m2(struct wpa_state_machine *sm,
3565 					struct wpa_eapol_ie_parse *kde)
3566 {
3567 #ifdef CONFIG_IEEE80211BE
3568 	int i;
3569 	unsigned int n_links = 0;
3570 
3571 	if (sm->mld_assoc_link_id < 0)
3572 		return 0;
3573 
3574 	/* MLD MAC address must be the same */
3575 	if (!kde->mac_addr ||
3576 	    !ether_addr_equal(kde->mac_addr, sm->peer_mld_addr)) {
3577 		wpa_printf(MSG_DEBUG, "RSN: MLD: Invalid MLD address");
3578 		return -1;
3579 	}
3580 
3581 	/* Find matching link ID and the MAC address for each link */
3582 	for_each_link(kde->valid_mlo_links, i) {
3583 		/*
3584 		 * Each entry should contain the link information and the MAC
3585 		 * address.
3586 		 */
3587 		if (kde->mlo_link_len[i] != 1 + ETH_ALEN) {
3588 			wpa_printf(MSG_DEBUG,
3589 				   "RSN: MLD: Invalid MLO Link (ID %u) KDE len=%zu",
3590 				   i, kde->mlo_link_len[i]);
3591 			return -1;
3592 		}
3593 
3594 		if (!sm->mld_links[i].valid || i == sm->mld_assoc_link_id) {
3595 			wpa_printf(MSG_DEBUG,
3596 				   "RSN: MLD: Invalid link ID=%u", i);
3597 			return -1;
3598 		}
3599 
3600 		if (!ether_addr_equal(sm->mld_links[i].peer_addr,
3601 				      kde->mlo_link[i] + 1)) {
3602 			wpa_printf(MSG_DEBUG,
3603 				   "RSN: MLD: invalid MAC address=" MACSTR
3604 				   " expected " MACSTR " (link ID %u)",
3605 				   MAC2STR(kde->mlo_link[i] + 1),
3606 				   MAC2STR(sm->mld_links[i].peer_addr), i);
3607 			return -1;
3608 		}
3609 
3610 		n_links++;
3611 	}
3612 
3613 	/* Must have the same number of MLO links (excluding the local one) */
3614 	if (n_links != sm->n_mld_affiliated_links) {
3615 		wpa_printf(MSG_DEBUG,
3616 			   "RSN: MLD: Expecting %u MLD links in msg 2, but got %u",
3617 			   sm->n_mld_affiliated_links, n_links);
3618 		return -1;
3619 	}
3620 #endif /* CONFIG_IEEE80211BE */
3621 
3622 	return 0;
3623 }
3624 
3625 
3626 SM_STATE(WPA_PTK, PTKCALCNEGOTIATING)
3627 {
3628 	struct wpa_authenticator *wpa_auth = sm->wpa_auth;
3629 	struct wpa_ptk PTK;
3630 	int ok = 0, psk_found = 0;
3631 	const u8 *pmk = NULL;
3632 	size_t pmk_len;
3633 	int ft;
3634 	const u8 *eapol_key_ie, *key_data, *mic;
3635 	u16 key_info, ver, key_data_length;
3636 	size_t mic_len, eapol_key_ie_len;
3637 	struct ieee802_1x_hdr *hdr;
3638 	struct wpa_eapol_key *key;
3639 	struct wpa_eapol_ie_parse kde;
3640 	int vlan_id = 0;
3641 	int owe_ptk_workaround = !!wpa_auth->conf.owe_ptk_workaround;
3642 	u8 pmk_r0[PMK_LEN_MAX], pmk_r0_name[WPA_PMK_NAME_LEN];
3643 	u8 pmk_r1[PMK_LEN_MAX];
3644 	size_t key_len;
3645 	u8 *key_data_buf = NULL;
3646 	size_t key_data_buf_len = 0;
3647 	bool derive_kdk, no_kdk = false;
3648 
3649 	SM_ENTRY_MA(WPA_PTK, PTKCALCNEGOTIATING, wpa_ptk);
3650 	sm->EAPOLKeyReceived = false;
3651 	sm->update_snonce = false;
3652 	os_memset(&PTK, 0, sizeof(PTK));
3653 
3654 	mic_len = wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len);
3655 
3656 	derive_kdk = sm->wpa_auth->conf.secure_ltf &&
3657 		ieee802_11_rsnx_capab(sm->rsnxe, WLAN_RSNX_CAPAB_SECURE_LTF);
3658 
3659 	/* WPA with IEEE 802.1X: use the derived PMK from EAP
3660 	 * WPA-PSK: iterate through possible PSKs and select the one matching
3661 	 * the packet */
3662 	for (;;) {
3663 		if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) &&
3664 		    !wpa_key_mgmt_sae(sm->wpa_key_mgmt)) {
3665 			pmk = wpa_auth_get_psk(sm->wpa_auth, sm->addr,
3666 					       sm->p2p_dev_addr, pmk, &pmk_len,
3667 					       &vlan_id);
3668 			if (!pmk)
3669 				break;
3670 			psk_found = 1;
3671 #ifdef CONFIG_IEEE80211R_AP
3672 			if (wpa_key_mgmt_ft_psk(sm->wpa_key_mgmt)) {
3673 				os_memcpy(sm->xxkey, pmk, pmk_len);
3674 				sm->xxkey_len = pmk_len;
3675 			}
3676 #endif /* CONFIG_IEEE80211R_AP */
3677 		} else {
3678 			pmk = sm->PMK;
3679 			pmk_len = sm->pmk_len;
3680 		}
3681 
3682 		if ((!pmk || !pmk_len) && sm->pmksa) {
3683 			wpa_printf(MSG_DEBUG, "WPA: Use PMK from PMKSA cache");
3684 			pmk = sm->pmksa->pmk;
3685 			pmk_len = sm->pmksa->pmk_len;
3686 		}
3687 
3688 		no_kdk = false;
3689 	try_without_kdk:
3690 		if (wpa_derive_ptk(sm, sm->SNonce, pmk, pmk_len, &PTK,
3691 				   owe_ptk_workaround == 2, pmk_r0, pmk_r1,
3692 				   pmk_r0_name, &key_len, no_kdk) < 0)
3693 			break;
3694 
3695 		if (mic_len &&
3696 		    wpa_verify_key_mic(sm->wpa_key_mgmt, pmk_len, &PTK,
3697 				       sm->last_rx_eapol_key,
3698 				       sm->last_rx_eapol_key_len) == 0) {
3699 			if (sm->PMK != pmk) {
3700 				os_memcpy(sm->PMK, pmk, pmk_len);
3701 				sm->pmk_len = pmk_len;
3702 			}
3703 			ok = 1;
3704 			break;
3705 		}
3706 
3707 #ifdef CONFIG_FILS
3708 		if (!mic_len &&
3709 		    wpa_aead_decrypt(sm, &PTK, sm->last_rx_eapol_key,
3710 				     sm->last_rx_eapol_key_len, NULL) == 0) {
3711 			ok = 1;
3712 			break;
3713 		}
3714 #endif /* CONFIG_FILS */
3715 
3716 #ifdef CONFIG_OWE
3717 		if (sm->wpa_key_mgmt == WPA_KEY_MGMT_OWE && pmk_len > 32 &&
3718 		    owe_ptk_workaround == 1) {
3719 			wpa_printf(MSG_DEBUG,
3720 				   "OWE: Try PTK derivation workaround with SHA256");
3721 			owe_ptk_workaround = 2;
3722 			continue;
3723 		}
3724 #endif /* CONFIG_OWE */
3725 
3726 		/* Some deployed STAs that advertise SecureLTF support in the
3727 		 * RSNXE in (Re)Association Request frames, do not derive KDK
3728 		 * during PTK generation. Try to work around this by checking if
3729 		 * a PTK derived without KDK would result in a matching MIC. */
3730 		if (!sm->wpa_auth->conf.force_kdk_derivation &&
3731 		    derive_kdk && !no_kdk) {
3732 			wpa_printf(MSG_DEBUG,
3733 				   "Try new PTK derivation without KDK as a workaround");
3734 			no_kdk = true;
3735 			goto try_without_kdk;
3736 		}
3737 
3738 		if (!wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) ||
3739 		    wpa_key_mgmt_sae(sm->wpa_key_mgmt))
3740 			break;
3741 	}
3742 
3743 	if (no_kdk && ok) {
3744 		/* The workaround worked, so allow the 4-way handshake to be
3745 		 * completed with the PTK that was derived without the KDK. */
3746 		wpa_printf(MSG_DEBUG,
3747 			   "PTK without KDK worked - misbehaving STA "
3748 			   MACSTR, MAC2STR(sm->addr));
3749 	}
3750 
3751 	if (!ok && wpa_key_mgmt_wpa_psk_no_sae(sm->wpa_key_mgmt) &&
3752 	    wpa_auth->conf.radius_psk && wpa_auth->cb->request_radius_psk &&
3753 	    !sm->waiting_radius_psk) {
3754 		wpa_printf(MSG_DEBUG, "No PSK available - ask RADIUS server");
3755 		wpa_auth->cb->request_radius_psk(wpa_auth->cb_ctx, sm->addr,
3756 						 sm->wpa_key_mgmt,
3757 						 sm->ANonce,
3758 						 sm->last_rx_eapol_key,
3759 						 sm->last_rx_eapol_key_len);
3760 		sm->waiting_radius_psk = 1;
3761 		goto out;
3762 	}
3763 
3764 	if (!ok) {
3765 		wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm),
3766 				LOGGER_DEBUG,
3767 				"invalid MIC in msg 2/4 of 4-Way Handshake");
3768 		if (psk_found)
3769 			wpa_auth_psk_failure_report(sm->wpa_auth, sm->addr);
3770 		goto out;
3771 	}
3772 
3773 	/*
3774 	 * Note: last_rx_eapol_key length fields have already been validated in
3775 	 * wpa_receive().
3776 	 */
3777 	hdr = (struct ieee802_1x_hdr *) sm->last_rx_eapol_key;
3778 	key = (struct wpa_eapol_key *) (hdr + 1);
3779 	mic = (u8 *) (key + 1);
3780 	key_info = WPA_GET_BE16(key->key_info);
3781 	key_data = mic + mic_len + 2;
3782 	key_data_length = WPA_GET_BE16(mic + mic_len);
3783 	if (key_data_length > sm->last_rx_eapol_key_len - sizeof(*hdr) -
3784 	    sizeof(*key) - mic_len - 2)
3785 		goto out;
3786 
3787 	ver = key_info & WPA_KEY_INFO_TYPE_MASK;
3788 	if (mic_len && (key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
3789 		if (ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES &&
3790 		    ver != WPA_KEY_INFO_TYPE_AES_128_CMAC &&
3791 		    !wpa_use_aes_key_wrap(sm->wpa_key_mgmt)) {
3792 			wpa_printf(MSG_INFO,
3793 				   "Unsupported EAPOL-Key Key Data field encryption");
3794 			goto out;
3795 		}
3796 
3797 		if (key_data_length < 8 || key_data_length % 8) {
3798 			wpa_printf(MSG_INFO,
3799 				   "RSN: Unsupported AES-WRAP len %u",
3800 				   key_data_length);
3801 			goto out;
3802 		}
3803 		key_data_length -= 8; /* AES-WRAP adds 8 bytes */
3804 		key_data_buf = os_malloc(key_data_length);
3805 		if (!key_data_buf)
3806 			goto out;
3807 		key_data_buf_len = key_data_length;
3808 		if (aes_unwrap(PTK.kek, PTK.kek_len, key_data_length / 8,
3809 			       key_data, key_data_buf)) {
3810 			bin_clear_free(key_data_buf, key_data_buf_len);
3811 			wpa_printf(MSG_INFO,
3812 				   "RSN: AES unwrap failed - could not decrypt EAPOL-Key key data");
3813 			goto out;
3814 		}
3815 		key_data = key_data_buf;
3816 		wpa_hexdump_key(MSG_DEBUG, "RSN: Decrypted EAPOL-Key Key Data",
3817 				key_data, key_data_length);
3818 	}
3819 
3820 	if (wpa_parse_kde_ies(key_data, key_data_length, &kde) < 0) {
3821 		wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
3822 				 "received EAPOL-Key msg 2/4 with invalid Key Data contents");
3823 		goto out;
3824 	}
3825 	if (kde.rsn_ie) {
3826 		eapol_key_ie = kde.rsn_ie;
3827 		eapol_key_ie_len = kde.rsn_ie_len;
3828 	} else if (kde.osen) {
3829 		eapol_key_ie = kde.osen;
3830 		eapol_key_ie_len = kde.osen_len;
3831 	} else {
3832 		eapol_key_ie = kde.wpa_ie;
3833 		eapol_key_ie_len = kde.wpa_ie_len;
3834 	}
3835 	ft = sm->wpa == WPA_VERSION_WPA2 && wpa_key_mgmt_ft(sm->wpa_key_mgmt);
3836 	if (!sm->wpa_ie ||
3837 	    wpa_compare_rsn_ie(ft, sm->wpa_ie, sm->wpa_ie_len,
3838 			       eapol_key_ie, eapol_key_ie_len)) {
3839 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
3840 				"WPA IE from (Re)AssocReq did not match with msg 2/4");
3841 		if (sm->wpa_ie) {
3842 			wpa_hexdump(MSG_DEBUG, "WPA IE in AssocReq",
3843 				    sm->wpa_ie, sm->wpa_ie_len);
3844 		}
3845 		wpa_hexdump(MSG_DEBUG, "WPA IE in msg 2/4",
3846 			    eapol_key_ie, eapol_key_ie_len);
3847 		/* MLME-DEAUTHENTICATE.request */
3848 		wpa_sta_disconnect(wpa_auth, sm->addr,
3849 				   WLAN_REASON_PREV_AUTH_NOT_VALID);
3850 		goto out;
3851 	}
3852 	if ((!sm->rsnxe && kde.rsnxe) ||
3853 	    (sm->rsnxe && !kde.rsnxe) ||
3854 	    (sm->rsnxe && kde.rsnxe &&
3855 	     (sm->rsnxe_len != kde.rsnxe_len ||
3856 	      os_memcmp(sm->rsnxe, kde.rsnxe, sm->rsnxe_len) != 0))) {
3857 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
3858 				"RSNXE from (Re)AssocReq did not match the one in EAPOL-Key msg 2/4");
3859 		wpa_hexdump(MSG_DEBUG, "RSNXE in AssocReq",
3860 			    sm->rsnxe, sm->rsnxe_len);
3861 		wpa_hexdump(MSG_DEBUG, "RSNXE in EAPOL-Key msg 2/4",
3862 			    kde.rsnxe, kde.rsnxe_len);
3863 		/* MLME-DEAUTHENTICATE.request */
3864 		wpa_sta_disconnect(wpa_auth, sm->addr,
3865 				   WLAN_REASON_PREV_AUTH_NOT_VALID);
3866 		goto out;
3867 	}
3868 #ifdef CONFIG_OCV
3869 	if (wpa_auth_uses_ocv(sm)) {
3870 		struct wpa_channel_info ci;
3871 		int tx_chanwidth;
3872 		int tx_seg1_idx;
3873 		enum oci_verify_result res;
3874 
3875 		if (wpa_channel_info(wpa_auth, &ci) != 0) {
3876 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
3877 					LOGGER_INFO,
3878 					"Failed to get channel info to validate received OCI in EAPOL-Key 2/4");
3879 			goto out;
3880 		}
3881 
3882 		if (get_sta_tx_parameters(sm,
3883 					  channel_width_to_int(ci.chanwidth),
3884 					  ci.seg1_idx, &tx_chanwidth,
3885 					  &tx_seg1_idx) < 0)
3886 			goto out;
3887 
3888 		res = ocv_verify_tx_params(kde.oci, kde.oci_len, &ci,
3889 					   tx_chanwidth, tx_seg1_idx);
3890 		if (wpa_auth_uses_ocv(sm) == 2 && res == OCI_NOT_FOUND) {
3891 			/* Work around misbehaving STAs */
3892 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
3893 					 LOGGER_INFO,
3894 					 "Disable OCV with a STA that does not send OCI");
3895 			wpa_auth_set_ocv(sm, 0);
3896 		} else if (res != OCI_SUCCESS) {
3897 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
3898 					 LOGGER_INFO,
3899 					 "OCV failed: %s", ocv_errorstr);
3900 			if (wpa_auth->conf.msg_ctx)
3901 				wpa_msg(wpa_auth->conf.msg_ctx, MSG_INFO,
3902 					OCV_FAILURE "addr=" MACSTR
3903 					" frame=eapol-key-m2 error=%s",
3904 					MAC2STR(wpa_auth_get_spa(sm)),
3905 					ocv_errorstr);
3906 			goto out;
3907 		}
3908 	}
3909 #endif /* CONFIG_OCV */
3910 #ifdef CONFIG_IEEE80211R_AP
3911 	if (ft && ft_check_msg_2_of_4(wpa_auth, sm, &kde) < 0) {
3912 		wpa_sta_disconnect(wpa_auth, sm->addr,
3913 				   WLAN_REASON_PREV_AUTH_NOT_VALID);
3914 		goto out;
3915 	}
3916 #endif /* CONFIG_IEEE80211R_AP */
3917 #ifdef CONFIG_P2P
3918 	if (kde.ip_addr_req && kde.ip_addr_req[0] &&
3919 	    wpa_auth->ip_pool && WPA_GET_BE32(sm->ip_addr) == 0) {
3920 		int idx;
3921 		wpa_printf(MSG_DEBUG,
3922 			   "P2P: IP address requested in EAPOL-Key exchange");
3923 		idx = bitfield_get_first_zero(wpa_auth->ip_pool);
3924 		if (idx >= 0) {
3925 			u32 start = WPA_GET_BE32(wpa_auth->conf.ip_addr_start);
3926 			bitfield_set(wpa_auth->ip_pool, idx);
3927 			sm->ip_addr_bit = idx;
3928 			WPA_PUT_BE32(sm->ip_addr, start + idx);
3929 			wpa_printf(MSG_DEBUG,
3930 				   "P2P: Assigned IP address %u.%u.%u.%u to "
3931 				   MACSTR " (bit %u)",
3932 				   sm->ip_addr[0], sm->ip_addr[1],
3933 				   sm->ip_addr[2], sm->ip_addr[3],
3934 				   MAC2STR(wpa_auth_get_spa(sm)),
3935 				   sm->ip_addr_bit);
3936 		}
3937 	}
3938 #endif /* CONFIG_P2P */
3939 
3940 #ifdef CONFIG_DPP2
3941 	if (DPP_VERSION > 1 && kde.dpp_kde) {
3942 		wpa_printf(MSG_DEBUG,
3943 			   "DPP: peer Protocol Version %u Flags 0x%x",
3944 			   kde.dpp_kde[0], kde.dpp_kde[1]);
3945 		if (sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP &&
3946 		    wpa_auth->conf.dpp_pfs != 2 &&
3947 		    (kde.dpp_kde[1] & DPP_KDE_PFS_ALLOWED) &&
3948 		    !sm->dpp_z) {
3949 			wpa_printf(MSG_INFO,
3950 				   "DPP: Peer indicated it supports PFS and local configuration allows this, but PFS was not negotiated for the association");
3951 			wpa_sta_disconnect(wpa_auth, sm->addr,
3952 					   WLAN_REASON_PREV_AUTH_NOT_VALID);
3953 			goto out;
3954 		}
3955 	}
3956 #endif /* CONFIG_DPP2 */
3957 
3958 	if (wpa_auth_validate_ml_kdes_m2(sm, &kde) < 0) {
3959 		wpa_sta_disconnect(wpa_auth, sm->addr,
3960 				   WLAN_REASON_PREV_AUTH_NOT_VALID);
3961 		return;
3962 	}
3963 
3964 	if (vlan_id && wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) &&
3965 	    wpa_auth_update_vlan(wpa_auth, sm->addr, vlan_id) < 0) {
3966 		wpa_sta_disconnect(wpa_auth, sm->addr,
3967 				   WLAN_REASON_PREV_AUTH_NOT_VALID);
3968 		goto out;
3969 	}
3970 
3971 	sm->pending_1_of_4_timeout = 0;
3972 	eloop_cancel_timeout(wpa_send_eapol_timeout, sm->wpa_auth, sm);
3973 
3974 	if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) && sm->PMK != pmk) {
3975 		/* PSK may have changed from the previous choice, so update
3976 		 * state machine data based on whatever PSK was selected here.
3977 		 */
3978 		os_memcpy(sm->PMK, pmk, PMK_LEN);
3979 		sm->pmk_len = PMK_LEN;
3980 	}
3981 
3982 	sm->MICVerified = true;
3983 
3984 #ifdef CONFIG_IEEE80211R_AP
3985 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt) && !sm->ft_completed) {
3986 		wpa_printf(MSG_DEBUG, "FT: Store PMK-R0/PMK-R1");
3987 		wpa_auth_ft_store_keys(sm, pmk_r0, pmk_r1, pmk_r0_name,
3988 				       key_len);
3989 	}
3990 #endif /* CONFIG_IEEE80211R_AP */
3991 
3992 	os_memcpy(&sm->PTK, &PTK, sizeof(PTK));
3993 	forced_memzero(&PTK, sizeof(PTK));
3994 	sm->PTK_valid = true;
3995 out:
3996 	forced_memzero(pmk_r0, sizeof(pmk_r0));
3997 	forced_memzero(pmk_r1, sizeof(pmk_r1));
3998 	bin_clear_free(key_data_buf, key_data_buf_len);
3999 }
4000 
4001 
4002 SM_STATE(WPA_PTK, PTKCALCNEGOTIATING2)
4003 {
4004 	SM_ENTRY_MA(WPA_PTK, PTKCALCNEGOTIATING2, wpa_ptk);
4005 	sm->TimeoutCtr = 0;
4006 }
4007 
4008 
4009 static int ieee80211w_kde_len(struct wpa_state_machine *sm)
4010 {
4011 	size_t len = 0;
4012 	struct wpa_authenticator *wpa_auth = sm->wpa_auth;
4013 
4014 	if (sm->mgmt_frame_prot) {
4015 		len += 2 + RSN_SELECTOR_LEN + WPA_IGTK_KDE_PREFIX_LEN;
4016 		len += wpa_cipher_key_len(wpa_auth->conf.group_mgmt_cipher);
4017 	}
4018 
4019 	if (wpa_auth->conf.tx_bss_auth)
4020 		wpa_auth = wpa_auth->conf.tx_bss_auth;
4021 	if (sm->mgmt_frame_prot && sm->wpa_auth->conf.beacon_prot) {
4022 		len += 2 + RSN_SELECTOR_LEN + WPA_BIGTK_KDE_PREFIX_LEN;
4023 		len += wpa_cipher_key_len(wpa_auth->conf.group_mgmt_cipher);
4024 	}
4025 
4026 	return len;
4027 }
4028 
4029 
4030 static u8 * ieee80211w_kde_add(struct wpa_state_machine *sm, u8 *pos)
4031 {
4032 	struct wpa_igtk_kde igtk;
4033 	struct wpa_bigtk_kde bigtk;
4034 	struct wpa_group *gsm = sm->group;
4035 	u8 rsc[WPA_KEY_RSC_LEN];
4036 	struct wpa_authenticator *wpa_auth = sm->wpa_auth;
4037 	struct wpa_auth_config *conf = &wpa_auth->conf;
4038 	size_t len = wpa_cipher_key_len(conf->group_mgmt_cipher);
4039 
4040 	if (!sm->mgmt_frame_prot)
4041 		return pos;
4042 
4043 #ifdef CONFIG_IEEE80211BE
4044 	if (sm->mld_assoc_link_id >= 0)
4045 		return pos; /* Use per-link MLO KDEs instead */
4046 #endif /* CONFIG_IEEE80211BE */
4047 
4048 	igtk.keyid[0] = gsm->GN_igtk;
4049 	igtk.keyid[1] = 0;
4050 	if (gsm->wpa_group_state != WPA_GROUP_SETKEYSDONE ||
4051 	    wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN_igtk, rsc) < 0)
4052 		os_memset(igtk.pn, 0, sizeof(igtk.pn));
4053 	else
4054 		os_memcpy(igtk.pn, rsc, sizeof(igtk.pn));
4055 	os_memcpy(igtk.igtk, gsm->IGTK[gsm->GN_igtk - 4], len);
4056 	if (conf->disable_gtk || sm->wpa_key_mgmt == WPA_KEY_MGMT_OSEN) {
4057 		/*
4058 		 * Provide unique random IGTK to each STA to prevent use of
4059 		 * IGTK in the BSS.
4060 		 */
4061 		if (random_get_bytes(igtk.igtk, len) < 0)
4062 			return pos;
4063 	}
4064 	pos = wpa_add_kde(pos, RSN_KEY_DATA_IGTK,
4065 			  (const u8 *) &igtk, WPA_IGTK_KDE_PREFIX_LEN + len,
4066 			  NULL, 0);
4067 	forced_memzero(&igtk, sizeof(igtk));
4068 
4069 	if (wpa_auth->conf.tx_bss_auth) {
4070 		wpa_auth = wpa_auth->conf.tx_bss_auth;
4071 		conf = &wpa_auth->conf;
4072 		len = wpa_cipher_key_len(conf->group_mgmt_cipher);
4073 		gsm = wpa_auth->group;
4074 	}
4075 
4076 	if (!sm->wpa_auth->conf.beacon_prot)
4077 		return pos;
4078 
4079 	bigtk.keyid[0] = gsm->GN_bigtk;
4080 	bigtk.keyid[1] = 0;
4081 	if (gsm->wpa_group_state != WPA_GROUP_SETKEYSDONE ||
4082 	    wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN_bigtk, rsc) < 0)
4083 		os_memset(bigtk.pn, 0, sizeof(bigtk.pn));
4084 	else
4085 		os_memcpy(bigtk.pn, rsc, sizeof(bigtk.pn));
4086 	os_memcpy(bigtk.bigtk, gsm->BIGTK[gsm->GN_bigtk - 6], len);
4087 	if (sm->wpa_key_mgmt == WPA_KEY_MGMT_OSEN) {
4088 		/*
4089 		 * Provide unique random BIGTK to each OSEN STA to prevent use
4090 		 * of BIGTK in the BSS.
4091 		 */
4092 		if (random_get_bytes(bigtk.bigtk, len) < 0)
4093 			return pos;
4094 	}
4095 	pos = wpa_add_kde(pos, RSN_KEY_DATA_BIGTK,
4096 			  (const u8 *) &bigtk, WPA_BIGTK_KDE_PREFIX_LEN + len,
4097 			  NULL, 0);
4098 	forced_memzero(&bigtk, sizeof(bigtk));
4099 
4100 	return pos;
4101 }
4102 
4103 
4104 static int ocv_oci_len(struct wpa_state_machine *sm)
4105 {
4106 #ifdef CONFIG_OCV
4107 	if (wpa_auth_uses_ocv(sm))
4108 		return OCV_OCI_KDE_LEN;
4109 #endif /* CONFIG_OCV */
4110 	return 0;
4111 }
4112 
4113 
4114 static int ocv_oci_add(struct wpa_state_machine *sm, u8 **argpos,
4115 		       unsigned int freq)
4116 {
4117 #ifdef CONFIG_OCV
4118 	struct wpa_channel_info ci;
4119 
4120 	if (!wpa_auth_uses_ocv(sm))
4121 		return 0;
4122 
4123 	if (wpa_channel_info(sm->wpa_auth, &ci) != 0) {
4124 		wpa_printf(MSG_WARNING,
4125 			   "Failed to get channel info for OCI element");
4126 		return -1;
4127 	}
4128 #ifdef CONFIG_TESTING_OPTIONS
4129 	if (freq) {
4130 		wpa_printf(MSG_INFO,
4131 			   "TEST: Override OCI KDE frequency %d -> %u MHz",
4132 			   ci.frequency, freq);
4133 		ci.frequency = freq;
4134 	}
4135 #endif /* CONFIG_TESTING_OPTIONS */
4136 
4137 	return ocv_insert_oci_kde(&ci, argpos);
4138 #else /* CONFIG_OCV */
4139 	return 0;
4140 #endif /* CONFIG_OCV */
4141 }
4142 
4143 
4144 #ifdef CONFIG_TESTING_OPTIONS
4145 static u8 * replace_ie(const char *name, const u8 *old_buf, size_t *len, u8 eid,
4146 		       const u8 *ie, size_t ie_len)
4147 {
4148 	const u8 *elem;
4149 	u8 *buf;
4150 
4151 	wpa_printf(MSG_DEBUG, "TESTING: %s EAPOL override", name);
4152 	wpa_hexdump(MSG_DEBUG, "TESTING: wpa_ie before override",
4153 		    old_buf, *len);
4154 	buf = os_malloc(*len + ie_len);
4155 	if (!buf)
4156 		return NULL;
4157 	os_memcpy(buf, old_buf, *len);
4158 	elem = get_ie(buf, *len, eid);
4159 	if (elem) {
4160 		u8 elem_len = 2 + elem[1];
4161 
4162 		os_memmove((void *) elem, elem + elem_len,
4163 			   *len - (elem - buf) - elem_len);
4164 		*len -= elem_len;
4165 	}
4166 	os_memcpy(buf + *len, ie, ie_len);
4167 	*len += ie_len;
4168 	wpa_hexdump(MSG_DEBUG, "TESTING: wpa_ie after EAPOL override",
4169 		    buf, *len);
4170 
4171 	return buf;
4172 }
4173 #endif /* CONFIG_TESTING_OPTIONS */
4174 
4175 
4176 #ifdef CONFIG_IEEE80211BE
4177 
4178 void wpa_auth_ml_get_key_info(struct wpa_authenticator *a,
4179 			      struct wpa_auth_ml_link_key_info *info,
4180 			      bool mgmt_frame_prot, bool beacon_prot)
4181 {
4182 	struct wpa_group *gsm = a->group;
4183 	u8 rsc[WPA_KEY_RSC_LEN];
4184 
4185 	wpa_printf(MSG_DEBUG,
4186 		   "MLD: Get group key info: link_id=%u, IGTK=%u, BIGTK=%u",
4187 		   info->link_id, mgmt_frame_prot, beacon_prot);
4188 
4189 	info->gtkidx = gsm->GN & 0x03;
4190 	info->gtk = gsm->GTK[gsm->GN - 1];
4191 	info->gtk_len = gsm->GTK_len;
4192 
4193 	if (wpa_auth_get_seqnum(a, NULL, gsm->GN, rsc) < 0)
4194 		os_memset(info->pn, 0, sizeof(info->pn));
4195 	else
4196 		os_memcpy(info->pn, rsc, sizeof(info->pn));
4197 
4198 	if (!mgmt_frame_prot)
4199 		return;
4200 
4201 	info->igtkidx = gsm->GN_igtk;
4202 	info->igtk = gsm->IGTK[gsm->GN_igtk - 4];
4203 	info->igtk_len = wpa_cipher_key_len(a->conf.group_mgmt_cipher);
4204 
4205 	if (wpa_auth_get_seqnum(a, NULL, gsm->GN_igtk, rsc) < 0)
4206 		os_memset(info->ipn, 0, sizeof(info->ipn));
4207 	else
4208 		os_memcpy(info->ipn, rsc, sizeof(info->ipn));
4209 
4210 	if (!beacon_prot)
4211 		return;
4212 
4213 	if (a->conf.tx_bss_auth) {
4214 		a = a->conf.tx_bss_auth;
4215 		gsm = a->group;
4216 	}
4217 
4218 	info->bigtkidx = gsm->GN_bigtk;
4219 	info->bigtk = gsm->BIGTK[gsm->GN_bigtk - 6];
4220 
4221 	if (wpa_auth_get_seqnum(a, NULL, gsm->GN_bigtk, rsc) < 0)
4222 		os_memset(info->bipn, 0, sizeof(info->bipn));
4223 	else
4224 		os_memcpy(info->bipn, rsc, sizeof(info->bipn));
4225 }
4226 
4227 
4228 static void wpa_auth_get_ml_key_info(struct wpa_authenticator *wpa_auth,
4229 				     struct wpa_auth_ml_key_info *info)
4230 {
4231 	if (!wpa_auth->cb->get_ml_key_info)
4232 		return;
4233 
4234 	wpa_auth->cb->get_ml_key_info(wpa_auth->cb_ctx, info);
4235 }
4236 
4237 
4238 static size_t wpa_auth_ml_group_kdes_len(struct wpa_state_machine *sm)
4239 {
4240 	struct wpa_authenticator *wpa_auth;
4241 	size_t kde_len = 0;
4242 	int link_id;
4243 
4244 	if (sm->mld_assoc_link_id < 0)
4245 		return 0;
4246 
4247 	for (link_id = 0; link_id < MAX_NUM_MLD_LINKS; link_id++) {
4248 		if (!sm->mld_links[link_id].valid)
4249 			continue;
4250 
4251 		wpa_auth = sm->mld_links[link_id].wpa_auth;
4252 		if (!wpa_auth || !wpa_auth->group)
4253 			continue;
4254 
4255 		/* MLO GTK KDE
4256 		 * Header + Key ID + Tx + LinkID + PN + GTK */
4257 		kde_len += KDE_HDR_LEN + 1 + RSN_PN_LEN;
4258 		kde_len += wpa_auth->group->GTK_len;
4259 
4260 		if (!sm->mgmt_frame_prot)
4261 			continue;
4262 
4263 		if (wpa_auth->conf.tx_bss_auth)
4264 			wpa_auth = wpa_auth->conf.tx_bss_auth;
4265 
4266 		/* MLO IGTK KDE
4267 		 * Header + Key ID + IPN + LinkID + IGTK */
4268 		kde_len += KDE_HDR_LEN + WPA_IGTK_KDE_PREFIX_LEN + 1;
4269 		kde_len += wpa_cipher_key_len(wpa_auth->conf.group_mgmt_cipher);
4270 
4271 		if (!wpa_auth->conf.beacon_prot)
4272 			continue;
4273 
4274 		/* MLO BIGTK KDE
4275 		 * Header + Key ID + BIPN + LinkID + BIGTK */
4276 		kde_len += KDE_HDR_LEN + WPA_BIGTK_KDE_PREFIX_LEN + 1;
4277 		kde_len += wpa_cipher_key_len(wpa_auth->conf.group_mgmt_cipher);
4278 	}
4279 
4280 	wpa_printf(MSG_DEBUG, "MLO Group KDEs len = %zu", kde_len);
4281 
4282 	return kde_len;
4283 }
4284 
4285 
4286 static u8 * wpa_auth_ml_group_kdes(struct wpa_state_machine *sm, u8 *pos)
4287 {
4288 	struct wpa_auth_ml_key_info ml_key_info;
4289 	unsigned int i, link_id;
4290 	u8 *start = pos;
4291 
4292 	/* First fetch the key information from all the authenticators */
4293 	os_memset(&ml_key_info, 0, sizeof(ml_key_info));
4294 	ml_key_info.n_mld_links = sm->n_mld_affiliated_links + 1;
4295 
4296 	/*
4297 	 * Assume that management frame protection and beacon protection are the
4298 	 * same on all links.
4299 	 */
4300 	ml_key_info.mgmt_frame_prot = sm->mgmt_frame_prot;
4301 	ml_key_info.beacon_prot = sm->wpa_auth->conf.beacon_prot;
4302 
4303 	for (i = 0, link_id = 0; link_id < MAX_NUM_MLD_LINKS; link_id++) {
4304 		if (!sm->mld_links[link_id].valid)
4305 			continue;
4306 
4307 		ml_key_info.links[i++].link_id = link_id;
4308 	}
4309 
4310 	wpa_auth_get_ml_key_info(sm->wpa_auth, &ml_key_info);
4311 
4312 	/* Add MLO GTK KDEs */
4313 	for (i = 0, link_id = 0; link_id < MAX_NUM_MLD_LINKS; link_id++) {
4314 		if (!sm->mld_links[link_id].valid ||
4315 		    !ml_key_info.links[i].gtk_len)
4316 			continue;
4317 
4318 		wpa_printf(MSG_DEBUG, "RSN: MLO GTK: link=%u", link_id);
4319 		wpa_hexdump_key(MSG_DEBUG, "RSN: MLO GTK",
4320 				ml_key_info.links[i].gtk,
4321 				ml_key_info.links[i].gtk_len);
4322 
4323 		*pos++ = WLAN_EID_VENDOR_SPECIFIC;
4324 		*pos++ = RSN_SELECTOR_LEN + 1 + 6 +
4325 			ml_key_info.links[i].gtk_len;
4326 
4327 		RSN_SELECTOR_PUT(pos, RSN_KEY_DATA_MLO_GTK);
4328 		pos += RSN_SELECTOR_LEN;
4329 
4330 		*pos++ = (ml_key_info.links[i].gtkidx & 0x3) | (link_id << 4);
4331 
4332 		os_memcpy(pos, ml_key_info.links[i].pn, 6);
4333 		pos += 6;
4334 
4335 		os_memcpy(pos, ml_key_info.links[i].gtk,
4336 			  ml_key_info.links[i].gtk_len);
4337 		pos += ml_key_info.links[i].gtk_len;
4338 
4339 		i++;
4340 	}
4341 
4342 	if (!sm->mgmt_frame_prot) {
4343 		wpa_printf(MSG_DEBUG, "RSN: MLO Group KDE len = %ld",
4344 			   pos - start);
4345 		return pos;
4346 	}
4347 
4348 	/* Add MLO IGTK KDEs */
4349 	for (i = 0, link_id = 0; link_id < MAX_NUM_MLD_LINKS; link_id++) {
4350 		if (!sm->mld_links[link_id].valid ||
4351 		    !ml_key_info.links[i].igtk_len)
4352 			continue;
4353 
4354 		wpa_printf(MSG_DEBUG, "RSN: MLO IGTK: link=%u", link_id);
4355 		wpa_hexdump_key(MSG_DEBUG, "RSN: MLO IGTK",
4356 				ml_key_info.links[i].igtk,
4357 				ml_key_info.links[i].igtk_len);
4358 
4359 		*pos++ = WLAN_EID_VENDOR_SPECIFIC;
4360 		*pos++ = RSN_SELECTOR_LEN + 2 + 1 +
4361 			sizeof(ml_key_info.links[i].ipn) +
4362 			ml_key_info.links[i].igtk_len;
4363 
4364 		RSN_SELECTOR_PUT(pos, RSN_KEY_DATA_MLO_IGTK);
4365 		pos += RSN_SELECTOR_LEN;
4366 
4367 		/* Add the Key ID */
4368 		*pos++ = ml_key_info.links[i].igtkidx;
4369 		*pos++ = 0;
4370 
4371 		/* Add the IPN */
4372 		os_memcpy(pos, ml_key_info.links[i].ipn,
4373 			  sizeof(ml_key_info.links[i].ipn));
4374 		pos += sizeof(ml_key_info.links[i].ipn);
4375 
4376 		*pos++ = ml_key_info.links[i].link_id << 4;
4377 
4378 		os_memcpy(pos, ml_key_info.links[i].igtk,
4379 			  ml_key_info.links[i].igtk_len);
4380 		pos += ml_key_info.links[i].igtk_len;
4381 
4382 		i++;
4383 	}
4384 
4385 	if (!sm->wpa_auth->conf.beacon_prot) {
4386 		wpa_printf(MSG_DEBUG, "RSN: MLO Group KDE len = %ld",
4387 			   pos - start);
4388 		return pos;
4389 	}
4390 
4391 	/* Add MLO BIGTK KDEs */
4392 	for (i = 0, link_id = 0; link_id < MAX_NUM_MLD_LINKS; link_id++) {
4393 		if (!sm->mld_links[link_id].valid ||
4394 		    !ml_key_info.links[i].bigtk ||
4395 		    !ml_key_info.links[i].igtk_len)
4396 			continue;
4397 
4398 		wpa_printf(MSG_DEBUG, "RSN: MLO BIGTK: link=%u", link_id);
4399 		wpa_hexdump_key(MSG_DEBUG, "RSN: MLO BIGTK",
4400 				ml_key_info.links[i].bigtk,
4401 				ml_key_info.links[i].igtk_len);
4402 
4403 		*pos++ = WLAN_EID_VENDOR_SPECIFIC;
4404 		*pos++ = RSN_SELECTOR_LEN + 2 + 1 +
4405 			sizeof(ml_key_info.links[i].bipn) +
4406 			ml_key_info.links[i].igtk_len;
4407 
4408 		RSN_SELECTOR_PUT(pos, RSN_KEY_DATA_MLO_BIGTK);
4409 		pos += RSN_SELECTOR_LEN;
4410 
4411 		/* Add the Key ID */
4412 		*pos++ = ml_key_info.links[i].bigtkidx;
4413 		*pos++ = 0;
4414 
4415 		/* Add the BIPN */
4416 		os_memcpy(pos, ml_key_info.links[i].bipn,
4417 			  sizeof(ml_key_info.links[i].bipn));
4418 		pos += sizeof(ml_key_info.links[i].bipn);
4419 
4420 		*pos++ = ml_key_info.links[i].link_id << 4;
4421 
4422 		os_memcpy(pos, ml_key_info.links[i].bigtk,
4423 			  ml_key_info.links[i].igtk_len);
4424 		pos += ml_key_info.links[i].igtk_len;
4425 
4426 		i++;
4427 	}
4428 
4429 	wpa_printf(MSG_DEBUG, "RSN: MLO Group KDE len = %ld", pos - start);
4430 	return pos;
4431 }
4432 
4433 #endif /* CONFIG_IEEE80211BE */
4434 
4435 
4436 static size_t wpa_auth_ml_kdes_len(struct wpa_state_machine *sm)
4437 {
4438 	size_t kde_len = 0;
4439 
4440 #ifdef CONFIG_IEEE80211BE
4441 	unsigned int link_id;
4442 
4443 	if (sm->mld_assoc_link_id < 0)
4444 		return 0;
4445 
4446 	/* For the MAC Address KDE */
4447 	kde_len = 2 + RSN_SELECTOR_LEN + ETH_ALEN;
4448 
4449 	/* MLO Link KDE for each link */
4450 	for (link_id = 0; link_id < MAX_NUM_MLD_LINKS; link_id++) {
4451 		struct wpa_authenticator *wpa_auth;
4452 		const u8 *ie;
4453 
4454 		wpa_auth = wpa_get_link_auth(sm->wpa_auth, link_id);
4455 		if (!wpa_auth)
4456 			continue;
4457 
4458 		kde_len += 2 + RSN_SELECTOR_LEN + 1 + ETH_ALEN;
4459 		ie = get_ie(wpa_auth->wpa_ie, wpa_auth->wpa_ie_len,
4460 			    WLAN_EID_RSN);
4461 		if (ie)
4462 			kde_len += 2 + ie[1];
4463 		ie = get_ie(wpa_auth->wpa_ie, wpa_auth->wpa_ie_len,
4464 			    WLAN_EID_RSNX);
4465 		if (ie)
4466 			kde_len += 2 + ie[1];
4467 	}
4468 
4469 	kde_len += wpa_auth_ml_group_kdes_len(sm);
4470 #endif /* CONFIG_IEEE80211BE */
4471 
4472 	return kde_len;
4473 }
4474 
4475 
4476 static u8 * wpa_auth_ml_kdes(struct wpa_state_machine *sm, u8 *pos)
4477 {
4478 #ifdef CONFIG_IEEE80211BE
4479 	u8 link_id;
4480 	u8 *start = pos;
4481 
4482 	if (sm->mld_assoc_link_id < 0)
4483 		return pos;
4484 
4485 	wpa_printf(MSG_DEBUG, "RSN: MLD: Adding MAC Address KDE");
4486 	pos = wpa_add_kde(pos, RSN_KEY_DATA_MAC_ADDR,
4487 			  sm->wpa_auth->mld_addr, ETH_ALEN, NULL, 0);
4488 
4489 	for (link_id = 0; link_id < MAX_NUM_MLD_LINKS; link_id++) {
4490 		struct wpa_authenticator *wpa_auth;
4491 		const u8 *rsne, *rsnxe;
4492 		size_t rsne_len, rsnxe_len;
4493 
4494 		wpa_auth = wpa_get_link_auth(sm->wpa_auth, link_id);
4495 		if (!wpa_auth)
4496 			continue;
4497 
4498 		rsne = get_ie(wpa_auth->wpa_ie, wpa_auth->wpa_ie_len,
4499 			     WLAN_EID_RSN);
4500 		rsne_len = rsne ? 2 + rsne[1] : 0;
4501 
4502 		rsnxe = get_ie(wpa_auth->wpa_ie, wpa_auth->wpa_ie_len,
4503 			       WLAN_EID_RSNX);
4504 		rsnxe_len = rsnxe ? 2 + rsnxe[1] : 0;
4505 
4506 		wpa_printf(MSG_DEBUG,
4507 			   "RSN: MLO Link: link=%u, len=%zu", link_id,
4508 			   RSN_SELECTOR_LEN + 1 + ETH_ALEN +
4509 			   rsne_len + rsnxe_len);
4510 
4511 		*pos++ = WLAN_EID_VENDOR_SPECIFIC;
4512 		*pos++ = RSN_SELECTOR_LEN + 1 + ETH_ALEN +
4513 			rsne_len + rsnxe_len;
4514 
4515 		RSN_SELECTOR_PUT(pos, RSN_KEY_DATA_MLO_LINK);
4516 		pos += RSN_SELECTOR_LEN;
4517 
4518 		/* Add the Link Information */
4519 		*pos = link_id;
4520 		if (rsne_len)
4521 			*pos |= RSN_MLO_LINK_KDE_LI_RSNE_INFO;
4522 		if (rsnxe_len)
4523 			*pos |= RSN_MLO_LINK_KDE_LI_RSNXE_INFO;
4524 
4525 		pos++;
4526 		os_memcpy(pos, wpa_auth->addr, ETH_ALEN);
4527 		pos += ETH_ALEN;
4528 
4529 		if (rsne_len) {
4530 			os_memcpy(pos, rsne, rsne_len);
4531 			pos += rsne_len;
4532 		}
4533 
4534 		if (rsnxe_len) {
4535 			os_memcpy(pos, rsnxe, rsnxe_len);
4536 			pos += rsnxe_len;
4537 		}
4538 	}
4539 
4540 	wpa_printf(MSG_DEBUG, "RSN: MLO Link KDE len = %ld", pos - start);
4541 	pos = wpa_auth_ml_group_kdes(sm, pos);
4542 #endif /* CONFIG_IEEE80211BE */
4543 
4544 	return pos;
4545 }
4546 
4547 
4548 SM_STATE(WPA_PTK, PTKINITNEGOTIATING)
4549 {
4550 	u8 rsc[WPA_KEY_RSC_LEN], *_rsc, *gtk, *kde = NULL, *pos, stub_gtk[32];
4551 	size_t gtk_len, kde_len = 0, wpa_ie_len;
4552 	struct wpa_group *gsm = sm->group;
4553 	u8 *wpa_ie;
4554 	int secure, gtkidx, encr = 0;
4555 	u8 *wpa_ie_buf = NULL, *wpa_ie_buf2 = NULL;
4556 	u8 hdr[2];
4557 	struct wpa_auth_config *conf = &sm->wpa_auth->conf;
4558 #ifdef CONFIG_IEEE80211BE
4559 	bool is_mld = sm->mld_assoc_link_id >= 0;
4560 #else /* CONFIG_IEEE80211BE */
4561 	bool is_mld = false;
4562 #endif /* CONFIG_IEEE80211BE */
4563 
4564 	SM_ENTRY_MA(WPA_PTK, PTKINITNEGOTIATING, wpa_ptk);
4565 	sm->TimeoutEvt = false;
4566 
4567 	sm->TimeoutCtr++;
4568 	if (conf->wpa_disable_eapol_key_retries && sm->TimeoutCtr > 1) {
4569 		/* Do not allow retransmission of EAPOL-Key msg 3/4 */
4570 		return;
4571 	}
4572 	if (sm->TimeoutCtr > conf->wpa_pairwise_update_count) {
4573 		/* No point in sending the EAPOL-Key - we will disconnect
4574 		 * immediately following this. */
4575 		return;
4576 	}
4577 
4578 	/* Send EAPOL(1, 1, 1, Pair, P, RSC, ANonce, MIC(PTK), RSNIE, [MDIE],
4579 	   GTK[GN], IGTK, [BIGTK], [FTIE], [TIE * 2])
4580 	 */
4581 	os_memset(rsc, 0, WPA_KEY_RSC_LEN);
4582 	wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN, rsc);
4583 	/* If FT is used, wpa_auth->wpa_ie includes both RSNIE and MDIE */
4584 	wpa_ie = sm->wpa_auth->wpa_ie;
4585 	wpa_ie_len = sm->wpa_auth->wpa_ie_len;
4586 	if (sm->wpa == WPA_VERSION_WPA && (conf->wpa & WPA_PROTO_RSN) &&
4587 	    wpa_ie_len > wpa_ie[1] + 2U && wpa_ie[0] == WLAN_EID_RSN) {
4588 		/* WPA-only STA, remove RSN IE and possible MDIE */
4589 		wpa_ie = wpa_ie + wpa_ie[1] + 2;
4590 		if (wpa_ie[0] == WLAN_EID_RSNX)
4591 			wpa_ie = wpa_ie + wpa_ie[1] + 2;
4592 		if (wpa_ie[0] == WLAN_EID_MOBILITY_DOMAIN)
4593 			wpa_ie = wpa_ie + wpa_ie[1] + 2;
4594 		wpa_ie_len = wpa_ie[1] + 2;
4595 	}
4596 #ifdef CONFIG_TESTING_OPTIONS
4597 	if (conf->rsne_override_eapol_set) {
4598 		wpa_ie_buf2 = replace_ie(
4599 			"RSNE", wpa_ie, &wpa_ie_len, WLAN_EID_RSN,
4600 			conf->rsne_override_eapol,
4601 			conf->rsne_override_eapol_len);
4602 		if (!wpa_ie_buf2)
4603 			goto done;
4604 		wpa_ie = wpa_ie_buf2;
4605 	}
4606 	if (conf->rsnxe_override_eapol_set) {
4607 		wpa_ie_buf = replace_ie(
4608 			"RSNXE", wpa_ie, &wpa_ie_len, WLAN_EID_RSNX,
4609 			conf->rsnxe_override_eapol,
4610 			conf->rsnxe_override_eapol_len);
4611 		if (!wpa_ie_buf)
4612 			goto done;
4613 		wpa_ie = wpa_ie_buf;
4614 	}
4615 #endif /* CONFIG_TESTING_OPTIONS */
4616 	wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
4617 			"sending 3/4 msg of 4-Way Handshake");
4618 	if (sm->wpa == WPA_VERSION_WPA2) {
4619 		if (sm->use_ext_key_id && sm->TimeoutCtr == 1 &&
4620 		    wpa_auth_set_key(sm->wpa_auth, 0,
4621 				     wpa_cipher_to_alg(sm->pairwise),
4622 				     sm->addr,
4623 				     sm->keyidx_active, sm->PTK.tk,
4624 				     wpa_cipher_key_len(sm->pairwise),
4625 				     KEY_FLAG_PAIRWISE_RX)) {
4626 			wpa_sta_disconnect(sm->wpa_auth, sm->addr,
4627 					   WLAN_REASON_PREV_AUTH_NOT_VALID);
4628 			return;
4629 		}
4630 
4631 #ifdef CONFIG_PASN
4632 		if (sm->wpa_auth->conf.secure_ltf &&
4633 		    ieee802_11_rsnx_capab(sm->rsnxe,
4634 					  WLAN_RSNX_CAPAB_SECURE_LTF) &&
4635 		    wpa_auth_set_ltf_keyseed(sm->wpa_auth, sm->addr,
4636 					     sm->PTK.ltf_keyseed,
4637 					     sm->PTK.ltf_keyseed_len)) {
4638 			wpa_printf(MSG_ERROR,
4639 				   "WPA: Failed to set LTF keyseed to driver");
4640 			wpa_sta_disconnect(sm->wpa_auth, sm->addr,
4641 					   WLAN_REASON_PREV_AUTH_NOT_VALID);
4642 			return;
4643 		}
4644 #endif /* CONFIG_PASN */
4645 
4646 		/* WPA2 send GTK in the 4-way handshake */
4647 		secure = 1;
4648 		gtk = gsm->GTK[gsm->GN - 1];
4649 		gtk_len = gsm->GTK_len;
4650 		if (conf->disable_gtk ||
4651 		    sm->wpa_key_mgmt == WPA_KEY_MGMT_OSEN) {
4652 			/*
4653 			 * Provide unique random GTK to each STA to prevent use
4654 			 * of GTK in the BSS.
4655 			 */
4656 			if (random_get_bytes(stub_gtk, gtk_len) < 0)
4657 				goto done;
4658 			gtk = stub_gtk;
4659 		}
4660 		gtkidx = gsm->GN;
4661 		_rsc = rsc;
4662 		encr = 1;
4663 	} else {
4664 		/* WPA does not include GTK in msg 3/4 */
4665 		secure = 0;
4666 		gtk = NULL;
4667 		gtk_len = 0;
4668 		gtkidx = 0;
4669 		_rsc = NULL;
4670 		if (sm->rx_eapol_key_secure) {
4671 			/*
4672 			 * It looks like Windows 7 supplicant tries to use
4673 			 * Secure bit in msg 2/4 after having reported Michael
4674 			 * MIC failure and it then rejects the 4-way handshake
4675 			 * if msg 3/4 does not set Secure bit. Work around this
4676 			 * by setting the Secure bit here even in the case of
4677 			 * WPA if the supplicant used it first.
4678 			 */
4679 			wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm),
4680 					LOGGER_DEBUG,
4681 					"STA used Secure bit in WPA msg 2/4 - set Secure for 3/4 as workaround");
4682 			secure = 1;
4683 		}
4684 	}
4685 
4686 	kde_len = wpa_ie_len + ieee80211w_kde_len(sm) + ocv_oci_len(sm);
4687 
4688 	if (sm->use_ext_key_id)
4689 		kde_len += 2 + RSN_SELECTOR_LEN + 2;
4690 
4691 	if (gtk)
4692 		kde_len += 2 + RSN_SELECTOR_LEN + 2 + gtk_len;
4693 #ifdef CONFIG_IEEE80211R_AP
4694 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
4695 		kde_len += 2 + PMKID_LEN; /* PMKR1Name into RSN IE */
4696 		kde_len += 300; /* FTIE + 2 * TIE */
4697 	}
4698 #endif /* CONFIG_IEEE80211R_AP */
4699 #ifdef CONFIG_P2P
4700 	if (WPA_GET_BE32(sm->ip_addr) > 0)
4701 		kde_len += 2 + RSN_SELECTOR_LEN + 3 * 4;
4702 #endif /* CONFIG_P2P */
4703 
4704 	if (conf->transition_disable)
4705 		kde_len += 2 + RSN_SELECTOR_LEN + 1;
4706 
4707 #ifdef CONFIG_DPP2
4708 	if (sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP)
4709 		kde_len += 2 + RSN_SELECTOR_LEN + 2;
4710 #endif /* CONFIG_DPP2 */
4711 
4712 	kde_len += wpa_auth_ml_kdes_len(sm);
4713 
4714 	if (sm->ssid_protection)
4715 		kde_len += 2 + conf->ssid_len;
4716 
4717 #ifdef CONFIG_TESTING_OPTIONS
4718 	if (conf->eapol_m3_elements)
4719 		kde_len += wpabuf_len(conf->eapol_m3_elements);
4720 #endif /* CONFIG_TESTING_OPTIONS */
4721 
4722 	kde = os_malloc(kde_len);
4723 	if (!kde)
4724 		goto done;
4725 
4726 	pos = kde;
4727 	if (!is_mld) {
4728 		os_memcpy(pos, wpa_ie, wpa_ie_len);
4729 		pos += wpa_ie_len;
4730 	}
4731 #ifdef CONFIG_IEEE80211R_AP
4732 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
4733 		int res;
4734 		size_t elen;
4735 
4736 		elen = pos - kde;
4737 		res = wpa_insert_pmkid(kde, &elen, sm->pmk_r1_name, true);
4738 		if (res < 0) {
4739 			wpa_printf(MSG_ERROR,
4740 				   "FT: Failed to insert PMKR1Name into RSN IE in EAPOL-Key data");
4741 			goto done;
4742 		}
4743 		pos -= wpa_ie_len;
4744 		pos += elen;
4745 	}
4746 #endif /* CONFIG_IEEE80211R_AP */
4747 	hdr[1] = 0;
4748 
4749 	if (sm->use_ext_key_id) {
4750 		hdr[0] = sm->keyidx_active & 0x01;
4751 		pos = wpa_add_kde(pos, RSN_KEY_DATA_KEYID, hdr, 2, NULL, 0);
4752 	}
4753 
4754 	if (gtk && !is_mld) {
4755 		hdr[0] = gtkidx & 0x03;
4756 		pos = wpa_add_kde(pos, RSN_KEY_DATA_GROUPKEY, hdr, 2,
4757 				  gtk, gtk_len);
4758 	}
4759 	pos = ieee80211w_kde_add(sm, pos);
4760 	if (ocv_oci_add(sm, &pos, conf->oci_freq_override_eapol_m3) < 0)
4761 		goto done;
4762 
4763 #ifdef CONFIG_IEEE80211R_AP
4764 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
4765 		int res;
4766 
4767 		if (sm->assoc_resp_ftie &&
4768 		    kde + kde_len - pos >= 2 + sm->assoc_resp_ftie[1]) {
4769 			os_memcpy(pos, sm->assoc_resp_ftie,
4770 				  2 + sm->assoc_resp_ftie[1]);
4771 			res = 2 + sm->assoc_resp_ftie[1];
4772 		} else {
4773 			res = wpa_write_ftie(conf, sm->wpa_key_mgmt,
4774 					     sm->xxkey_len,
4775 					     conf->r0_key_holder,
4776 					     conf->r0_key_holder_len,
4777 					     NULL, NULL, pos,
4778 					     kde + kde_len - pos,
4779 					     NULL, 0, 0);
4780 		}
4781 		if (res < 0) {
4782 			wpa_printf(MSG_ERROR,
4783 				   "FT: Failed to insert FTIE into EAPOL-Key Key Data");
4784 			goto done;
4785 		}
4786 		pos += res;
4787 
4788 		/* TIE[ReassociationDeadline] (TU) */
4789 		*pos++ = WLAN_EID_TIMEOUT_INTERVAL;
4790 		*pos++ = 5;
4791 		*pos++ = WLAN_TIMEOUT_REASSOC_DEADLINE;
4792 		WPA_PUT_LE32(pos, conf->reassociation_deadline);
4793 		pos += 4;
4794 
4795 		/* TIE[KeyLifetime] (seconds) */
4796 		*pos++ = WLAN_EID_TIMEOUT_INTERVAL;
4797 		*pos++ = 5;
4798 		*pos++ = WLAN_TIMEOUT_KEY_LIFETIME;
4799 		WPA_PUT_LE32(pos, conf->r0_key_lifetime);
4800 		pos += 4;
4801 	}
4802 #endif /* CONFIG_IEEE80211R_AP */
4803 #ifdef CONFIG_P2P
4804 	if (WPA_GET_BE32(sm->ip_addr) > 0) {
4805 		u8 addr[3 * 4];
4806 		os_memcpy(addr, sm->ip_addr, 4);
4807 		os_memcpy(addr + 4, conf->ip_addr_mask, 4);
4808 		os_memcpy(addr + 8, conf->ip_addr_go, 4);
4809 		pos = wpa_add_kde(pos, WFA_KEY_DATA_IP_ADDR_ALLOC,
4810 				  addr, sizeof(addr), NULL, 0);
4811 	}
4812 #endif /* CONFIG_P2P */
4813 
4814 	if (conf->transition_disable)
4815 		pos = wpa_add_kde(pos, WFA_KEY_DATA_TRANSITION_DISABLE,
4816 				  &conf->transition_disable, 1, NULL, 0);
4817 
4818 #ifdef CONFIG_DPP2
4819 	if (DPP_VERSION > 1 && sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP) {
4820 		u8 payload[2];
4821 
4822 		payload[0] = DPP_VERSION; /* Protocol Version */
4823 		payload[1] = 0; /* Flags */
4824 		if (conf->dpp_pfs == 0)
4825 			payload[1] |= DPP_KDE_PFS_ALLOWED;
4826 		else if (conf->dpp_pfs == 1)
4827 			payload[1] |= DPP_KDE_PFS_ALLOWED |
4828 				DPP_KDE_PFS_REQUIRED;
4829 		pos = wpa_add_kde(pos, WFA_KEY_DATA_DPP,
4830 				  payload, sizeof(payload), NULL, 0);
4831 	}
4832 #endif /* CONFIG_DPP2 */
4833 
4834 	pos = wpa_auth_ml_kdes(sm, pos);
4835 
4836 	if (sm->ssid_protection) {
4837 		*pos++ = WLAN_EID_SSID;
4838 		*pos++ = conf->ssid_len;
4839 		os_memcpy(pos, conf->ssid, conf->ssid_len);
4840 		pos += conf->ssid_len;
4841 	}
4842 
4843 #ifdef CONFIG_TESTING_OPTIONS
4844 	if (conf->eapol_m3_elements) {
4845 		os_memcpy(pos, wpabuf_head(conf->eapol_m3_elements),
4846 			  wpabuf_len(conf->eapol_m3_elements));
4847 		pos += wpabuf_len(conf->eapol_m3_elements);
4848 	}
4849 
4850 	if (conf->eapol_m3_no_encrypt)
4851 		encr = 0;
4852 #endif /* CONFIG_TESTING_OPTIONS */
4853 
4854 	wpa_send_eapol(sm->wpa_auth, sm,
4855 		       (secure ? WPA_KEY_INFO_SECURE : 0) |
4856 		       (wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len) ?
4857 			WPA_KEY_INFO_MIC : 0) |
4858 		       WPA_KEY_INFO_ACK | WPA_KEY_INFO_INSTALL |
4859 		       WPA_KEY_INFO_KEY_TYPE,
4860 		       _rsc, sm->ANonce, kde, pos - kde, 0, encr);
4861 done:
4862 	bin_clear_free(kde, kde_len);
4863 	os_free(wpa_ie_buf);
4864 	os_free(wpa_ie_buf2);
4865 }
4866 
4867 
4868 static int wpa_auth_validate_ml_kdes_m4(struct wpa_state_machine *sm)
4869 {
4870 #ifdef CONFIG_IEEE80211BE
4871 	const struct ieee802_1x_hdr *hdr;
4872 	const struct wpa_eapol_key *key;
4873 	struct wpa_eapol_ie_parse kde;
4874 	const u8 *key_data, *mic;
4875 	u16 key_data_length;
4876 	size_t mic_len;
4877 
4878 	if (sm->mld_assoc_link_id < 0)
4879 		return 0;
4880 
4881 	/*
4882 	 * Note: last_rx_eapol_key length fields have already been validated in
4883 	 * wpa_receive().
4884 	 */
4885 	mic_len = wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len);
4886 
4887 	hdr = (const struct ieee802_1x_hdr *) sm->last_rx_eapol_key;
4888 	key = (const struct wpa_eapol_key *) (hdr + 1);
4889 	mic = (const u8 *) (key + 1);
4890 	key_data = mic + mic_len + 2;
4891 	key_data_length = WPA_GET_BE16(mic + mic_len);
4892 	if (key_data_length > sm->last_rx_eapol_key_len - sizeof(*hdr) -
4893 	    sizeof(*key) - mic_len - 2)
4894 		return -1;
4895 
4896 	if (wpa_parse_kde_ies(key_data, key_data_length, &kde) < 0) {
4897 		wpa_auth_vlogger(sm->wpa_auth, wpa_auth_get_spa(sm),
4898 				 LOGGER_INFO,
4899 				 "received EAPOL-Key msg 4/4 with invalid Key Data contents");
4900 		return -1;
4901 	}
4902 
4903 	/* MLD MAC address must be the same */
4904 	if (!kde.mac_addr ||
4905 	    !ether_addr_equal(kde.mac_addr, sm->peer_mld_addr)) {
4906 		wpa_printf(MSG_DEBUG,
4907 			   "MLD: Mismatching or missing MLD address in EAPOL-Key msg 4/4");
4908 		return -1;
4909 	}
4910 
4911 	wpa_printf(MSG_DEBUG, "MLD: MLD address in EAPOL-Key msg 4/4: " MACSTR,
4912 		   MAC2STR(kde.mac_addr));
4913 #endif /* CONFIG_IEEE80211BE */
4914 
4915 	return 0;
4916 }
4917 
4918 
4919 SM_STATE(WPA_PTK, PTKINITDONE)
4920 {
4921 	SM_ENTRY_MA(WPA_PTK, PTKINITDONE, wpa_ptk);
4922 	sm->EAPOLKeyReceived = false;
4923 
4924 	if (wpa_auth_validate_ml_kdes_m4(sm) < 0) {
4925 		wpa_sta_disconnect(sm->wpa_auth, sm->addr,
4926 				   WLAN_REASON_PREV_AUTH_NOT_VALID);
4927 		return;
4928 	}
4929 
4930 	if (sm->Pair) {
4931 		enum wpa_alg alg = wpa_cipher_to_alg(sm->pairwise);
4932 		int klen = wpa_cipher_key_len(sm->pairwise);
4933 		int res;
4934 
4935 		if (sm->use_ext_key_id)
4936 			res = wpa_auth_set_key(sm->wpa_auth, 0, 0, sm->addr,
4937 					       sm->keyidx_active, NULL, 0,
4938 					       KEY_FLAG_PAIRWISE_RX_TX_MODIFY);
4939 		else
4940 			res = wpa_auth_set_key(sm->wpa_auth, 0, alg, sm->addr,
4941 					       0, sm->PTK.tk, klen,
4942 					       KEY_FLAG_PAIRWISE_RX_TX);
4943 		if (res) {
4944 			wpa_sta_disconnect(sm->wpa_auth, sm->addr,
4945 					   WLAN_REASON_PREV_AUTH_NOT_VALID);
4946 			return;
4947 		}
4948 
4949 #ifdef CONFIG_PASN
4950 		if (sm->wpa_auth->conf.secure_ltf &&
4951 		    ieee802_11_rsnx_capab(sm->rsnxe,
4952 					  WLAN_RSNX_CAPAB_SECURE_LTF) &&
4953 		    wpa_auth_set_ltf_keyseed(sm->wpa_auth, sm->addr,
4954 					     sm->PTK.ltf_keyseed,
4955 					     sm->PTK.ltf_keyseed_len)) {
4956 			wpa_printf(MSG_ERROR,
4957 				   "WPA: Failed to set LTF keyseed to driver");
4958 			wpa_sta_disconnect(sm->wpa_auth, sm->addr,
4959 					   WLAN_REASON_PREV_AUTH_NOT_VALID);
4960 			return;
4961 		}
4962 #endif /* CONFIG_PASN */
4963 
4964 		/* FIX: MLME-SetProtection.Request(TA, Tx_Rx) */
4965 		sm->pairwise_set = true;
4966 
4967 		wpa_auth_set_ptk_rekey_timer(sm);
4968 		wpa_auth_store_ptksa(sm->wpa_auth, sm->addr, sm->pairwise,
4969 				     dot11RSNAConfigPMKLifetime, &sm->PTK);
4970 
4971 		if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) ||
4972 		    sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP ||
4973 		    sm->wpa_key_mgmt == WPA_KEY_MGMT_OWE) {
4974 			wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
4975 					   WPA_EAPOL_authorized, 1);
4976 		}
4977 	}
4978 
4979 	if (0 /* IBSS == TRUE */) {
4980 		sm->keycount++;
4981 		if (sm->keycount == 2) {
4982 			wpa_auth_set_eapol(sm->wpa_auth, sm->addr,
4983 					   WPA_EAPOL_portValid, 1);
4984 		}
4985 	} else {
4986 		wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_portValid,
4987 				   1);
4988 	}
4989 	wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyAvailable,
4990 			   false);
4991 	wpa_auth_set_eapol(sm->wpa_auth, sm->addr, WPA_EAPOL_keyDone, true);
4992 	if (sm->wpa == WPA_VERSION_WPA)
4993 		sm->PInitAKeys = true;
4994 	else
4995 		sm->has_GTK = true;
4996 	wpa_auth_vlogger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
4997 			 "pairwise key handshake completed (%s)",
4998 			 sm->wpa == WPA_VERSION_WPA ? "WPA" : "RSN");
4999 	wpa_msg(sm->wpa_auth->conf.msg_ctx, MSG_INFO, "EAPOL-4WAY-HS-COMPLETED "
5000 		MACSTR, MAC2STR(sm->addr));
5001 
5002 #ifdef CONFIG_IEEE80211R_AP
5003 	wpa_ft_push_pmk_r1(sm->wpa_auth, wpa_auth_get_spa(sm));
5004 #endif /* CONFIG_IEEE80211R_AP */
5005 
5006 	sm->ptkstart_without_success = 0;
5007 }
5008 
5009 
5010 SM_STEP(WPA_PTK)
5011 {
5012 	struct wpa_authenticator *wpa_auth = sm->wpa_auth;
5013 	struct wpa_auth_config *conf = &wpa_auth->conf;
5014 
5015 	if (sm->Init)
5016 		SM_ENTER(WPA_PTK, INITIALIZE);
5017 	else if (sm->Disconnect
5018 		 /* || FIX: dot11RSNAConfigSALifetime timeout */) {
5019 		wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
5020 				"WPA_PTK: sm->Disconnect");
5021 		SM_ENTER(WPA_PTK, DISCONNECT);
5022 	}
5023 	else if (sm->DeauthenticationRequest)
5024 		SM_ENTER(WPA_PTK, DISCONNECTED);
5025 	else if (sm->AuthenticationRequest)
5026 		SM_ENTER(WPA_PTK, AUTHENTICATION);
5027 	else if (sm->ReAuthenticationRequest)
5028 		SM_ENTER(WPA_PTK, AUTHENTICATION2);
5029 	else if (sm->PTKRequest) {
5030 		if (wpa_auth_sm_ptk_update(sm) < 0)
5031 			SM_ENTER(WPA_PTK, DISCONNECTED);
5032 		else
5033 			SM_ENTER(WPA_PTK, PTKSTART);
5034 	} else switch (sm->wpa_ptk_state) {
5035 	case WPA_PTK_INITIALIZE:
5036 		break;
5037 	case WPA_PTK_DISCONNECT:
5038 		SM_ENTER(WPA_PTK, DISCONNECTED);
5039 		break;
5040 	case WPA_PTK_DISCONNECTED:
5041 		SM_ENTER(WPA_PTK, INITIALIZE);
5042 		break;
5043 	case WPA_PTK_AUTHENTICATION:
5044 		SM_ENTER(WPA_PTK, AUTHENTICATION2);
5045 		break;
5046 	case WPA_PTK_AUTHENTICATION2:
5047 		if (wpa_key_mgmt_wpa_ieee8021x(sm->wpa_key_mgmt) &&
5048 		    wpa_auth_get_eapol(wpa_auth, sm->addr,
5049 				       WPA_EAPOL_keyRun))
5050 			SM_ENTER(WPA_PTK, INITPMK);
5051 		else if (wpa_key_mgmt_wpa_psk(sm->wpa_key_mgmt) ||
5052 			 sm->wpa_key_mgmt == WPA_KEY_MGMT_OWE
5053 			 /* FIX: && 802.1X::keyRun */)
5054 			SM_ENTER(WPA_PTK, INITPSK);
5055 		else if (sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP)
5056 			SM_ENTER(WPA_PTK, INITPMK);
5057 		break;
5058 	case WPA_PTK_INITPMK:
5059 		if (wpa_auth_get_eapol(wpa_auth, sm->addr,
5060 				       WPA_EAPOL_keyAvailable)) {
5061 			SM_ENTER(WPA_PTK, PTKSTART);
5062 #ifdef CONFIG_DPP
5063 		} else if (sm->wpa_key_mgmt == WPA_KEY_MGMT_DPP && sm->pmksa) {
5064 			SM_ENTER(WPA_PTK, PTKSTART);
5065 #endif /* CONFIG_DPP */
5066 		} else {
5067 			wpa_auth->dot11RSNA4WayHandshakeFailures++;
5068 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
5069 					LOGGER_INFO,
5070 					"INITPMK - keyAvailable = false");
5071 			SM_ENTER(WPA_PTK, DISCONNECT);
5072 		}
5073 		break;
5074 	case WPA_PTK_INITPSK:
5075 		if (wpa_auth_get_psk(wpa_auth, sm->addr, sm->p2p_dev_addr,
5076 				     NULL, NULL, NULL)) {
5077 			SM_ENTER(WPA_PTK, PTKSTART);
5078 #ifdef CONFIG_SAE
5079 		} else if (wpa_auth_uses_sae(sm) && sm->pmksa) {
5080 			SM_ENTER(WPA_PTK, PTKSTART);
5081 #endif /* CONFIG_SAE */
5082 		} else if (wpa_key_mgmt_wpa_psk_no_sae(sm->wpa_key_mgmt) &&
5083 			   wpa_auth->conf.radius_psk) {
5084 			wpa_printf(MSG_DEBUG,
5085 				   "INITPSK: No PSK yet available for STA - use RADIUS later");
5086 			SM_ENTER(WPA_PTK, PTKSTART);
5087 		} else {
5088 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
5089 					LOGGER_INFO,
5090 					"no PSK configured for the STA");
5091 			wpa_auth->dot11RSNA4WayHandshakeFailures++;
5092 			SM_ENTER(WPA_PTK, DISCONNECT);
5093 		}
5094 		break;
5095 	case WPA_PTK_PTKSTART:
5096 		if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
5097 		    sm->EAPOLKeyPairwise)
5098 			SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING);
5099 		else if (sm->TimeoutCtr > conf->wpa_pairwise_update_count) {
5100 			wpa_auth->dot11RSNA4WayHandshakeFailures++;
5101 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
5102 					 LOGGER_DEBUG,
5103 					 "PTKSTART: Retry limit %u reached",
5104 					 conf->wpa_pairwise_update_count);
5105 			sm->disconnect_reason =
5106 				WLAN_REASON_4WAY_HANDSHAKE_TIMEOUT;
5107 			SM_ENTER(WPA_PTK, DISCONNECT);
5108 		} else if (sm->TimeoutEvt)
5109 			SM_ENTER(WPA_PTK, PTKSTART);
5110 		break;
5111 	case WPA_PTK_PTKCALCNEGOTIATING:
5112 		if (sm->MICVerified)
5113 			SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING2);
5114 		else if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
5115 			 sm->EAPOLKeyPairwise)
5116 			SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING);
5117 		else if (sm->TimeoutEvt)
5118 			SM_ENTER(WPA_PTK, PTKSTART);
5119 		break;
5120 	case WPA_PTK_PTKCALCNEGOTIATING2:
5121 		SM_ENTER(WPA_PTK, PTKINITNEGOTIATING);
5122 		break;
5123 	case WPA_PTK_PTKINITNEGOTIATING:
5124 		if (sm->update_snonce)
5125 			SM_ENTER(WPA_PTK, PTKCALCNEGOTIATING);
5126 		else if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
5127 			 sm->EAPOLKeyPairwise && sm->MICVerified)
5128 			SM_ENTER(WPA_PTK, PTKINITDONE);
5129 		else if (sm->TimeoutCtr >
5130 			 conf->wpa_pairwise_update_count ||
5131 			 (conf->wpa_disable_eapol_key_retries &&
5132 			  sm->TimeoutCtr > 1)) {
5133 			wpa_auth->dot11RSNA4WayHandshakeFailures++;
5134 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
5135 					 LOGGER_DEBUG,
5136 					 "PTKINITNEGOTIATING: Retry limit %u reached",
5137 					 conf->wpa_pairwise_update_count);
5138 			sm->disconnect_reason =
5139 				WLAN_REASON_4WAY_HANDSHAKE_TIMEOUT;
5140 			SM_ENTER(WPA_PTK, DISCONNECT);
5141 		} else if (sm->TimeoutEvt)
5142 			SM_ENTER(WPA_PTK, PTKINITNEGOTIATING);
5143 		break;
5144 	case WPA_PTK_PTKINITDONE:
5145 		break;
5146 	}
5147 }
5148 
5149 
5150 SM_STATE(WPA_PTK_GROUP, IDLE)
5151 {
5152 	SM_ENTRY_MA(WPA_PTK_GROUP, IDLE, wpa_ptk_group);
5153 	if (sm->Init) {
5154 		/* Init flag is not cleared here, so avoid busy
5155 		 * loop by claiming nothing changed. */
5156 		sm->changed = false;
5157 	}
5158 	sm->GTimeoutCtr = 0;
5159 }
5160 
5161 
5162 SM_STATE(WPA_PTK_GROUP, REKEYNEGOTIATING)
5163 {
5164 	u8 rsc[WPA_KEY_RSC_LEN];
5165 	struct wpa_group *gsm = sm->group;
5166 	const u8 *kde = NULL;
5167 	u8 *kde_buf = NULL, *pos, hdr[2];
5168 	size_t kde_len = 0;
5169 	u8 *gtk, stub_gtk[32];
5170 	struct wpa_auth_config *conf = &sm->wpa_auth->conf;
5171 	bool is_mld = false;
5172 
5173 #ifdef CONFIG_IEEE80211BE
5174 	is_mld = sm->mld_assoc_link_id >= 0;
5175 #endif /* CONFIG_IEEE80211BE */
5176 
5177 	SM_ENTRY_MA(WPA_PTK_GROUP, REKEYNEGOTIATING, wpa_ptk_group);
5178 
5179 	sm->GTimeoutCtr++;
5180 	if (conf->wpa_disable_eapol_key_retries && sm->GTimeoutCtr > 1) {
5181 		/* Do not allow retransmission of EAPOL-Key group msg 1/2 */
5182 		return;
5183 	}
5184 	if (sm->GTimeoutCtr > conf->wpa_group_update_count) {
5185 		/* No point in sending the EAPOL-Key - we will disconnect
5186 		 * immediately following this. */
5187 		return;
5188 	}
5189 
5190 	if (sm->wpa == WPA_VERSION_WPA)
5191 		sm->PInitAKeys = false;
5192 	sm->TimeoutEvt = false;
5193 	/* Send EAPOL(1, 1, 1, !Pair, G, RSC, GNonce, MIC(PTK), GTK[GN]) */
5194 	os_memset(rsc, 0, WPA_KEY_RSC_LEN);
5195 	if (gsm->wpa_group_state == WPA_GROUP_SETKEYSDONE)
5196 		wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN, rsc);
5197 	wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
5198 			"sending 1/2 msg of Group Key Handshake");
5199 
5200 	gtk = gsm->GTK[gsm->GN - 1];
5201 	if (conf->disable_gtk || sm->wpa_key_mgmt == WPA_KEY_MGMT_OSEN) {
5202 		/*
5203 		 * Provide unique random GTK to each STA to prevent use
5204 		 * of GTK in the BSS.
5205 		 */
5206 		if (random_get_bytes(stub_gtk, gsm->GTK_len) < 0)
5207 			return;
5208 		gtk = stub_gtk;
5209 	}
5210 
5211 	if (sm->wpa == WPA_VERSION_WPA2 && !is_mld) {
5212 		kde_len = 2 + RSN_SELECTOR_LEN + 2 + gsm->GTK_len +
5213 			ieee80211w_kde_len(sm) + ocv_oci_len(sm);
5214 		kde_buf = os_malloc(kde_len);
5215 		if (!kde_buf)
5216 			return;
5217 
5218 		kde = pos = kde_buf;
5219 		hdr[0] = gsm->GN & 0x03;
5220 		hdr[1] = 0;
5221 		pos = wpa_add_kde(pos, RSN_KEY_DATA_GROUPKEY, hdr, 2,
5222 				  gtk, gsm->GTK_len);
5223 		pos = ieee80211w_kde_add(sm, pos);
5224 		if (ocv_oci_add(sm, &pos,
5225 				conf->oci_freq_override_eapol_g1) < 0) {
5226 			os_free(kde_buf);
5227 			return;
5228 		}
5229 		kde_len = pos - kde;
5230 #ifdef CONFIG_IEEE80211BE
5231 	} else if (sm->wpa == WPA_VERSION_WPA2 && is_mld) {
5232 		kde_len = wpa_auth_ml_group_kdes_len(sm);
5233 		if (kde_len) {
5234 			kde_buf = os_malloc(kde_len);
5235 			if (!kde_buf)
5236 				return;
5237 
5238 			kde = pos = kde_buf;
5239 			pos = wpa_auth_ml_group_kdes(sm, pos);
5240 			kde_len = pos - kde_buf;
5241 		}
5242 #endif /* CONFIG_IEEE80211BE */
5243 	} else {
5244 		kde = gtk;
5245 		kde_len = gsm->GTK_len;
5246 	}
5247 
5248 	wpa_send_eapol(sm->wpa_auth, sm,
5249 		       WPA_KEY_INFO_SECURE |
5250 		       (wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len) ?
5251 			WPA_KEY_INFO_MIC : 0) |
5252 		       WPA_KEY_INFO_ACK |
5253 		       (!sm->Pair ? WPA_KEY_INFO_INSTALL : 0),
5254 		       rsc, NULL, kde, kde_len, gsm->GN, 1);
5255 
5256 	bin_clear_free(kde_buf, kde_len);
5257 }
5258 
5259 
5260 SM_STATE(WPA_PTK_GROUP, REKEYESTABLISHED)
5261 {
5262 	struct wpa_authenticator *wpa_auth = sm->wpa_auth;
5263 #ifdef CONFIG_OCV
5264 	const u8 *key_data, *mic;
5265 	struct ieee802_1x_hdr *hdr;
5266 	struct wpa_eapol_key *key;
5267 	struct wpa_eapol_ie_parse kde;
5268 	size_t mic_len;
5269 	u16 key_data_length;
5270 #endif /* CONFIG_OCV */
5271 
5272 	SM_ENTRY_MA(WPA_PTK_GROUP, REKEYESTABLISHED, wpa_ptk_group);
5273 	sm->EAPOLKeyReceived = false;
5274 
5275 #ifdef CONFIG_OCV
5276 	mic_len = wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len);
5277 
5278 	/*
5279 	 * Note: last_rx_eapol_key length fields have already been validated in
5280 	 * wpa_receive().
5281 	 */
5282 	hdr = (struct ieee802_1x_hdr *) sm->last_rx_eapol_key;
5283 	key = (struct wpa_eapol_key *) (hdr + 1);
5284 	mic = (u8 *) (key + 1);
5285 	key_data = mic + mic_len + 2;
5286 	key_data_length = WPA_GET_BE16(mic + mic_len);
5287 	if (key_data_length > sm->last_rx_eapol_key_len - sizeof(*hdr) -
5288 	    sizeof(*key) - mic_len - 2)
5289 		return;
5290 
5291 	if (wpa_parse_kde_ies(key_data, key_data_length, &kde) < 0) {
5292 		wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
5293 				 "received EAPOL-Key group msg 2/2 with invalid Key Data contents");
5294 		return;
5295 	}
5296 
5297 	if (wpa_auth_uses_ocv(sm)) {
5298 		struct wpa_channel_info ci;
5299 		int tx_chanwidth;
5300 		int tx_seg1_idx;
5301 
5302 		if (wpa_channel_info(wpa_auth, &ci) != 0) {
5303 			wpa_auth_logger(wpa_auth, wpa_auth_get_spa(sm),
5304 					LOGGER_INFO,
5305 					"Failed to get channel info to validate received OCI in EAPOL-Key group 2/2");
5306 			return;
5307 		}
5308 
5309 		if (get_sta_tx_parameters(sm,
5310 					  channel_width_to_int(ci.chanwidth),
5311 					  ci.seg1_idx, &tx_chanwidth,
5312 					  &tx_seg1_idx) < 0)
5313 			return;
5314 
5315 		if (ocv_verify_tx_params(kde.oci, kde.oci_len, &ci,
5316 					 tx_chanwidth, tx_seg1_idx) !=
5317 		    OCI_SUCCESS) {
5318 			wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm),
5319 					 LOGGER_INFO,
5320 					 "OCV failed: %s", ocv_errorstr);
5321 			if (wpa_auth->conf.msg_ctx)
5322 				wpa_msg(wpa_auth->conf.msg_ctx, MSG_INFO,
5323 					OCV_FAILURE "addr=" MACSTR
5324 					" frame=eapol-key-g2 error=%s",
5325 					MAC2STR(wpa_auth_get_spa(sm)),
5326 					ocv_errorstr);
5327 			return;
5328 		}
5329 	}
5330 #endif /* CONFIG_OCV */
5331 
5332 	if (sm->GUpdateStationKeys)
5333 		wpa_gkeydone_sta(sm);
5334 	sm->GTimeoutCtr = 0;
5335 	/* FIX: MLME.SetProtection.Request(TA, Tx_Rx) */
5336 	wpa_auth_vlogger(wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
5337 			 "group key handshake completed (%s)",
5338 			 sm->wpa == WPA_VERSION_WPA ? "WPA" : "RSN");
5339 	sm->has_GTK = true;
5340 }
5341 
5342 
5343 SM_STATE(WPA_PTK_GROUP, KEYERROR)
5344 {
5345 	SM_ENTRY_MA(WPA_PTK_GROUP, KEYERROR, wpa_ptk_group);
5346 	if (sm->GUpdateStationKeys)
5347 		wpa_gkeydone_sta(sm);
5348 	if (sm->wpa_auth->conf.no_disconnect_on_group_keyerror &&
5349 	    sm->wpa == WPA_VERSION_WPA2) {
5350 		wpa_auth_vlogger(sm->wpa_auth, wpa_auth_get_spa(sm),
5351 				 LOGGER_DEBUG,
5352 				 "group key handshake failed after %u tries - allow STA to remain connected",
5353 				 sm->wpa_auth->conf.wpa_group_update_count);
5354 		return;
5355 	}
5356 	sm->Disconnect = true;
5357 	sm->disconnect_reason = WLAN_REASON_GROUP_KEY_UPDATE_TIMEOUT;
5358 	wpa_auth_vlogger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_INFO,
5359 			 "group key handshake failed (%s) after %u tries",
5360 			 sm->wpa == WPA_VERSION_WPA ? "WPA" : "RSN",
5361 			 sm->wpa_auth->conf.wpa_group_update_count);
5362 }
5363 
5364 
5365 SM_STEP(WPA_PTK_GROUP)
5366 {
5367 	if (sm->Init || sm->PtkGroupInit) {
5368 		SM_ENTER(WPA_PTK_GROUP, IDLE);
5369 		sm->PtkGroupInit = false;
5370 	} else switch (sm->wpa_ptk_group_state) {
5371 	case WPA_PTK_GROUP_IDLE:
5372 		if (sm->GUpdateStationKeys ||
5373 		    (sm->wpa == WPA_VERSION_WPA && sm->PInitAKeys))
5374 			SM_ENTER(WPA_PTK_GROUP, REKEYNEGOTIATING);
5375 		break;
5376 	case WPA_PTK_GROUP_REKEYNEGOTIATING:
5377 		if (sm->EAPOLKeyReceived && !sm->EAPOLKeyRequest &&
5378 		    !sm->EAPOLKeyPairwise && sm->MICVerified)
5379 			SM_ENTER(WPA_PTK_GROUP, REKEYESTABLISHED);
5380 		else if (sm->GTimeoutCtr >
5381 			 sm->wpa_auth->conf.wpa_group_update_count ||
5382 			 (sm->wpa_auth->conf.wpa_disable_eapol_key_retries &&
5383 			  sm->GTimeoutCtr > 1))
5384 			SM_ENTER(WPA_PTK_GROUP, KEYERROR);
5385 		else if (sm->TimeoutEvt)
5386 			SM_ENTER(WPA_PTK_GROUP, REKEYNEGOTIATING);
5387 		break;
5388 	case WPA_PTK_GROUP_KEYERROR:
5389 		SM_ENTER(WPA_PTK_GROUP, IDLE);
5390 		break;
5391 	case WPA_PTK_GROUP_REKEYESTABLISHED:
5392 		SM_ENTER(WPA_PTK_GROUP, IDLE);
5393 		break;
5394 	}
5395 }
5396 
5397 
5398 static int wpa_gtk_update(struct wpa_authenticator *wpa_auth,
5399 			  struct wpa_group *group)
5400 {
5401 	struct wpa_auth_config *conf = &wpa_auth->conf;
5402 	int ret = 0;
5403 	size_t len;
5404 
5405 	os_memcpy(group->GNonce, group->Counter, WPA_NONCE_LEN);
5406 	inc_byte_array(group->Counter, WPA_NONCE_LEN);
5407 	if (wpa_gmk_to_gtk(group->GMK, "Group key expansion",
5408 			   wpa_auth->addr, group->GNonce,
5409 			   group->GTK[group->GN - 1], group->GTK_len) < 0)
5410 		ret = -1;
5411 	wpa_hexdump_key(MSG_DEBUG, "GTK",
5412 			group->GTK[group->GN - 1], group->GTK_len);
5413 
5414 	if (conf->ieee80211w != NO_MGMT_FRAME_PROTECTION) {
5415 		len = wpa_cipher_key_len(conf->group_mgmt_cipher);
5416 		os_memcpy(group->GNonce, group->Counter, WPA_NONCE_LEN);
5417 		inc_byte_array(group->Counter, WPA_NONCE_LEN);
5418 		if (wpa_gmk_to_gtk(group->GMK, "IGTK key expansion",
5419 				   wpa_auth->addr, group->GNonce,
5420 				   group->IGTK[group->GN_igtk - 4], len) < 0)
5421 			ret = -1;
5422 		wpa_hexdump_key(MSG_DEBUG, "IGTK",
5423 				group->IGTK[group->GN_igtk - 4], len);
5424 	}
5425 
5426 	if (!wpa_auth->non_tx_beacon_prot &&
5427 	    conf->ieee80211w == NO_MGMT_FRAME_PROTECTION)
5428 		return ret;
5429 	if (!conf->beacon_prot)
5430 		return ret;
5431 
5432 	if (wpa_auth->conf.tx_bss_auth) {
5433 		group = wpa_auth->conf.tx_bss_auth->group;
5434 		if (group->bigtk_set)
5435 			return ret;
5436 		wpa_printf(MSG_DEBUG, "Set up BIGTK for TX BSS");
5437 	}
5438 
5439 	len = wpa_cipher_key_len(conf->group_mgmt_cipher);
5440 	os_memcpy(group->GNonce, group->Counter, WPA_NONCE_LEN);
5441 	inc_byte_array(group->Counter, WPA_NONCE_LEN);
5442 	if (wpa_gmk_to_gtk(group->GMK, "BIGTK key expansion",
5443 			   wpa_auth->addr, group->GNonce,
5444 			   group->BIGTK[group->GN_bigtk - 6], len) < 0)
5445 		return -1;
5446 	group->bigtk_set = true;
5447 	wpa_hexdump_key(MSG_DEBUG, "BIGTK",
5448 			group->BIGTK[group->GN_bigtk - 6], len);
5449 
5450 	return ret;
5451 }
5452 
5453 
5454 static void wpa_group_gtk_init(struct wpa_authenticator *wpa_auth,
5455 			       struct wpa_group *group)
5456 {
5457 	wpa_printf(MSG_DEBUG,
5458 		   "WPA: group state machine entering state GTK_INIT (VLAN-ID %d)",
5459 		   group->vlan_id);
5460 	group->changed = false; /* GInit is not cleared here; avoid loop */
5461 	group->wpa_group_state = WPA_GROUP_GTK_INIT;
5462 
5463 	/* GTK[0..N] = 0 */
5464 	os_memset(group->GTK, 0, sizeof(group->GTK));
5465 	group->GN = 1;
5466 	group->GM = 2;
5467 	group->GN_igtk = 4;
5468 	group->GM_igtk = 5;
5469 	group->GN_bigtk = 6;
5470 	group->GM_bigtk = 7;
5471 	/* GTK[GN] = CalcGTK() */
5472 	wpa_gtk_update(wpa_auth, group);
5473 }
5474 
5475 
5476 static int wpa_group_update_sta(struct wpa_state_machine *sm, void *ctx)
5477 {
5478 	if (ctx != NULL && ctx != sm->group)
5479 		return 0;
5480 
5481 	if (sm->wpa_ptk_state != WPA_PTK_PTKINITDONE) {
5482 		wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm),
5483 				LOGGER_DEBUG,
5484 				"Not in PTKINITDONE; skip Group Key update");
5485 		sm->GUpdateStationKeys = false;
5486 		return 0;
5487 	}
5488 	if (sm->GUpdateStationKeys) {
5489 		/*
5490 		 * This should not really happen, so add a debug log entry.
5491 		 * Since we clear the GKeyDoneStations before the loop, the
5492 		 * station needs to be counted here anyway.
5493 		 */
5494 		wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm),
5495 				LOGGER_DEBUG,
5496 				"GUpdateStationKeys was already set when marking station for GTK rekeying");
5497 	}
5498 
5499 	/* Do not rekey GTK/IGTK when STA is in WNM-Sleep Mode */
5500 	if (sm->is_wnmsleep)
5501 		return 0;
5502 
5503 	sm->group->GKeyDoneStations++;
5504 	sm->GUpdateStationKeys = true;
5505 
5506 	wpa_sm_step(sm);
5507 	return 0;
5508 }
5509 
5510 
5511 #ifdef CONFIG_WNM_AP
5512 /* update GTK when exiting WNM-Sleep Mode */
5513 void wpa_wnmsleep_rekey_gtk(struct wpa_state_machine *sm)
5514 {
5515 	if (!sm || sm->is_wnmsleep)
5516 		return;
5517 
5518 	wpa_group_update_sta(sm, NULL);
5519 }
5520 
5521 
5522 void wpa_set_wnmsleep(struct wpa_state_machine *sm, int flag)
5523 {
5524 	if (sm)
5525 		sm->is_wnmsleep = !!flag;
5526 }
5527 
5528 
5529 int wpa_wnmsleep_gtk_subelem(struct wpa_state_machine *sm, u8 *pos)
5530 {
5531 	struct wpa_auth_config *conf = &sm->wpa_auth->conf;
5532 	struct wpa_group *gsm = sm->group;
5533 	u8 *start = pos;
5534 
5535 	/*
5536 	 * GTK subelement:
5537 	 * Sub-elem ID[1] | Length[1] | Key Info[2] | Key Length[1] | RSC[8] |
5538 	 * Key[5..32]
5539 	 */
5540 	*pos++ = WNM_SLEEP_SUBELEM_GTK;
5541 	*pos++ = 11 + gsm->GTK_len;
5542 	/* Key ID in B0-B1 of Key Info */
5543 	WPA_PUT_LE16(pos, gsm->GN & 0x03);
5544 	pos += 2;
5545 	*pos++ = gsm->GTK_len;
5546 	if (wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN, pos) != 0)
5547 		return 0;
5548 	pos += 8;
5549 	os_memcpy(pos, gsm->GTK[gsm->GN - 1], gsm->GTK_len);
5550 	if (conf->disable_gtk || sm->wpa_key_mgmt == WPA_KEY_MGMT_OSEN) {
5551 		/*
5552 		 * Provide unique random GTK to each STA to prevent use
5553 		 * of GTK in the BSS.
5554 		 */
5555 		if (random_get_bytes(pos, gsm->GTK_len) < 0)
5556 			return 0;
5557 	}
5558 	pos += gsm->GTK_len;
5559 
5560 	wpa_printf(MSG_DEBUG, "WNM: GTK Key ID %u in WNM-Sleep Mode exit",
5561 		   gsm->GN);
5562 	wpa_hexdump_key(MSG_DEBUG, "WNM: GTK in WNM-Sleep Mode exit",
5563 			gsm->GTK[gsm->GN - 1], gsm->GTK_len);
5564 
5565 	return pos - start;
5566 }
5567 
5568 
5569 int wpa_wnmsleep_igtk_subelem(struct wpa_state_machine *sm, u8 *pos)
5570 {
5571 	struct wpa_auth_config *conf = &sm->wpa_auth->conf;
5572 	struct wpa_group *gsm = sm->group;
5573 	u8 *start = pos;
5574 	size_t len = wpa_cipher_key_len(sm->wpa_auth->conf.group_mgmt_cipher);
5575 
5576 	/*
5577 	 * IGTK subelement:
5578 	 * Sub-elem ID[1] | Length[1] | KeyID[2] | PN[6] | Key[16]
5579 	 */
5580 	*pos++ = WNM_SLEEP_SUBELEM_IGTK;
5581 	*pos++ = 2 + 6 + len;
5582 	WPA_PUT_LE16(pos, gsm->GN_igtk);
5583 	pos += 2;
5584 	if (wpa_auth_get_seqnum(sm->wpa_auth, NULL, gsm->GN_igtk, pos) != 0)
5585 		return 0;
5586 	pos += 6;
5587 
5588 	os_memcpy(pos, gsm->IGTK[gsm->GN_igtk - 4], len);
5589 	if (conf->disable_gtk || sm->wpa_key_mgmt == WPA_KEY_MGMT_OSEN) {
5590 		/*
5591 		 * Provide unique random IGTK to each STA to prevent use
5592 		 * of IGTK in the BSS.
5593 		 */
5594 		if (random_get_bytes(pos, len) < 0)
5595 			return 0;
5596 	}
5597 	pos += len;
5598 
5599 	wpa_printf(MSG_DEBUG, "WNM: IGTK Key ID %u in WNM-Sleep Mode exit",
5600 		   gsm->GN_igtk);
5601 	wpa_hexdump_key(MSG_DEBUG, "WNM: IGTK in WNM-Sleep Mode exit",
5602 			gsm->IGTK[gsm->GN_igtk - 4], len);
5603 
5604 	return pos - start;
5605 }
5606 
5607 
5608 int wpa_wnmsleep_bigtk_subelem(struct wpa_state_machine *sm, u8 *pos)
5609 {
5610 	struct wpa_authenticator *wpa_auth = sm->wpa_auth;
5611 	struct wpa_group *gsm = wpa_auth->group;
5612 	u8 *start = pos;
5613 	size_t len = wpa_cipher_key_len(wpa_auth->conf.group_mgmt_cipher);
5614 
5615 	/*
5616 	 * BIGTK subelement:
5617 	 * Sub-elem ID[1] | Length[1] | KeyID[2] | PN[6] | Key[16]
5618 	 */
5619 	*pos++ = WNM_SLEEP_SUBELEM_BIGTK;
5620 	*pos++ = 2 + 6 + len;
5621 	WPA_PUT_LE16(pos, gsm->GN_bigtk);
5622 	pos += 2;
5623 	if (wpa_auth_get_seqnum(wpa_auth, NULL, gsm->GN_bigtk, pos) != 0)
5624 		return 0;
5625 	pos += 6;
5626 
5627 	os_memcpy(pos, gsm->BIGTK[gsm->GN_bigtk - 6], len);
5628 	if (sm->wpa_key_mgmt == WPA_KEY_MGMT_OSEN) {
5629 		/*
5630 		 * Provide unique random BIGTK to each STA to prevent use
5631 		 * of BIGTK in the BSS.
5632 		 */
5633 		if (random_get_bytes(pos, len) < 0)
5634 			return 0;
5635 	}
5636 	pos += len;
5637 
5638 	wpa_printf(MSG_DEBUG, "WNM: BIGTK Key ID %u in WNM-Sleep Mode exit",
5639 		   gsm->GN_bigtk);
5640 	wpa_hexdump_key(MSG_DEBUG, "WNM: BIGTK in WNM-Sleep Mode exit",
5641 			gsm->BIGTK[gsm->GN_bigtk - 6], len);
5642 
5643 	return pos - start;
5644 }
5645 
5646 #endif /* CONFIG_WNM_AP */
5647 
5648 
5649 static void wpa_group_update_gtk(struct wpa_authenticator *wpa_auth,
5650 				 struct wpa_group *group)
5651 {
5652 	int tmp;
5653 
5654 	tmp = group->GM;
5655 	group->GM = group->GN;
5656 	group->GN = tmp;
5657 	tmp = group->GM_igtk;
5658 	group->GM_igtk = group->GN_igtk;
5659 	group->GN_igtk = tmp;
5660 	tmp = group->GM_bigtk;
5661 	group->GM_bigtk = group->GN_bigtk;
5662 	group->GN_bigtk = tmp;
5663 	/* "GKeyDoneStations = GNoStations" is done in more robust way by
5664 	 * counting the STAs that are marked with GUpdateStationKeys instead of
5665 	 * including all STAs that could be in not-yet-completed state. */
5666 	wpa_gtk_update(wpa_auth, group);
5667 }
5668 
5669 
5670 static void wpa_group_setkeys(struct wpa_authenticator *wpa_auth,
5671 			      struct wpa_group *group)
5672 {
5673 	wpa_printf(MSG_DEBUG,
5674 		   "WPA: group state machine entering state SETKEYS (VLAN-ID %d)",
5675 		   group->vlan_id);
5676 	group->changed = true;
5677 	group->wpa_group_state = WPA_GROUP_SETKEYS;
5678 	group->GTKReKey = false;
5679 
5680 #ifdef CONFIG_IEEE80211BE
5681 	if (wpa_auth->is_ml)
5682 		goto skip_update;
5683 #endif /* CONFIG_IEEE80211BE */
5684 
5685 	wpa_group_update_gtk(wpa_auth, group);
5686 
5687 	if (group->GKeyDoneStations) {
5688 		wpa_printf(MSG_DEBUG,
5689 			   "wpa_group_setkeys: Unexpected GKeyDoneStations=%d when starting new GTK rekey",
5690 			   group->GKeyDoneStations);
5691 		group->GKeyDoneStations = 0;
5692 	}
5693 
5694 #ifdef CONFIG_IEEE80211BE
5695 skip_update:
5696 #endif /* CONFIG_IEEE80211BE */
5697 	wpa_auth_for_each_sta(wpa_auth, wpa_group_update_sta, group);
5698 	wpa_printf(MSG_DEBUG, "wpa_group_setkeys: GKeyDoneStations=%d",
5699 		   group->GKeyDoneStations);
5700 }
5701 
5702 
5703 static int wpa_group_config_group_keys(struct wpa_authenticator *wpa_auth,
5704 				       struct wpa_group *group)
5705 {
5706 	struct wpa_auth_config *conf = &wpa_auth->conf;
5707 	int ret = 0;
5708 
5709 	if (wpa_auth_set_key(wpa_auth, group->vlan_id,
5710 			     wpa_cipher_to_alg(conf->wpa_group),
5711 			     broadcast_ether_addr, group->GN,
5712 			     group->GTK[group->GN - 1], group->GTK_len,
5713 			     KEY_FLAG_GROUP_TX_DEFAULT) < 0)
5714 		ret = -1;
5715 
5716 	if (conf->ieee80211w != NO_MGMT_FRAME_PROTECTION) {
5717 		enum wpa_alg alg;
5718 		size_t len;
5719 
5720 		alg = wpa_cipher_to_alg(conf->group_mgmt_cipher);
5721 		len = wpa_cipher_key_len(conf->group_mgmt_cipher);
5722 
5723 		if (ret == 0 &&
5724 		    wpa_auth_set_key(wpa_auth, group->vlan_id, alg,
5725 				     broadcast_ether_addr, group->GN_igtk,
5726 				     group->IGTK[group->GN_igtk - 4], len,
5727 				     KEY_FLAG_GROUP_TX_DEFAULT) < 0)
5728 			ret = -1;
5729 
5730 		if (ret || !conf->beacon_prot)
5731 			return ret;
5732 		if (wpa_auth->conf.tx_bss_auth) {
5733 			wpa_auth = wpa_auth->conf.tx_bss_auth;
5734 			group = wpa_auth->group;
5735 			if (!group->bigtk_set || group->bigtk_configured)
5736 				return ret;
5737 		}
5738 		if (wpa_auth_set_key(wpa_auth, group->vlan_id, alg,
5739 				     broadcast_ether_addr, group->GN_bigtk,
5740 				     group->BIGTK[group->GN_bigtk - 6], len,
5741 				     KEY_FLAG_GROUP_TX_DEFAULT) < 0)
5742 			ret = -1;
5743 		else
5744 			group->bigtk_configured = true;
5745 	}
5746 
5747 	return ret;
5748 }
5749 
5750 
5751 static int wpa_group_disconnect_cb(struct wpa_state_machine *sm, void *ctx)
5752 {
5753 	if (sm->group == ctx) {
5754 		wpa_printf(MSG_DEBUG, "WPA: Mark STA " MACSTR
5755 			   " for disconnection due to fatal failure",
5756 			   MAC2STR(wpa_auth_get_spa(sm)));
5757 		sm->Disconnect = true;
5758 	}
5759 
5760 	return 0;
5761 }
5762 
5763 
5764 static void wpa_group_fatal_failure(struct wpa_authenticator *wpa_auth,
5765 				    struct wpa_group *group)
5766 {
5767 	wpa_printf(MSG_DEBUG,
5768 		   "WPA: group state machine entering state FATAL_FAILURE");
5769 	group->changed = true;
5770 	group->wpa_group_state = WPA_GROUP_FATAL_FAILURE;
5771 	wpa_auth_for_each_sta(wpa_auth, wpa_group_disconnect_cb, group);
5772 }
5773 
5774 
5775 static int wpa_group_setkeysdone(struct wpa_authenticator *wpa_auth,
5776 				 struct wpa_group *group)
5777 {
5778 	wpa_printf(MSG_DEBUG,
5779 		   "WPA: group state machine entering state SETKEYSDONE (VLAN-ID %d)",
5780 		   group->vlan_id);
5781 	group->changed = true;
5782 	group->wpa_group_state = WPA_GROUP_SETKEYSDONE;
5783 
5784 	if (wpa_group_config_group_keys(wpa_auth, group) < 0) {
5785 		wpa_group_fatal_failure(wpa_auth, group);
5786 		return -1;
5787 	}
5788 
5789 	return 0;
5790 }
5791 
5792 
5793 static void wpa_group_sm_step(struct wpa_authenticator *wpa_auth,
5794 			      struct wpa_group *group)
5795 {
5796 	if (group->GInit) {
5797 		wpa_group_gtk_init(wpa_auth, group);
5798 	} else if (group->wpa_group_state == WPA_GROUP_FATAL_FAILURE) {
5799 		/* Do not allow group operations */
5800 	} else if (group->wpa_group_state == WPA_GROUP_GTK_INIT &&
5801 		   group->GTKAuthenticator) {
5802 		wpa_group_setkeysdone(wpa_auth, group);
5803 	} else if (group->wpa_group_state == WPA_GROUP_SETKEYSDONE &&
5804 		   group->GTKReKey) {
5805 		wpa_group_setkeys(wpa_auth, group);
5806 	} else if (group->wpa_group_state == WPA_GROUP_SETKEYS) {
5807 		if (group->GKeyDoneStations == 0)
5808 			wpa_group_setkeysdone(wpa_auth, group);
5809 		else if (group->GTKReKey)
5810 			wpa_group_setkeys(wpa_auth, group);
5811 	}
5812 }
5813 
5814 
5815 static void wpa_clear_changed(struct wpa_state_machine *sm)
5816 {
5817 #ifdef CONFIG_IEEE80211BE
5818 	int link_id;
5819 #endif /* CONFIG_IEEE80211BE */
5820 
5821 	sm->changed = false;
5822 	sm->wpa_auth->group->changed = false;
5823 
5824 #ifdef CONFIG_IEEE80211BE
5825 	for_each_sm_auth(sm, link_id)
5826 		sm->mld_links[link_id].wpa_auth->group->changed = false;
5827 #endif /* CONFIG_IEEE80211BE */
5828 }
5829 
5830 
5831 static void wpa_group_sm_step_links(struct wpa_state_machine *sm)
5832 {
5833 #ifdef CONFIG_IEEE80211BE
5834 	int link_id;
5835 #endif /* CONFIG_IEEE80211BE */
5836 
5837 	if (!sm || !sm->wpa_auth)
5838 		return;
5839 	wpa_group_sm_step(sm->wpa_auth, sm->wpa_auth->group);
5840 
5841 #ifdef CONFIG_IEEE80211BE
5842 	for_each_sm_auth(sm, link_id) {
5843 		wpa_group_sm_step(sm->mld_links[link_id].wpa_auth,
5844 				  sm->mld_links[link_id].wpa_auth->group);
5845 	}
5846 #endif /* CONFIG_IEEE80211BE */
5847 }
5848 
5849 
5850 static bool wpa_group_sm_changed(struct wpa_state_machine *sm)
5851 {
5852 #ifdef CONFIG_IEEE80211BE
5853 	int link_id;
5854 #endif /* CONFIG_IEEE80211BE */
5855 	bool changed;
5856 
5857 	if (!sm || !sm->wpa_auth)
5858 		return false;
5859 	changed = sm->wpa_auth->group->changed;
5860 
5861 #ifdef CONFIG_IEEE80211BE
5862 	for_each_sm_auth(sm, link_id)
5863 		changed |= sm->mld_links[link_id].wpa_auth->group->changed;
5864 #endif /* CONFIG_IEEE80211BE */
5865 
5866 	return changed;
5867 }
5868 
5869 
5870 static int wpa_sm_step(struct wpa_state_machine *sm)
5871 {
5872 	if (!sm)
5873 		return 0;
5874 
5875 	if (sm->in_step_loop) {
5876 		/* This should not happen, but if it does, make sure we do not
5877 		 * end up freeing the state machine too early by exiting the
5878 		 * recursive call. */
5879 		wpa_printf(MSG_ERROR, "WPA: wpa_sm_step() called recursively");
5880 		return 0;
5881 	}
5882 
5883 	sm->in_step_loop = 1;
5884 	do {
5885 		if (sm->pending_deinit)
5886 			break;
5887 
5888 		wpa_clear_changed(sm);
5889 
5890 		SM_STEP_RUN(WPA_PTK);
5891 		if (sm->pending_deinit)
5892 			break;
5893 		SM_STEP_RUN(WPA_PTK_GROUP);
5894 		if (sm->pending_deinit)
5895 			break;
5896 		wpa_group_sm_step_links(sm);
5897 	} while (sm->changed || wpa_group_sm_changed(sm));
5898 	sm->in_step_loop = 0;
5899 
5900 	if (sm->pending_deinit) {
5901 		wpa_printf(MSG_DEBUG,
5902 			   "WPA: Completing pending STA state machine deinit for "
5903 			   MACSTR, MAC2STR(wpa_auth_get_spa(sm)));
5904 		wpa_free_sta_sm(sm);
5905 		return 1;
5906 	}
5907 	return 0;
5908 }
5909 
5910 
5911 static void wpa_sm_call_step(void *eloop_ctx, void *timeout_ctx)
5912 {
5913 	struct wpa_state_machine *sm = eloop_ctx;
5914 	wpa_sm_step(sm);
5915 }
5916 
5917 
5918 void wpa_auth_sm_notify(struct wpa_state_machine *sm)
5919 {
5920 	if (!sm)
5921 		return;
5922 	eloop_register_timeout(0, 0, wpa_sm_call_step, sm, NULL);
5923 }
5924 
5925 
5926 void wpa_gtk_rekey(struct wpa_authenticator *wpa_auth)
5927 {
5928 	int tmp, i;
5929 	struct wpa_group *group;
5930 
5931 	if (!wpa_auth)
5932 		return;
5933 
5934 	group = wpa_auth->group;
5935 
5936 	for (i = 0; i < 2; i++) {
5937 		tmp = group->GM;
5938 		group->GM = group->GN;
5939 		group->GN = tmp;
5940 		tmp = group->GM_igtk;
5941 		group->GM_igtk = group->GN_igtk;
5942 		group->GN_igtk = tmp;
5943 		if (!wpa_auth->conf.tx_bss_auth) {
5944 			tmp = group->GM_bigtk;
5945 			group->GM_bigtk = group->GN_bigtk;
5946 			group->GN_bigtk = tmp;
5947 		}
5948 		wpa_gtk_update(wpa_auth, group);
5949 		wpa_group_config_group_keys(wpa_auth, group);
5950 	}
5951 }
5952 
5953 
5954 static const char * wpa_bool_txt(int val)
5955 {
5956 	return val ? "TRUE" : "FALSE";
5957 }
5958 
5959 
5960 #define RSN_SUITE "%02x-%02x-%02x-%d"
5961 #define RSN_SUITE_ARG(s) \
5962 ((s) >> 24) & 0xff, ((s) >> 16) & 0xff, ((s) >> 8) & 0xff, (s) & 0xff
5963 
5964 int wpa_get_mib(struct wpa_authenticator *wpa_auth, char *buf, size_t buflen)
5965 {
5966 	struct wpa_auth_config *conf;
5967 	int len = 0, ret;
5968 	char pmkid_txt[PMKID_LEN * 2 + 1];
5969 #ifdef CONFIG_RSN_PREAUTH
5970 	const int preauth = 1;
5971 #else /* CONFIG_RSN_PREAUTH */
5972 	const int preauth = 0;
5973 #endif /* CONFIG_RSN_PREAUTH */
5974 
5975 	if (!wpa_auth)
5976 		return len;
5977 	conf = &wpa_auth->conf;
5978 
5979 	ret = os_snprintf(buf + len, buflen - len,
5980 			  "dot11RSNAOptionImplemented=TRUE\n"
5981 			  "dot11RSNAPreauthenticationImplemented=%s\n"
5982 			  "dot11RSNAEnabled=%s\n"
5983 			  "dot11RSNAPreauthenticationEnabled=%s\n",
5984 			  wpa_bool_txt(preauth),
5985 			  wpa_bool_txt(conf->wpa & WPA_PROTO_RSN),
5986 			  wpa_bool_txt(conf->rsn_preauth));
5987 	if (os_snprintf_error(buflen - len, ret))
5988 		return len;
5989 	len += ret;
5990 
5991 	wpa_snprintf_hex(pmkid_txt, sizeof(pmkid_txt),
5992 			 wpa_auth->dot11RSNAPMKIDUsed, PMKID_LEN);
5993 
5994 	ret = os_snprintf(
5995 		buf + len, buflen - len,
5996 		"dot11RSNAConfigVersion=%u\n"
5997 		"dot11RSNAConfigPairwiseKeysSupported=9999\n"
5998 		/* FIX: dot11RSNAConfigGroupCipher */
5999 		/* FIX: dot11RSNAConfigGroupRekeyMethod */
6000 		/* FIX: dot11RSNAConfigGroupRekeyTime */
6001 		/* FIX: dot11RSNAConfigGroupRekeyPackets */
6002 		"dot11RSNAConfigGroupRekeyStrict=%u\n"
6003 		"dot11RSNAConfigGroupUpdateCount=%u\n"
6004 		"dot11RSNAConfigPairwiseUpdateCount=%u\n"
6005 		"dot11RSNAConfigGroupCipherSize=%u\n"
6006 		"dot11RSNAConfigPMKLifetime=%u\n"
6007 		"dot11RSNAConfigPMKReauthThreshold=%u\n"
6008 		"dot11RSNAConfigNumberOfPTKSAReplayCounters=0\n"
6009 		"dot11RSNAConfigSATimeout=%u\n"
6010 		"dot11RSNAAuthenticationSuiteSelected=" RSN_SUITE "\n"
6011 		"dot11RSNAPairwiseCipherSelected=" RSN_SUITE "\n"
6012 		"dot11RSNAGroupCipherSelected=" RSN_SUITE "\n"
6013 		"dot11RSNAPMKIDUsed=%s\n"
6014 		"dot11RSNAAuthenticationSuiteRequested=" RSN_SUITE "\n"
6015 		"dot11RSNAPairwiseCipherRequested=" RSN_SUITE "\n"
6016 		"dot11RSNAGroupCipherRequested=" RSN_SUITE "\n"
6017 		"dot11RSNATKIPCounterMeasuresInvoked=%u\n"
6018 		"dot11RSNA4WayHandshakeFailures=%u\n"
6019 		"dot11RSNAConfigNumberOfGTKSAReplayCounters=0\n",
6020 		RSN_VERSION,
6021 		!!conf->wpa_strict_rekey,
6022 		conf->wpa_group_update_count,
6023 		conf->wpa_pairwise_update_count,
6024 		wpa_cipher_key_len(conf->wpa_group) * 8,
6025 		dot11RSNAConfigPMKLifetime,
6026 		dot11RSNAConfigPMKReauthThreshold,
6027 		dot11RSNAConfigSATimeout,
6028 		RSN_SUITE_ARG(wpa_auth->dot11RSNAAuthenticationSuiteSelected),
6029 		RSN_SUITE_ARG(wpa_auth->dot11RSNAPairwiseCipherSelected),
6030 		RSN_SUITE_ARG(wpa_auth->dot11RSNAGroupCipherSelected),
6031 		pmkid_txt,
6032 		RSN_SUITE_ARG(wpa_auth->dot11RSNAAuthenticationSuiteRequested),
6033 		RSN_SUITE_ARG(wpa_auth->dot11RSNAPairwiseCipherRequested),
6034 		RSN_SUITE_ARG(wpa_auth->dot11RSNAGroupCipherRequested),
6035 		wpa_auth->dot11RSNATKIPCounterMeasuresInvoked,
6036 		wpa_auth->dot11RSNA4WayHandshakeFailures);
6037 	if (os_snprintf_error(buflen - len, ret))
6038 		return len;
6039 	len += ret;
6040 
6041 	/* TODO: dot11RSNAConfigPairwiseCiphersTable */
6042 	/* TODO: dot11RSNAConfigAuthenticationSuitesTable */
6043 
6044 	/* Private MIB */
6045 	ret = os_snprintf(buf + len, buflen - len, "hostapdWPAGroupState=%d\n",
6046 			  wpa_auth->group->wpa_group_state);
6047 	if (os_snprintf_error(buflen - len, ret))
6048 		return len;
6049 	len += ret;
6050 
6051 	return len;
6052 }
6053 
6054 
6055 int wpa_get_mib_sta(struct wpa_state_machine *sm, char *buf, size_t buflen)
6056 {
6057 	int len = 0, ret;
6058 	u32 pairwise = 0;
6059 
6060 	if (!sm)
6061 		return 0;
6062 
6063 	/* TODO: FF-FF-FF-FF-FF-FF entry for broadcast/multicast stats */
6064 
6065 	/* dot11RSNAStatsEntry */
6066 
6067 	pairwise = wpa_cipher_to_suite(sm->wpa == WPA_VERSION_WPA2 ?
6068 				       WPA_PROTO_RSN : WPA_PROTO_WPA,
6069 				       sm->pairwise);
6070 	if (pairwise == 0)
6071 		return 0;
6072 
6073 	ret = os_snprintf(
6074 		buf + len, buflen - len,
6075 		/* TODO: dot11RSNAStatsIndex */
6076 		"dot11RSNAStatsSTAAddress=" MACSTR "\n"
6077 		"dot11RSNAStatsVersion=1\n"
6078 		"dot11RSNAStatsSelectedPairwiseCipher=" RSN_SUITE "\n"
6079 		/* TODO: dot11RSNAStatsTKIPICVErrors */
6080 		"dot11RSNAStatsTKIPLocalMICFailures=%u\n"
6081 		"dot11RSNAStatsTKIPRemoteMICFailures=%u\n"
6082 		/* TODO: dot11RSNAStatsCCMPReplays */
6083 		/* TODO: dot11RSNAStatsCCMPDecryptErrors */
6084 		/* TODO: dot11RSNAStatsTKIPReplays */,
6085 		MAC2STR(sm->addr),
6086 		RSN_SUITE_ARG(pairwise),
6087 		sm->dot11RSNAStatsTKIPLocalMICFailures,
6088 		sm->dot11RSNAStatsTKIPRemoteMICFailures);
6089 	if (os_snprintf_error(buflen - len, ret))
6090 		return len;
6091 	len += ret;
6092 
6093 	/* Private MIB */
6094 	ret = os_snprintf(buf + len, buflen - len,
6095 			  "wpa=%d\n"
6096 			  "AKMSuiteSelector=" RSN_SUITE "\n"
6097 			  "hostapdWPAPTKState=%d\n"
6098 			  "hostapdWPAPTKGroupState=%d\n"
6099 			  "hostapdMFPR=%d\n",
6100 			  sm->wpa,
6101 			  RSN_SUITE_ARG(wpa_akm_to_suite(sm->wpa_key_mgmt)),
6102 			  sm->wpa_ptk_state,
6103 			  sm->wpa_ptk_group_state,
6104 			  sm->mfpr);
6105 	if (os_snprintf_error(buflen - len, ret))
6106 		return len;
6107 	len += ret;
6108 
6109 	return len;
6110 }
6111 
6112 
6113 void wpa_auth_countermeasures_start(struct wpa_authenticator *wpa_auth)
6114 {
6115 	if (wpa_auth)
6116 		wpa_auth->dot11RSNATKIPCounterMeasuresInvoked++;
6117 }
6118 
6119 
6120 int wpa_auth_pairwise_set(struct wpa_state_machine *sm)
6121 {
6122 	return sm && sm->pairwise_set;
6123 }
6124 
6125 
6126 int wpa_auth_get_pairwise(struct wpa_state_machine *sm)
6127 {
6128 	return sm->pairwise;
6129 }
6130 
6131 
6132 const u8 * wpa_auth_get_pmk(struct wpa_state_machine *sm, int *len)
6133 {
6134 	if (!sm)
6135 		return NULL;
6136 	*len = sm->pmk_len;
6137 	return sm->PMK;
6138 }
6139 
6140 
6141 const u8 * wpa_auth_get_dpp_pkhash(struct wpa_state_machine *sm)
6142 {
6143 	if (!sm || !sm->pmksa)
6144 		return NULL;
6145 	return sm->pmksa->dpp_pkhash;
6146 }
6147 
6148 
6149 int wpa_auth_sta_key_mgmt(struct wpa_state_machine *sm)
6150 {
6151 	if (!sm)
6152 		return -1;
6153 	return sm->wpa_key_mgmt;
6154 }
6155 
6156 
6157 int wpa_auth_sta_wpa_version(struct wpa_state_machine *sm)
6158 {
6159 	if (!sm)
6160 		return 0;
6161 	return sm->wpa;
6162 }
6163 
6164 
6165 int wpa_auth_sta_ft_tk_already_set(struct wpa_state_machine *sm)
6166 {
6167 	if (!sm || !wpa_key_mgmt_ft(sm->wpa_key_mgmt))
6168 		return 0;
6169 	return sm->tk_already_set;
6170 }
6171 
6172 
6173 int wpa_auth_sta_fils_tk_already_set(struct wpa_state_machine *sm)
6174 {
6175 	if (!sm || !wpa_key_mgmt_fils(sm->wpa_key_mgmt))
6176 		return 0;
6177 	return sm->tk_already_set;
6178 }
6179 
6180 
6181 int wpa_auth_sta_clear_pmksa(struct wpa_state_machine *sm,
6182 			     struct rsn_pmksa_cache_entry *entry)
6183 {
6184 	if (!sm || sm->pmksa != entry)
6185 		return -1;
6186 	sm->pmksa = NULL;
6187 	return 0;
6188 }
6189 
6190 
6191 struct rsn_pmksa_cache_entry *
6192 wpa_auth_sta_get_pmksa(struct wpa_state_machine *sm)
6193 {
6194 	return sm ? sm->pmksa : NULL;
6195 }
6196 
6197 
6198 void wpa_auth_sta_local_mic_failure_report(struct wpa_state_machine *sm)
6199 {
6200 	if (sm)
6201 		sm->dot11RSNAStatsTKIPLocalMICFailures++;
6202 }
6203 
6204 
6205 const u8 * wpa_auth_get_wpa_ie(struct wpa_authenticator *wpa_auth, size_t *len)
6206 {
6207 	if (!wpa_auth)
6208 		return NULL;
6209 	*len = wpa_auth->wpa_ie_len;
6210 	return wpa_auth->wpa_ie;
6211 }
6212 
6213 
6214 int wpa_auth_pmksa_add(struct wpa_state_machine *sm, const u8 *pmk,
6215 		       unsigned int pmk_len,
6216 		       int session_timeout, struct eapol_state_machine *eapol)
6217 {
6218 	if (!sm || sm->wpa != WPA_VERSION_WPA2 ||
6219 	    sm->wpa_auth->conf.disable_pmksa_caching)
6220 		return -1;
6221 
6222 #ifdef CONFIG_IEEE80211R_AP
6223 	if (pmk_len >= 2 * PMK_LEN && wpa_key_mgmt_ft(sm->wpa_key_mgmt) &&
6224 	    wpa_key_mgmt_wpa_ieee8021x(sm->wpa_key_mgmt) &&
6225 	    !wpa_key_mgmt_sha384(sm->wpa_key_mgmt)) {
6226 		/* Cache MPMK/XXKey instead of initial part from MSK */
6227 		pmk = pmk + PMK_LEN;
6228 		pmk_len = PMK_LEN;
6229 	} else
6230 #endif /* CONFIG_IEEE80211R_AP */
6231 	if (wpa_key_mgmt_sha384(sm->wpa_key_mgmt)) {
6232 		if (pmk_len > PMK_LEN_SUITE_B_192)
6233 			pmk_len = PMK_LEN_SUITE_B_192;
6234 	} else if (pmk_len > PMK_LEN) {
6235 		pmk_len = PMK_LEN;
6236 	}
6237 
6238 	wpa_hexdump_key(MSG_DEBUG, "RSN: Cache PMK", pmk, pmk_len);
6239 	if (pmksa_cache_auth_add(sm->wpa_auth->pmksa, pmk, pmk_len, NULL,
6240 				 sm->PTK.kck, sm->PTK.kck_len,
6241 				 wpa_auth_get_aa(sm),
6242 				 wpa_auth_get_spa(sm), session_timeout,
6243 				 eapol, sm->wpa_key_mgmt))
6244 		return 0;
6245 
6246 	return -1;
6247 }
6248 
6249 
6250 int wpa_auth_pmksa_add_preauth(struct wpa_authenticator *wpa_auth,
6251 			       const u8 *pmk, size_t len, const u8 *sta_addr,
6252 			       int session_timeout,
6253 			       struct eapol_state_machine *eapol)
6254 {
6255 	if (!wpa_auth)
6256 		return -1;
6257 
6258 	wpa_hexdump_key(MSG_DEBUG, "RSN: Cache PMK from preauth", pmk, len);
6259 	if (pmksa_cache_auth_add(wpa_auth->pmksa, pmk, len, NULL,
6260 				 NULL, 0,
6261 				 wpa_auth->addr,
6262 				 sta_addr, session_timeout, eapol,
6263 				 WPA_KEY_MGMT_IEEE8021X))
6264 		return 0;
6265 
6266 	return -1;
6267 }
6268 
6269 
6270 int wpa_auth_pmksa_add_sae(struct wpa_authenticator *wpa_auth, const u8 *addr,
6271 			   const u8 *pmk, size_t pmk_len, const u8 *pmkid,
6272 			   int akmp)
6273 {
6274 	if (wpa_auth->conf.disable_pmksa_caching)
6275 		return -1;
6276 
6277 	wpa_hexdump_key(MSG_DEBUG, "RSN: Cache PMK from SAE", pmk, pmk_len);
6278 	if (!akmp)
6279 		akmp = WPA_KEY_MGMT_SAE;
6280 	if (pmksa_cache_auth_add(wpa_auth->pmksa, pmk, pmk_len, pmkid,
6281 				 NULL, 0, wpa_auth->addr, addr, 0, NULL, akmp))
6282 		return 0;
6283 
6284 	return -1;
6285 }
6286 
6287 
6288 void wpa_auth_add_sae_pmkid(struct wpa_state_machine *sm, const u8 *pmkid)
6289 {
6290 	os_memcpy(sm->pmkid, pmkid, PMKID_LEN);
6291 	sm->pmkid_set = 1;
6292 }
6293 
6294 
6295 int wpa_auth_pmksa_add2(struct wpa_authenticator *wpa_auth, const u8 *addr,
6296 			const u8 *pmk, size_t pmk_len, const u8 *pmkid,
6297 			int session_timeout, int akmp, const u8 *dpp_pkhash)
6298 {
6299 	struct rsn_pmksa_cache_entry *entry;
6300 
6301 	if (!wpa_auth || wpa_auth->conf.disable_pmksa_caching)
6302 		return -1;
6303 
6304 	wpa_hexdump_key(MSG_DEBUG, "RSN: Cache PMK (3)", pmk, PMK_LEN);
6305 	entry = pmksa_cache_auth_add(wpa_auth->pmksa, pmk, pmk_len, pmkid,
6306 				 NULL, 0, wpa_auth->addr, addr, session_timeout,
6307 				 NULL, akmp);
6308 	if (!entry)
6309 		return -1;
6310 
6311 	if (dpp_pkhash)
6312 		entry->dpp_pkhash = os_memdup(dpp_pkhash, SHA256_MAC_LEN);
6313 
6314 	return 0;
6315 }
6316 
6317 
6318 void wpa_auth_pmksa_remove(struct wpa_authenticator *wpa_auth,
6319 			   const u8 *sta_addr)
6320 {
6321 	struct rsn_pmksa_cache_entry *pmksa;
6322 
6323 	if (!wpa_auth || !wpa_auth->pmksa)
6324 		return;
6325 	pmksa = pmksa_cache_auth_get(wpa_auth->pmksa, sta_addr, NULL);
6326 	if (pmksa) {
6327 		wpa_printf(MSG_DEBUG, "WPA: Remove PMKSA cache entry for "
6328 			   MACSTR " based on request", MAC2STR(sta_addr));
6329 		pmksa_cache_free_entry(wpa_auth->pmksa, pmksa);
6330 	}
6331 }
6332 
6333 
6334 int wpa_auth_pmksa_list(struct wpa_authenticator *wpa_auth, char *buf,
6335 			size_t len)
6336 {
6337 	if (!wpa_auth || !wpa_auth->pmksa)
6338 		return 0;
6339 	return pmksa_cache_auth_list(wpa_auth->pmksa, buf, len);
6340 }
6341 
6342 
6343 void wpa_auth_pmksa_flush(struct wpa_authenticator *wpa_auth)
6344 {
6345 	if (wpa_auth && wpa_auth->pmksa)
6346 		pmksa_cache_auth_flush(wpa_auth->pmksa);
6347 }
6348 
6349 
6350 #ifdef CONFIG_PMKSA_CACHE_EXTERNAL
6351 #ifdef CONFIG_MESH
6352 
6353 int wpa_auth_pmksa_list_mesh(struct wpa_authenticator *wpa_auth, const u8 *addr,
6354 			     char *buf, size_t len)
6355 {
6356 	if (!wpa_auth || !wpa_auth->pmksa)
6357 		return 0;
6358 
6359 	return pmksa_cache_auth_list_mesh(wpa_auth->pmksa, addr, buf, len);
6360 }
6361 
6362 
6363 struct rsn_pmksa_cache_entry *
6364 wpa_auth_pmksa_create_entry(const u8 *aa, const u8 *spa, const u8 *pmk,
6365 			    size_t pmk_len, int akmp,
6366 			    const u8 *pmkid, int expiration)
6367 {
6368 	struct rsn_pmksa_cache_entry *entry;
6369 	struct os_reltime now;
6370 
6371 	entry = pmksa_cache_auth_create_entry(pmk, pmk_len, pmkid, NULL, 0, aa,
6372 					      spa, 0, NULL, akmp);
6373 	if (!entry)
6374 		return NULL;
6375 
6376 	os_get_reltime(&now);
6377 	entry->expiration = now.sec + expiration;
6378 	return entry;
6379 }
6380 
6381 
6382 int wpa_auth_pmksa_add_entry(struct wpa_authenticator *wpa_auth,
6383 			     struct rsn_pmksa_cache_entry *entry)
6384 {
6385 	int ret;
6386 
6387 	if (!wpa_auth || !wpa_auth->pmksa)
6388 		return -1;
6389 
6390 	ret = pmksa_cache_auth_add_entry(wpa_auth->pmksa, entry);
6391 	if (ret < 0)
6392 		wpa_printf(MSG_DEBUG,
6393 			   "RSN: Failed to store external PMKSA cache for "
6394 			   MACSTR, MAC2STR(entry->spa));
6395 
6396 	return ret;
6397 }
6398 
6399 #endif /* CONFIG_MESH */
6400 #endif /* CONFIG_PMKSA_CACHE_EXTERNAL */
6401 
6402 
6403 struct rsn_pmksa_cache *
6404 wpa_auth_get_pmksa_cache(struct wpa_authenticator *wpa_auth)
6405 {
6406 	if (!wpa_auth || !wpa_auth->pmksa)
6407 		return NULL;
6408 	return wpa_auth->pmksa;
6409 }
6410 
6411 
6412 struct rsn_pmksa_cache_entry *
6413 wpa_auth_pmksa_get(struct wpa_authenticator *wpa_auth, const u8 *sta_addr,
6414 		   const u8 *pmkid)
6415 {
6416 	if (!wpa_auth || !wpa_auth->pmksa)
6417 		return NULL;
6418 	return pmksa_cache_auth_get(wpa_auth->pmksa, sta_addr, pmkid);
6419 }
6420 
6421 
6422 void wpa_auth_pmksa_set_to_sm(struct rsn_pmksa_cache_entry *pmksa,
6423 			      struct wpa_state_machine *sm,
6424 			      struct wpa_authenticator *wpa_auth,
6425 			      u8 *pmkid, u8 *pmk, size_t *pmk_len)
6426 {
6427 	if (!sm)
6428 		return;
6429 
6430 	sm->pmksa = pmksa;
6431 	os_memcpy(pmk, pmksa->pmk, pmksa->pmk_len);
6432 	*pmk_len = pmksa->pmk_len;
6433 	os_memcpy(pmkid, pmksa->pmkid, PMKID_LEN);
6434 	os_memcpy(wpa_auth->dot11RSNAPMKIDUsed, pmksa->pmkid, PMKID_LEN);
6435 }
6436 
6437 
6438 /*
6439  * Remove and free the group from wpa_authenticator. This is triggered by a
6440  * callback to make sure nobody is currently iterating the group list while it
6441  * gets modified.
6442  */
6443 static void wpa_group_free(struct wpa_authenticator *wpa_auth,
6444 			   struct wpa_group *group)
6445 {
6446 	struct wpa_group *prev = wpa_auth->group;
6447 
6448 	wpa_printf(MSG_DEBUG, "WPA: Remove group state machine for VLAN-ID %d",
6449 		   group->vlan_id);
6450 
6451 	while (prev) {
6452 		if (prev->next == group) {
6453 			/* This never frees the special first group as needed */
6454 			prev->next = group->next;
6455 			os_free(group);
6456 			break;
6457 		}
6458 		prev = prev->next;
6459 	}
6460 
6461 }
6462 
6463 
6464 /* Increase the reference counter for group */
6465 static void wpa_group_get(struct wpa_authenticator *wpa_auth,
6466 			  struct wpa_group *group)
6467 {
6468 	/* Skip the special first group */
6469 	if (wpa_auth->group == group)
6470 		return;
6471 
6472 	group->references++;
6473 }
6474 
6475 
6476 /* Decrease the reference counter and maybe free the group */
6477 static void wpa_group_put(struct wpa_authenticator *wpa_auth,
6478 			  struct wpa_group *group)
6479 {
6480 	/* Skip the special first group */
6481 	if (wpa_auth->group == group)
6482 		return;
6483 
6484 	group->references--;
6485 	if (group->references)
6486 		return;
6487 	wpa_group_free(wpa_auth, group);
6488 }
6489 
6490 
6491 /*
6492  * Add a group that has its references counter set to zero. Caller needs to
6493  * call wpa_group_get() on the return value to mark the entry in use.
6494  */
6495 static struct wpa_group *
6496 wpa_auth_add_group(struct wpa_authenticator *wpa_auth, int vlan_id)
6497 {
6498 	struct wpa_group *group;
6499 
6500 	if (!wpa_auth || !wpa_auth->group)
6501 		return NULL;
6502 
6503 	wpa_printf(MSG_DEBUG, "WPA: Add group state machine for VLAN-ID %d",
6504 		   vlan_id);
6505 	group = wpa_group_init(wpa_auth, vlan_id, 0);
6506 	if (!group)
6507 		return NULL;
6508 
6509 	group->next = wpa_auth->group->next;
6510 	wpa_auth->group->next = group;
6511 
6512 	return group;
6513 }
6514 
6515 
6516 /*
6517  * Enforce that the group state machine for the VLAN is running, increase
6518  * reference counter as interface is up. References might have been increased
6519  * even if a negative value is returned.
6520  * Returns: -1 on error (group missing, group already failed); otherwise, 0
6521  */
6522 int wpa_auth_ensure_group(struct wpa_authenticator *wpa_auth, int vlan_id)
6523 {
6524 	struct wpa_group *group;
6525 
6526 	if (!wpa_auth)
6527 		return 0;
6528 
6529 	group = wpa_auth->group;
6530 	while (group) {
6531 		if (group->vlan_id == vlan_id)
6532 			break;
6533 		group = group->next;
6534 	}
6535 
6536 	if (!group) {
6537 		group = wpa_auth_add_group(wpa_auth, vlan_id);
6538 		if (!group)
6539 			return -1;
6540 	}
6541 
6542 	wpa_printf(MSG_DEBUG,
6543 		   "WPA: Ensure group state machine running for VLAN ID %d",
6544 		   vlan_id);
6545 
6546 	wpa_group_get(wpa_auth, group);
6547 	group->num_setup_iface++;
6548 
6549 	if (group->wpa_group_state == WPA_GROUP_FATAL_FAILURE)
6550 		return -1;
6551 
6552 	return 0;
6553 }
6554 
6555 
6556 /*
6557  * Decrease reference counter, expected to be zero afterwards.
6558  * returns: -1 on error (group not found, group in fail state)
6559  *          -2 if wpa_group is still referenced
6560  *           0 else
6561  */
6562 int wpa_auth_release_group(struct wpa_authenticator *wpa_auth, int vlan_id)
6563 {
6564 	struct wpa_group *group;
6565 	int ret = 0;
6566 
6567 	if (!wpa_auth)
6568 		return 0;
6569 
6570 	group = wpa_auth->group;
6571 	while (group) {
6572 		if (group->vlan_id == vlan_id)
6573 			break;
6574 		group = group->next;
6575 	}
6576 
6577 	if (!group)
6578 		return -1;
6579 
6580 	wpa_printf(MSG_DEBUG,
6581 		   "WPA: Try stopping group state machine for VLAN ID %d",
6582 		   vlan_id);
6583 
6584 	if (group->num_setup_iface <= 0) {
6585 		wpa_printf(MSG_ERROR,
6586 			   "WPA: wpa_auth_release_group called more often than wpa_auth_ensure_group for VLAN ID %d, skipping.",
6587 			   vlan_id);
6588 		return -1;
6589 	}
6590 	group->num_setup_iface--;
6591 
6592 	if (group->wpa_group_state == WPA_GROUP_FATAL_FAILURE)
6593 		ret = -1;
6594 
6595 	if (group->references > 1) {
6596 		wpa_printf(MSG_DEBUG,
6597 			   "WPA: Cannot stop group state machine for VLAN ID %d as references are still hold",
6598 			   vlan_id);
6599 		ret = -2;
6600 	}
6601 
6602 	wpa_group_put(wpa_auth, group);
6603 
6604 	return ret;
6605 }
6606 
6607 
6608 int wpa_auth_sta_set_vlan(struct wpa_state_machine *sm, int vlan_id)
6609 {
6610 	struct wpa_group *group;
6611 
6612 	if (!sm || !sm->wpa_auth)
6613 		return 0;
6614 
6615 	group = sm->wpa_auth->group;
6616 	while (group) {
6617 		if (group->vlan_id == vlan_id)
6618 			break;
6619 		group = group->next;
6620 	}
6621 
6622 	if (!group) {
6623 		group = wpa_auth_add_group(sm->wpa_auth, vlan_id);
6624 		if (!group)
6625 			return -1;
6626 	}
6627 
6628 	if (sm->group == group)
6629 		return 0;
6630 
6631 	if (group->wpa_group_state == WPA_GROUP_FATAL_FAILURE)
6632 		return -1;
6633 
6634 	wpa_printf(MSG_DEBUG, "WPA: Moving STA " MACSTR
6635 		   " to use group state machine for VLAN ID %d",
6636 		   MAC2STR(wpa_auth_get_spa(sm)), vlan_id);
6637 
6638 	wpa_group_get(sm->wpa_auth, group);
6639 	wpa_group_put(sm->wpa_auth, sm->group);
6640 	sm->group = group;
6641 
6642 	return 0;
6643 }
6644 
6645 
6646 void wpa_auth_eapol_key_tx_status(struct wpa_authenticator *wpa_auth,
6647 				  struct wpa_state_machine *sm, int ack)
6648 {
6649 	if (!wpa_auth || !sm)
6650 		return;
6651 	wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key TX status for STA " MACSTR
6652 		   " ack=%d", MAC2STR(wpa_auth_get_spa(sm)), ack);
6653 	if (sm->pending_1_of_4_timeout && ack) {
6654 		/*
6655 		 * Some deployed supplicant implementations update their SNonce
6656 		 * for each EAPOL-Key 2/4 message even within the same 4-way
6657 		 * handshake and then fail to use the first SNonce when
6658 		 * deriving the PTK. This results in unsuccessful 4-way
6659 		 * handshake whenever the relatively short initial timeout is
6660 		 * reached and EAPOL-Key 1/4 is retransmitted. Try to work
6661 		 * around this by increasing the timeout now that we know that
6662 		 * the station has received the frame.
6663 		 */
6664 		int timeout_ms = eapol_key_timeout_subseq;
6665 		wpa_printf(MSG_DEBUG,
6666 			   "WPA: Increase initial EAPOL-Key 1/4 timeout by %u ms because of acknowledged frame",
6667 			   timeout_ms);
6668 		eloop_cancel_timeout(wpa_send_eapol_timeout, wpa_auth, sm);
6669 		eloop_register_timeout(timeout_ms / 1000,
6670 				       (timeout_ms % 1000) * 1000,
6671 				       wpa_send_eapol_timeout, wpa_auth, sm);
6672 	}
6673 
6674 #ifdef CONFIG_TESTING_OPTIONS
6675 	if (sm->eapol_status_cb) {
6676 		sm->eapol_status_cb(sm->eapol_status_cb_ctx1,
6677 				    sm->eapol_status_cb_ctx2);
6678 		sm->eapol_status_cb = NULL;
6679 	}
6680 #endif /* CONFIG_TESTING_OPTIONS */
6681 }
6682 
6683 
6684 int wpa_auth_uses_sae(struct wpa_state_machine *sm)
6685 {
6686 	if (!sm)
6687 		return 0;
6688 	return wpa_key_mgmt_sae(sm->wpa_key_mgmt);
6689 }
6690 
6691 
6692 int wpa_auth_uses_ft_sae(struct wpa_state_machine *sm)
6693 {
6694 	if (!sm)
6695 		return 0;
6696 	return sm->wpa_key_mgmt == WPA_KEY_MGMT_FT_SAE ||
6697 		sm->wpa_key_mgmt == WPA_KEY_MGMT_FT_SAE_EXT_KEY;
6698 }
6699 
6700 
6701 #ifdef CONFIG_P2P
6702 int wpa_auth_get_ip_addr(struct wpa_state_machine *sm, u8 *addr)
6703 {
6704 	if (!sm || WPA_GET_BE32(sm->ip_addr) == 0)
6705 		return -1;
6706 	os_memcpy(addr, sm->ip_addr, 4);
6707 	return 0;
6708 }
6709 #endif /* CONFIG_P2P */
6710 
6711 
6712 int wpa_auth_radius_das_disconnect_pmksa(struct wpa_authenticator *wpa_auth,
6713 					 struct radius_das_attrs *attr)
6714 {
6715 	return pmksa_cache_auth_radius_das_disconnect(wpa_auth->pmksa, attr);
6716 }
6717 
6718 
6719 void wpa_auth_reconfig_group_keys(struct wpa_authenticator *wpa_auth)
6720 {
6721 	struct wpa_group *group;
6722 
6723 	if (!wpa_auth)
6724 		return;
6725 	for (group = wpa_auth->group; group; group = group->next)
6726 		wpa_group_config_group_keys(wpa_auth, group);
6727 }
6728 
6729 
6730 #ifdef CONFIG_FILS
6731 
6732 struct wpa_auth_fils_iter_data {
6733 	struct wpa_authenticator *auth;
6734 	const u8 *cache_id;
6735 	struct rsn_pmksa_cache_entry *pmksa;
6736 	const u8 *spa;
6737 	const u8 *pmkid;
6738 };
6739 
6740 
6741 static int wpa_auth_fils_iter(struct wpa_authenticator *a, void *ctx)
6742 {
6743 	struct wpa_auth_fils_iter_data *data = ctx;
6744 
6745 	if (a == data->auth || !a->conf.fils_cache_id_set ||
6746 	    os_memcmp(a->conf.fils_cache_id, data->cache_id,
6747 		      FILS_CACHE_ID_LEN) != 0)
6748 		return 0;
6749 	data->pmksa = pmksa_cache_auth_get(a->pmksa, data->spa, data->pmkid);
6750 	return data->pmksa != NULL;
6751 }
6752 
6753 
6754 struct rsn_pmksa_cache_entry *
6755 wpa_auth_pmksa_get_fils_cache_id(struct wpa_authenticator *wpa_auth,
6756 				 const u8 *sta_addr, const u8 *pmkid)
6757 {
6758 	struct wpa_auth_fils_iter_data idata;
6759 
6760 	if (!wpa_auth->conf.fils_cache_id_set)
6761 		return NULL;
6762 	idata.auth = wpa_auth;
6763 	idata.cache_id = wpa_auth->conf.fils_cache_id;
6764 	idata.pmksa = NULL;
6765 	idata.spa = sta_addr;
6766 	idata.pmkid = pmkid;
6767 	wpa_auth_for_each_auth(wpa_auth, wpa_auth_fils_iter, &idata);
6768 	return idata.pmksa;
6769 }
6770 
6771 
6772 #ifdef CONFIG_IEEE80211R_AP
6773 int wpa_auth_write_fte(struct wpa_authenticator *wpa_auth,
6774 		       struct wpa_state_machine *sm,
6775 		       u8 *buf, size_t len)
6776 {
6777 	struct wpa_auth_config *conf = &wpa_auth->conf;
6778 
6779 	return wpa_write_ftie(conf, sm->wpa_key_mgmt, sm->xxkey_len,
6780 			      conf->r0_key_holder, conf->r0_key_holder_len,
6781 			      NULL, NULL, buf, len, NULL, 0, 0);
6782 }
6783 #endif /* CONFIG_IEEE80211R_AP */
6784 
6785 
6786 void wpa_auth_get_fils_aead_params(struct wpa_state_machine *sm,
6787 				   u8 *fils_anonce, u8 *fils_snonce,
6788 				   u8 *fils_kek, size_t *fils_kek_len)
6789 {
6790 	os_memcpy(fils_anonce, sm->ANonce, WPA_NONCE_LEN);
6791 	os_memcpy(fils_snonce, sm->SNonce, WPA_NONCE_LEN);
6792 	os_memcpy(fils_kek, sm->PTK.kek, WPA_KEK_MAX_LEN);
6793 	*fils_kek_len = sm->PTK.kek_len;
6794 }
6795 
6796 
6797 void wpa_auth_add_fils_pmk_pmkid(struct wpa_state_machine *sm, const u8 *pmk,
6798 				 size_t pmk_len, const u8 *pmkid)
6799 {
6800 	os_memcpy(sm->PMK, pmk, pmk_len);
6801 	sm->pmk_len = pmk_len;
6802 	os_memcpy(sm->pmkid, pmkid, PMKID_LEN);
6803 	sm->pmkid_set = 1;
6804 }
6805 
6806 #endif /* CONFIG_FILS */
6807 
6808 
6809 void wpa_auth_set_auth_alg(struct wpa_state_machine *sm, u16 auth_alg)
6810 {
6811 	if (sm)
6812 		sm->auth_alg = auth_alg;
6813 }
6814 
6815 
6816 #ifdef CONFIG_DPP2
6817 void wpa_auth_set_dpp_z(struct wpa_state_machine *sm, const struct wpabuf *z)
6818 {
6819 	if (sm) {
6820 		wpabuf_clear_free(sm->dpp_z);
6821 		sm->dpp_z = z ? wpabuf_dup(z) : NULL;
6822 	}
6823 }
6824 #endif /* CONFIG_DPP2 */
6825 
6826 
6827 void wpa_auth_set_ssid_protection(struct wpa_state_machine *sm, bool val)
6828 {
6829 	if (sm)
6830 		sm->ssid_protection = val;
6831 }
6832 
6833 
6834 void wpa_auth_set_transition_disable(struct wpa_authenticator *wpa_auth,
6835 				     u8 val)
6836 {
6837 	if (wpa_auth)
6838 		wpa_auth->conf.transition_disable = val;
6839 }
6840 
6841 
6842 #ifdef CONFIG_TESTING_OPTIONS
6843 
6844 int wpa_auth_resend_m1(struct wpa_state_machine *sm, int change_anonce,
6845 		       void (*cb)(void *ctx1, void *ctx2),
6846 		       void *ctx1, void *ctx2)
6847 {
6848 	const u8 *anonce = sm->ANonce;
6849 	u8 anonce_buf[WPA_NONCE_LEN];
6850 
6851 	if (change_anonce) {
6852 		if (random_get_bytes(anonce_buf, WPA_NONCE_LEN))
6853 			return -1;
6854 		anonce = anonce_buf;
6855 	}
6856 
6857 	wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
6858 			"sending 1/4 msg of 4-Way Handshake (TESTING)");
6859 	wpa_send_eapol(sm->wpa_auth, sm,
6860 		       WPA_KEY_INFO_ACK | WPA_KEY_INFO_KEY_TYPE, NULL,
6861 		       anonce, NULL, 0, 0, 0);
6862 	return 0;
6863 }
6864 
6865 
6866 int wpa_auth_resend_m3(struct wpa_state_machine *sm,
6867 		       void (*cb)(void *ctx1, void *ctx2),
6868 		       void *ctx1, void *ctx2)
6869 {
6870 	u8 rsc[WPA_KEY_RSC_LEN], *_rsc, *gtk, *kde, *pos;
6871 	u8 *opos;
6872 	size_t gtk_len, kde_len;
6873 	struct wpa_auth_config *conf = &sm->wpa_auth->conf;
6874 	struct wpa_group *gsm = sm->group;
6875 	u8 *wpa_ie;
6876 	int wpa_ie_len, secure, gtkidx, encr = 0;
6877 	u8 hdr[2];
6878 
6879 	/* Send EAPOL(1, 1, 1, Pair, P, RSC, ANonce, MIC(PTK), RSNIE, [MDIE],
6880 	   GTK[GN], IGTK, [BIGTK], [FTIE], [TIE * 2])
6881 	 */
6882 
6883 	/* Use 0 RSC */
6884 	os_memset(rsc, 0, WPA_KEY_RSC_LEN);
6885 	/* If FT is used, wpa_auth->wpa_ie includes both RSNIE and MDIE */
6886 	wpa_ie = sm->wpa_auth->wpa_ie;
6887 	wpa_ie_len = sm->wpa_auth->wpa_ie_len;
6888 	if (sm->wpa == WPA_VERSION_WPA &&
6889 	    (sm->wpa_auth->conf.wpa & WPA_PROTO_RSN) &&
6890 	    wpa_ie_len > wpa_ie[1] + 2 && wpa_ie[0] == WLAN_EID_RSN) {
6891 		/* WPA-only STA, remove RSN IE and possible MDIE */
6892 		wpa_ie = wpa_ie + wpa_ie[1] + 2;
6893 		if (wpa_ie[0] == WLAN_EID_RSNX)
6894 			wpa_ie = wpa_ie + wpa_ie[1] + 2;
6895 		if (wpa_ie[0] == WLAN_EID_MOBILITY_DOMAIN)
6896 			wpa_ie = wpa_ie + wpa_ie[1] + 2;
6897 		wpa_ie_len = wpa_ie[1] + 2;
6898 	}
6899 	wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
6900 			"sending 3/4 msg of 4-Way Handshake (TESTING)");
6901 	if (sm->wpa == WPA_VERSION_WPA2) {
6902 		/* WPA2 send GTK in the 4-way handshake */
6903 		secure = 1;
6904 		gtk = gsm->GTK[gsm->GN - 1];
6905 		gtk_len = gsm->GTK_len;
6906 		gtkidx = gsm->GN;
6907 		_rsc = rsc;
6908 		encr = 1;
6909 	} else {
6910 		/* WPA does not include GTK in msg 3/4 */
6911 		secure = 0;
6912 		gtk = NULL;
6913 		gtk_len = 0;
6914 		_rsc = NULL;
6915 		if (sm->rx_eapol_key_secure) {
6916 			/*
6917 			 * It looks like Windows 7 supplicant tries to use
6918 			 * Secure bit in msg 2/4 after having reported Michael
6919 			 * MIC failure and it then rejects the 4-way handshake
6920 			 * if msg 3/4 does not set Secure bit. Work around this
6921 			 * by setting the Secure bit here even in the case of
6922 			 * WPA if the supplicant used it first.
6923 			 */
6924 			wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm),
6925 					LOGGER_DEBUG,
6926 					"STA used Secure bit in WPA msg 2/4 - set Secure for 3/4 as workaround");
6927 			secure = 1;
6928 		}
6929 	}
6930 
6931 	kde_len = wpa_ie_len + ieee80211w_kde_len(sm) + ocv_oci_len(sm);
6932 
6933 	if (sm->use_ext_key_id)
6934 		kde_len += 2 + RSN_SELECTOR_LEN + 2;
6935 
6936 	if (gtk)
6937 		kde_len += 2 + RSN_SELECTOR_LEN + 2 + gtk_len;
6938 #ifdef CONFIG_IEEE80211R_AP
6939 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
6940 		kde_len += 2 + PMKID_LEN; /* PMKR1Name into RSN IE */
6941 		kde_len += 300; /* FTIE + 2 * TIE */
6942 	}
6943 #endif /* CONFIG_IEEE80211R_AP */
6944 	kde = os_malloc(kde_len);
6945 	if (!kde)
6946 		return -1;
6947 
6948 	pos = kde;
6949 	os_memcpy(pos, wpa_ie, wpa_ie_len);
6950 	pos += wpa_ie_len;
6951 #ifdef CONFIG_IEEE80211R_AP
6952 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
6953 		int res;
6954 		size_t elen;
6955 
6956 		elen = pos - kde;
6957 		res = wpa_insert_pmkid(kde, &elen, sm->pmk_r1_name, true);
6958 		if (res < 0) {
6959 			wpa_printf(MSG_ERROR,
6960 				   "FT: Failed to insert PMKR1Name into RSN IE in EAPOL-Key data");
6961 			os_free(kde);
6962 			return -1;
6963 		}
6964 		pos -= wpa_ie_len;
6965 		pos += elen;
6966 	}
6967 #endif /* CONFIG_IEEE80211R_AP */
6968 	hdr[1] = 0;
6969 
6970 	if (sm->use_ext_key_id) {
6971 		hdr[0] = sm->keyidx_active & 0x01;
6972 		pos = wpa_add_kde(pos, RSN_KEY_DATA_KEYID, hdr, 2, NULL, 0);
6973 	}
6974 
6975 	if (gtk) {
6976 		hdr[0] = gtkidx & 0x03;
6977 		pos = wpa_add_kde(pos, RSN_KEY_DATA_GROUPKEY, hdr, 2,
6978 				  gtk, gtk_len);
6979 	}
6980 	opos = pos;
6981 	pos = ieee80211w_kde_add(sm, pos);
6982 	if (pos - opos >= 2 + RSN_SELECTOR_LEN + WPA_IGTK_KDE_PREFIX_LEN) {
6983 		/* skip KDE header and keyid */
6984 		opos += 2 + RSN_SELECTOR_LEN + 2;
6985 		os_memset(opos, 0, 6); /* clear PN */
6986 	}
6987 	if (ocv_oci_add(sm, &pos, conf->oci_freq_override_eapol_m3) < 0) {
6988 		os_free(kde);
6989 		return -1;
6990 	}
6991 
6992 #ifdef CONFIG_IEEE80211R_AP
6993 	if (wpa_key_mgmt_ft(sm->wpa_key_mgmt)) {
6994 		int res;
6995 
6996 		if (sm->assoc_resp_ftie &&
6997 		    kde + kde_len - pos >= 2 + sm->assoc_resp_ftie[1]) {
6998 			os_memcpy(pos, sm->assoc_resp_ftie,
6999 				  2 + sm->assoc_resp_ftie[1]);
7000 			res = 2 + sm->assoc_resp_ftie[1];
7001 		} else {
7002 			res = wpa_write_ftie(conf, sm->wpa_key_mgmt,
7003 					     sm->xxkey_len,
7004 					     conf->r0_key_holder,
7005 					     conf->r0_key_holder_len,
7006 					     NULL, NULL, pos,
7007 					     kde + kde_len - pos,
7008 					     NULL, 0, 0);
7009 		}
7010 		if (res < 0) {
7011 			wpa_printf(MSG_ERROR,
7012 				   "FT: Failed to insert FTIE into EAPOL-Key Key Data");
7013 			os_free(kde);
7014 			return -1;
7015 		}
7016 		pos += res;
7017 
7018 		/* TIE[ReassociationDeadline] (TU) */
7019 		*pos++ = WLAN_EID_TIMEOUT_INTERVAL;
7020 		*pos++ = 5;
7021 		*pos++ = WLAN_TIMEOUT_REASSOC_DEADLINE;
7022 		WPA_PUT_LE32(pos, conf->reassociation_deadline);
7023 		pos += 4;
7024 
7025 		/* TIE[KeyLifetime] (seconds) */
7026 		*pos++ = WLAN_EID_TIMEOUT_INTERVAL;
7027 		*pos++ = 5;
7028 		*pos++ = WLAN_TIMEOUT_KEY_LIFETIME;
7029 		WPA_PUT_LE32(pos, conf->r0_key_lifetime);
7030 		pos += 4;
7031 	}
7032 #endif /* CONFIG_IEEE80211R_AP */
7033 
7034 	wpa_send_eapol(sm->wpa_auth, sm,
7035 		       (secure ? WPA_KEY_INFO_SECURE : 0) |
7036 		       (wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len) ?
7037 			WPA_KEY_INFO_MIC : 0) |
7038 		       WPA_KEY_INFO_ACK | WPA_KEY_INFO_INSTALL |
7039 		       WPA_KEY_INFO_KEY_TYPE,
7040 		       _rsc, sm->ANonce, kde, pos - kde, 0, encr);
7041 	bin_clear_free(kde, kde_len);
7042 	return 0;
7043 }
7044 
7045 
7046 int wpa_auth_resend_group_m1(struct wpa_state_machine *sm,
7047 			     void (*cb)(void *ctx1, void *ctx2),
7048 			     void *ctx1, void *ctx2)
7049 {
7050 	u8 rsc[WPA_KEY_RSC_LEN];
7051 	struct wpa_auth_config *conf = &sm->wpa_auth->conf;
7052 	struct wpa_group *gsm = sm->group;
7053 	const u8 *kde;
7054 	u8 *kde_buf = NULL, *pos, hdr[2];
7055 	u8 *opos;
7056 	size_t kde_len;
7057 	u8 *gtk;
7058 
7059 	/* Send EAPOL(1, 1, 1, !Pair, G, RSC, GNonce, MIC(PTK), GTK[GN]) */
7060 	os_memset(rsc, 0, WPA_KEY_RSC_LEN);
7061 	/* Use 0 RSC */
7062 	wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
7063 			"sending 1/2 msg of Group Key Handshake (TESTING)");
7064 
7065 	gtk = gsm->GTK[gsm->GN - 1];
7066 	if (sm->wpa == WPA_VERSION_WPA2) {
7067 		kde_len = 2 + RSN_SELECTOR_LEN + 2 + gsm->GTK_len +
7068 			ieee80211w_kde_len(sm) + ocv_oci_len(sm);
7069 		kde_buf = os_malloc(kde_len);
7070 		if (!kde_buf)
7071 			return -1;
7072 
7073 		kde = pos = kde_buf;
7074 		hdr[0] = gsm->GN & 0x03;
7075 		hdr[1] = 0;
7076 		pos = wpa_add_kde(pos, RSN_KEY_DATA_GROUPKEY, hdr, 2,
7077 				  gtk, gsm->GTK_len);
7078 		opos = pos;
7079 		pos = ieee80211w_kde_add(sm, pos);
7080 		if (pos - opos >=
7081 		    2 + RSN_SELECTOR_LEN + WPA_IGTK_KDE_PREFIX_LEN) {
7082 			/* skip KDE header and keyid */
7083 			opos += 2 + RSN_SELECTOR_LEN + 2;
7084 			os_memset(opos, 0, 6); /* clear PN */
7085 		}
7086 		if (ocv_oci_add(sm, &pos,
7087 				conf->oci_freq_override_eapol_g1) < 0) {
7088 			os_free(kde_buf);
7089 			return -1;
7090 		}
7091 		kde_len = pos - kde;
7092 	} else {
7093 		kde = gtk;
7094 		kde_len = gsm->GTK_len;
7095 	}
7096 
7097 	sm->eapol_status_cb = cb;
7098 	sm->eapol_status_cb_ctx1 = ctx1;
7099 	sm->eapol_status_cb_ctx2 = ctx2;
7100 
7101 	wpa_send_eapol(sm->wpa_auth, sm,
7102 		       WPA_KEY_INFO_SECURE |
7103 		       (wpa_mic_len(sm->wpa_key_mgmt, sm->pmk_len) ?
7104 			WPA_KEY_INFO_MIC : 0) |
7105 		       WPA_KEY_INFO_ACK |
7106 		       (!sm->Pair ? WPA_KEY_INFO_INSTALL : 0),
7107 		       rsc, NULL, kde, kde_len, gsm->GN, 1);
7108 
7109 	bin_clear_free(kde_buf, kde_len);
7110 	return 0;
7111 }
7112 
7113 
7114 int wpa_auth_rekey_gtk(struct wpa_authenticator *wpa_auth)
7115 {
7116 	if (!wpa_auth)
7117 		return -1;
7118 	eloop_cancel_timeout(wpa_rekey_gtk,
7119 			     wpa_get_primary_auth(wpa_auth), NULL);
7120 	return eloop_register_timeout(0, 0, wpa_rekey_gtk,
7121 				      wpa_get_primary_auth(wpa_auth), NULL);
7122 }
7123 
7124 
7125 int wpa_auth_rekey_ptk(struct wpa_authenticator *wpa_auth,
7126 		       struct wpa_state_machine *sm)
7127 {
7128 	if (!wpa_auth || !sm)
7129 		return -1;
7130 	wpa_auth_logger(wpa_auth, sm->addr, LOGGER_DEBUG, "rekeying PTK");
7131 	wpa_request_new_ptk(sm);
7132 	wpa_sm_step(sm);
7133 	return 0;
7134 }
7135 
7136 
7137 void wpa_auth_set_ft_rsnxe_used(struct wpa_authenticator *wpa_auth, int val)
7138 {
7139 	if (wpa_auth)
7140 		wpa_auth->conf.ft_rsnxe_used = val;
7141 }
7142 
7143 
7144 void wpa_auth_set_ocv_override_freq(struct wpa_authenticator *wpa_auth,
7145 				    enum wpa_auth_ocv_override_frame frame,
7146 				    unsigned int freq)
7147 {
7148 	if (!wpa_auth)
7149 		return;
7150 	switch (frame) {
7151 	case WPA_AUTH_OCV_OVERRIDE_EAPOL_M3:
7152 		wpa_auth->conf.oci_freq_override_eapol_m3 = freq;
7153 		break;
7154 	case WPA_AUTH_OCV_OVERRIDE_EAPOL_G1:
7155 		wpa_auth->conf.oci_freq_override_eapol_g1 = freq;
7156 		break;
7157 	case WPA_AUTH_OCV_OVERRIDE_FT_ASSOC:
7158 		wpa_auth->conf.oci_freq_override_ft_assoc = freq;
7159 		break;
7160 	case WPA_AUTH_OCV_OVERRIDE_FILS_ASSOC:
7161 		wpa_auth->conf.oci_freq_override_fils_assoc = freq;
7162 		break;
7163 	}
7164 }
7165 
7166 #endif /* CONFIG_TESTING_OPTIONS */
7167 
7168 
7169 void wpa_auth_sta_radius_psk_resp(struct wpa_state_machine *sm, bool success)
7170 {
7171 	if (!sm->waiting_radius_psk) {
7172 		wpa_printf(MSG_DEBUG,
7173 			   "Ignore RADIUS PSK response for " MACSTR
7174 			   " that did not wait one",
7175 			   MAC2STR(sm->addr));
7176 		return;
7177 	}
7178 
7179 	wpa_printf(MSG_DEBUG, "RADIUS PSK response for " MACSTR " (%s)",
7180 		   MAC2STR(sm->addr), success ? "success" : "fail");
7181 	sm->waiting_radius_psk = 0;
7182 
7183 	if (success) {
7184 		/* Try to process the EAPOL-Key msg 2/4 again */
7185 		sm->EAPOLKeyReceived = true;
7186 	} else {
7187 		sm->Disconnect = true;
7188 	}
7189 
7190 	eloop_register_timeout(0, 0, wpa_sm_call_step, sm, NULL);
7191 }
7192 
7193 
7194 void wpa_auth_set_ml_info(struct wpa_state_machine *sm,
7195 			  u8 mld_assoc_link_id, struct mld_info *info)
7196 {
7197 #ifdef CONFIG_IEEE80211BE
7198 	unsigned int link_id;
7199 
7200 	if (!info)
7201 		return;
7202 
7203 	os_memset(sm->mld_links, 0, sizeof(sm->mld_links));
7204 	sm->n_mld_affiliated_links = 0;
7205 
7206 	wpa_auth_logger(sm->wpa_auth, wpa_auth_get_spa(sm), LOGGER_DEBUG,
7207 			"MLD: Initialization");
7208 
7209 	os_memcpy(sm->peer_mld_addr, info->common_info.mld_addr, ETH_ALEN);
7210 
7211 	sm->mld_assoc_link_id = mld_assoc_link_id;
7212 
7213 	for (link_id = 0; link_id < MAX_NUM_MLD_LINKS; link_id++) {
7214 		struct mld_link_info *link = &info->links[link_id];
7215 		struct mld_link *sm_link = &sm->mld_links[link_id];
7216 		struct wpa_get_link_auth_ctx ctx;
7217 
7218 		sm_link->valid = link->valid;
7219 		if (!link->valid)
7220 			continue;
7221 
7222 		os_memcpy(sm_link->peer_addr, link->peer_addr, ETH_ALEN);
7223 
7224 		wpa_printf(MSG_DEBUG,
7225 			   "WPA_AUTH: MLD: id=%u, peer=" MACSTR,
7226 			   link_id,
7227 			   MAC2STR(sm_link->peer_addr));
7228 
7229 		if (link_id != mld_assoc_link_id) {
7230 			sm->n_mld_affiliated_links++;
7231 			ctx.addr = link->local_addr;
7232 			ctx.mld_addr = NULL;
7233 			ctx.link_id = -1;
7234 			ctx.wpa_auth = NULL;
7235 			wpa_auth_for_each_auth(sm->wpa_auth,
7236 					       wpa_get_link_sta_auth, &ctx);
7237 			if (ctx.wpa_auth) {
7238 				sm_link->wpa_auth = ctx.wpa_auth;
7239 				wpa_group_get(sm_link->wpa_auth,
7240 					      sm_link->wpa_auth->group);
7241 			}
7242 		} else {
7243 			sm_link->wpa_auth = sm->wpa_auth;
7244 		}
7245 
7246 		if (!sm_link->wpa_auth)
7247 			wpa_printf(MSG_ERROR,
7248 				   "Unable to find authenticator object for ML STA "
7249 				   MACSTR " on link id %d",
7250 				   MAC2STR(sm->wpa_auth->mld_addr),
7251 				   link_id);
7252 	}
7253 #endif /* CONFIG_IEEE80211BE */
7254 }
7255