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