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