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