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