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