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