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