1 /*
2  * WPA Supplicant - WPA state machine and EAPOL-Key processing
3  * Copyright (c) 2003-2010, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14 
15 #include "utils/includes.h"
16 
17 #include "utils/common.h"
18 #include "rsn_supp/wpa.h"
19 #include "rsn_supp/pmksa_cache.h"
20 #include "rsn_supp/wpa_i.h"
21 #include "common/eapol_common.h"
22 #include "common/ieee802_11_defs.h"
23 #include "rsn_supp/wpa_ie.h"
24 #include "esp_wpas_glue.h"
25 #include "esp_wifi_driver.h"
26 
27 #include "crypto/crypto.h"
28 #include "crypto/sha1.h"
29 #include "crypto/aes_wrap.h"
30 #include "crypto/ccmp.h"
31 #include "esp_rom_sys.h"
32 
33 /**
34  * eapol_sm_notify_eap_success - Notification of external EAP success trigger
35  * @sm: Pointer to EAPOL state machine allocated with eapol_sm_init()
36  * @success: %TRUE = set success, %FALSE = clear success
37  *
38  * Notify the EAPOL state machine that external event has forced EAP state to
39  * success (success = %TRUE). This can be cleared by setting success = %FALSE.
40  *
41  * This function is called to update EAP state when WPA-PSK key handshake has
42  * been completed successfully since WPA-PSK does not use EAP state machine.
43  */
44 
45 #define WPA_4_4_HANDSHAKE_BIT   (1<<13)
46 #define WPA_GROUP_HANDSHAKE_BIT (1<<14)
47   struct wpa_sm gWpaSm;
48 /* fix buf for tx for now */
49 #define WPA_TX_MSG_BUFF_MAXLEN 200
50 
51 #define ASSOC_IE_LEN 24 + 2 + PMKID_LEN + RSN_SELECTOR_LEN
52 #define MAX_EAPOL_RETRIES 3
53 u8 assoc_ie_buf[ASSOC_IE_LEN+2];
54 
55 void set_assoc_ie(u8 * assoc_buf);
56 
57 static int wpa_sm_set_key(struct install_key *sm, enum wpa_alg alg,
58         u8 *addr, int key_idx, int set_tx,
59         u8 *seq, size_t seq_len,
60         u8 *key, size_t key_len,
61         enum key_flag key_flag);
62 
63 static int wpa_sm_get_key(uint8_t *ifx, int *alg, u8 *addr, int *key_idx, u8 *key, size_t key_len, enum key_flag key_flag);
64 
65 void wpa_set_passphrase(char * passphrase, u8 *ssid, size_t ssid_len);
66 
67 void wpa_sm_set_pmk_from_pmksa(struct wpa_sm *sm);
68 static bool wpa_supplicant_gtk_in_use(struct wpa_sm *sm, struct wpa_gtk_data *gd);
wpa_sm_get_state(struct wpa_sm * sm)69 static inline enum wpa_states   wpa_sm_get_state(struct wpa_sm *sm)
70 {
71     return sm->wpa_state;;
72 }
73 
wpa_sm_cancel_auth_timeout(struct wpa_sm * sm)74 static inline void   wpa_sm_cancel_auth_timeout(struct wpa_sm *sm)
75 {
76 
77 }
78 
eapol_sm_notify_eap_success(Boolean success)79 void   eapol_sm_notify_eap_success(Boolean success)
80 {
81 
82 }
83 
cipher_type_map_supp_to_public(unsigned wpa_cipher)84 wifi_cipher_type_t cipher_type_map_supp_to_public(unsigned wpa_cipher)
85 {
86     switch (wpa_cipher) {
87     case WPA_CIPHER_NONE:
88         return WIFI_CIPHER_TYPE_NONE;
89 
90     case WPA_CIPHER_WEP40:
91         return WIFI_CIPHER_TYPE_WEP40;
92 
93     case WPA_CIPHER_WEP104:
94         return WIFI_CIPHER_TYPE_WEP104;
95 
96     case WPA_CIPHER_TKIP:
97         return WIFI_CIPHER_TYPE_TKIP;
98 
99     case WPA_CIPHER_CCMP:
100         return WIFI_CIPHER_TYPE_CCMP;
101 
102     case WPA_CIPHER_CCMP|WPA_CIPHER_TKIP:
103         return WIFI_CIPHER_TYPE_TKIP_CCMP;
104 
105     case WPA_CIPHER_AES_128_CMAC:
106         return WIFI_CIPHER_TYPE_AES_CMAC128;
107 
108     case WPA_CIPHER_SMS4:
109         return WIFI_CIPHER_TYPE_SMS4;
110 
111     default:
112         return WIFI_CIPHER_TYPE_UNKNOWN;
113     }
114 }
115 
cipher_type_map_public_to_supp(wifi_cipher_type_t cipher)116 unsigned cipher_type_map_public_to_supp(wifi_cipher_type_t cipher)
117 {
118     switch (cipher) {
119     case WIFI_CIPHER_TYPE_NONE:
120         return WPA_CIPHER_NONE;
121 
122     case WIFI_CIPHER_TYPE_WEP40:
123         return WPA_CIPHER_WEP40;
124 
125     case WIFI_CIPHER_TYPE_WEP104:
126         return WPA_CIPHER_WEP104;
127 
128     case WIFI_CIPHER_TYPE_TKIP:
129         return WPA_CIPHER_TKIP;
130 
131     case WIFI_CIPHER_TYPE_CCMP:
132         return WPA_CIPHER_CCMP;
133 
134 #ifdef CONFIG_GCMP
135     case WIFI_CIPHER_TYPE_GCMP:
136         return WPA_CIPHER_GCMP;
137 
138     case WIFI_CIPHER_TYPE_GCMP256:
139         return WPA_CIPHER_GCMP_256;
140 #endif
141 
142     case WIFI_CIPHER_TYPE_TKIP_CCMP:
143         return WPA_CIPHER_CCMP|WPA_CIPHER_TKIP;
144 
145     case WIFI_CIPHER_TYPE_AES_CMAC128:
146         return WPA_CIPHER_AES_128_CMAC;
147 
148 #ifdef CONFIG_GMAC
149     case WIFI_CIPHER_TYPE_AES_GMAC128:
150         return WPA_CIPHER_BIP_GMAC_128;
151 
152     case WIFI_CIPHER_TYPE_AES_GMAC256:
153         return WPA_CIPHER_BIP_GMAC_256;
154 #endif
155 
156     case WIFI_CIPHER_TYPE_SMS4:
157         return WPA_CIPHER_SMS4;
158 
159     default:
160         return WPA_CIPHER_NONE;
161     }
162 }
163 
is_wpa2_enterprise_connection(void)164 static bool is_wpa2_enterprise_connection(void)
165 {
166     uint8_t authmode;
167 
168     if (esp_wifi_sta_prof_is_wpa2_internal()) {
169         authmode = esp_wifi_sta_get_prof_authmode_internal();
170         if ((authmode == WPA2_AUTH_ENT) ||
171             (authmode == WPA2_AUTH_ENT_SHA256) ||
172             (authmode == WPA2_AUTH_ENT_SHA384_SUITE_B)) {
173             return true;
174         }
175     }
176 
177     return false;
178 }
179 
180 /**
181  * get_bssid - Get the current BSSID
182  * @priv: private driver interface data
183  * @bssid: buffer for BSSID (ETH_ALEN = 6 bytes)
184  *
185  * Returns: 0 on success, -1 on failure
186  *
187  * Query kernel driver for the current BSSID and copy it to bssid.
188  * Setting bssid to 00:00:00:00:00:00 is recommended if the STA is not
189  * associated.
190  */
wpa_sm_get_bssid(struct wpa_sm * sm,u8 * bssid)191 static inline int   wpa_sm_get_bssid(struct wpa_sm *sm, u8 *bssid)
192 {
193     memcpy(bssid, sm->bssid, ETH_ALEN);
194     return 0;
195 }
196 
197  /*
198  * wpa_ether_send - Send Ethernet frame
199  * @wpa_s: Pointer to wpa_supplicant data
200  * @dest: Destination MAC address
201  * @proto: Ethertype in host byte order
202  * @buf: Frame payload starting from IEEE 802.1X header
203  * @len: Frame payload length
204  * Returns: >=0 on success, <0 on failure
205  */
wpa_sm_ether_send(struct wpa_sm * sm,const u8 * dest,u16 proto,const u8 * data,size_t data_len)206 static inline int wpa_sm_ether_send( struct wpa_sm *sm, const u8 *dest, u16 proto,
207         const u8 *data, size_t data_len)
208 {
209     void *buffer = (void *)(data - sizeof(struct l2_ethhdr));
210     struct l2_ethhdr *eth = (struct l2_ethhdr *)buffer;
211 
212     memcpy(eth->h_dest, dest, ETH_ALEN);
213     memcpy(eth->h_source, sm->own_addr, ETH_ALEN);
214     eth->h_proto = host_to_be16(proto);
215     sm->sendto(buffer, sizeof(struct l2_ethhdr) + data_len);
216 
217     return 0;
218 }
219 
220 /**
221  * wpa_eapol_key_send - Send WPA/RSN EAPOL-Key message
222  * @sm: Pointer to WPA state machine data from wpa_sm_init()
223  * @kck: Key Confirmation Key (KCK, part of PTK)
224  * @kck_len: KCK length in octets
225  * @ver: Version field from Key Info
226  * @dest: Destination address for the frame
227  * @proto: Ethertype (usually ETH_P_EAPOL)
228  * @msg: EAPOL-Key message
229  * @msg_len: Length of message
230  * @key_mic: Pointer to the buffer to which the EAPOL-Key MIC is written
231  */
wpa_eapol_key_send(struct wpa_sm * sm,const u8 * kck,size_t kck_len,int ver,const u8 * dest,u16 proto,u8 * msg,size_t msg_len,u8 * key_mic)232 void wpa_eapol_key_send(struct wpa_sm *sm, const u8 *kck, size_t kck_len,
233             int ver, const u8 *dest, u16 proto,
234             u8 *msg, size_t msg_len, u8 *key_mic)
235 {
236     if (is_zero_ether_addr(dest) && is_zero_ether_addr(sm->bssid)) {
237         /*
238          * Association event was not yet received; try to fetch
239          * BSSID from the driver.
240          */
241         if (wpa_sm_get_bssid(sm, sm->bssid) < 0) {
242            #ifdef DEBUG_PRINT
243             wpa_printf(MSG_DEBUG, "WPA: Failed to read BSSID for "
244                    "EAPOL-Key destination address");
245            #endif
246         } else {
247             dest = sm->bssid;
248               #ifdef DEBUG_PRINT
249             wpa_printf(MSG_DEBUG, "WPA: Use BSSID (" MACSTR
250                    ") as the destination for EAPOL-Key",
251                    MAC2STR(dest));
252            #endif
253         }
254     }
255     if (key_mic &&
256         wpa_eapol_key_mic(kck, kck_len, sm->key_mgmt, ver, msg, msg_len,
257                   key_mic)) {
258 #ifdef DEBUG_PRINT
259         wpa_msg(NULL, MSG_ERROR,
260             "WPA: Failed to generate EAPOL-Key version %d key_mgmt 0x%x MIC",
261             ver, sm->key_mgmt);
262 #endif
263         goto out;
264     }
265     wpa_hexdump_key(MSG_DEBUG, "WPA: KCK", kck, kck_len);
266     wpa_hexdump(MSG_DEBUG, "WPA: Derived Key MIC", key_mic, wpa_mic_len(sm->key_mgmt));
267     wpa_hexdump(MSG_MSGDUMP, "WPA: TX EAPOL-Key", msg, msg_len);
268     wpa_sm_ether_send(sm, dest, proto, msg, msg_len);
269 out:
270     return;
271 }
272 
273 /**
274  * wpa_sm_key_request - Send EAPOL-Key Request
275  * @sm: Pointer to WPA state machine data from wpa_sm_init()
276  * @error: Indicate whether this is an Michael MIC error report
277  * @pairwise: 1 = error report for pairwise packet, 0 = for group packet
278  *
279  * Send an EAPOL-Key Request to the current authenticator. This function is
280  * used to request rekeying and it is usually called when a local Michael MIC
281  * failure is detected.
282  */
wpa_sm_key_request(struct wpa_sm * sm,int error,int pairwise)283 static void wpa_sm_key_request(struct wpa_sm *sm, int error, int pairwise)
284 {
285     size_t mic_len, hdrlen, rlen;
286     struct wpa_eapol_key *reply;
287     struct wpa_eapol_key_192 *reply192;
288     int key_info, ver;
289     u8 bssid[ETH_ALEN], *rbuf, *key_mic;
290 
291     if (sm->key_mgmt == WPA_KEY_MGMT_OSEN || wpa_key_mgmt_suite_b(sm->key_mgmt))
292         ver = WPA_KEY_INFO_TYPE_AKM_DEFINED;
293     else if (wpa_key_mgmt_ft(sm->key_mgmt) || wpa_key_mgmt_sha256(sm->key_mgmt))
294         ver = WPA_KEY_INFO_TYPE_AES_128_CMAC;
295     else if (sm->pairwise_cipher != WPA_CIPHER_TKIP)
296         ver = WPA_KEY_INFO_TYPE_HMAC_SHA1_AES;
297     else if (sm->key_mgmt == WPA_KEY_MGMT_SAE)
298         ver = 0;
299     else
300         ver = WPA_KEY_INFO_TYPE_HMAC_MD5_RC4;
301 
302     if (wpa_sm_get_bssid(sm, bssid) < 0) {
303         wpa_printf(MSG_DEBUG, "Failed to read BSSID for EAPOL-Key "
304                "request");
305         return;
306     }
307 
308     mic_len = wpa_mic_len(sm->key_mgmt);
309     hdrlen = mic_len == 24 ? sizeof(*reply192) : sizeof(*reply);
310     rbuf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_KEY, NULL,
311                   hdrlen, &rlen, (void *) &reply);
312     if (rbuf == NULL)
313         return;
314 
315     reply192 = (struct wpa_eapol_key_192 *) reply;
316 
317     reply->type = sm->proto == WPA_PROTO_RSN ?
318         EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
319     key_info = WPA_KEY_INFO_REQUEST | ver;
320     if (sm->ptk_set)
321         key_info |= WPA_KEY_INFO_MIC;
322     if (error)
323         key_info |= WPA_KEY_INFO_ERROR|WPA_KEY_INFO_SECURE;
324     if (pairwise)
325         key_info |= WPA_KEY_INFO_KEY_TYPE;
326 
327     WPA_PUT_BE16(reply->key_info, key_info);
328     WPA_PUT_BE16(reply->key_length, 0);
329 
330     os_memcpy(reply->replay_counter, sm->request_counter,
331           WPA_REPLAY_COUNTER_LEN);
332     inc_byte_array(sm->request_counter, WPA_REPLAY_COUNTER_LEN);
333     if (mic_len == 24)
334         WPA_PUT_BE16(reply192->key_data_length, 0);
335     else
336         WPA_PUT_BE16(reply->key_data_length, 0);
337 
338     if (!(key_info & WPA_KEY_INFO_MIC))
339         key_mic = NULL;
340     else
341         key_mic = reply192->key_mic; /* same offset in reply */
342 
343 
344     wpa_printf(MSG_DEBUG, "WPA: Sending EAPOL-Key Request (error=%d "
345            "pairwise=%d ptk_set=%d len=%lu)",
346            error, pairwise, sm->ptk_set, (unsigned long) rlen);
347     wpa_eapol_key_send(sm, sm->ptk.kck, sm->ptk.kck_len, ver, bssid,
348                        ETH_P_EAPOL, rbuf, rlen, key_mic);
349     wpa_sm_free_eapol(rbuf);
350 }
351 
wpa_sm_pmksa_free_cb(struct rsn_pmksa_cache_entry * entry,void * ctx,enum pmksa_free_reason reason)352 static void wpa_sm_pmksa_free_cb(struct rsn_pmksa_cache_entry *entry,
353         void *ctx, enum pmksa_free_reason reason)
354 {
355     struct wpa_sm *sm = ctx;
356     int deauth = 0;
357 
358     wpa_printf( MSG_DEBUG, "RSN: PMKSA cache entry free_cb: "
359             MACSTR " reason=%d", MAC2STR(entry->aa), reason);
360 
361     if (sm->cur_pmksa == entry) {
362         wpa_printf( MSG_DEBUG,
363                 "RSN: %s current PMKSA entry",
364                 reason == PMKSA_REPLACE ? "replaced" : "removed");
365         pmksa_cache_clear_current(sm);
366 
367         /*
368          * If an entry is simply being replaced, there's no need to
369          * deauthenticate because it will be immediately re-added.
370          * This happens when EAP authentication is completed again
371          * (reauth or failed PMKSA caching attempt).
372          * */
373         if (reason != PMKSA_REPLACE)
374             deauth = 1;
375     }
376 
377     if (reason == PMKSA_EXPIRE &&
378             (sm->pmk_len == entry->pmk_len &&
379              os_memcmp(sm->pmk, entry->pmk, sm->pmk_len) == 0)) {
380         wpa_printf( MSG_DEBUG,
381                 "RSN: deauthenticating due to expired PMK");
382         pmksa_cache_clear_current(sm);
383         deauth = 1;
384     }
385 
386     if (deauth) {
387         os_memset(sm->pmk, 0, sizeof(sm->pmk));
388         wpa_sm_deauthenticate(sm, WLAN_REASON_UNSPECIFIED);
389     }
390 }
391 
392 
393 
394 
395 
wpa_supplicant_get_pmk(struct wpa_sm * sm,const unsigned char * src_addr,const u8 * pmkid)396 static int wpa_supplicant_get_pmk(struct wpa_sm *sm,
397         const unsigned char *src_addr,
398         const u8 *pmkid)
399 {
400     int abort_cached = 0;
401 
402     if (pmkid && !sm->cur_pmksa) {
403         /* When using drivers that generate RSN IE, wpa_supplicant may
404          * not have enough time to get the association information
405          * event before receiving this 1/4 message, so try to find a
406          * matching PMKSA cache entry here. */
407         sm->cur_pmksa = pmksa_cache_get(sm->pmksa, src_addr, pmkid,
408                 NULL);
409         if (sm->cur_pmksa) {
410             wpa_printf(MSG_DEBUG,
411                     "RSN: found matching PMKID from PMKSA cache");
412         } else {
413             wpa_printf( MSG_DEBUG,
414                     "RSN: no matching PMKID found");
415             abort_cached = 1;
416         }
417     }
418 
419     if (pmkid && sm->cur_pmksa &&
420             os_memcmp_const(pmkid, sm->cur_pmksa->pmkid, PMKID_LEN) == 0) {
421 
422         wpa_hexdump(MSG_DEBUG, "RSN: matched PMKID", pmkid, PMKID_LEN);
423         wpa_sm_set_pmk_from_pmksa(sm);
424         wpa_hexdump_key(MSG_DEBUG, "RSN: PMK from PMKSA cache",
425                 sm->pmk, sm->pmk_len);
426         //eapol_sm_notify_cached(sm->eapol);
427 #ifdef CONFIG_IEEE80211R
428         sm->xxkey_len = 0;
429 #endif /* CONFIG_IEEE80211R */
430     } else if (wpa_key_mgmt_wpa_ieee8021x(sm->key_mgmt)) {
431         int res = 0, pmk_len;
432         /* For ESP_SUPPLICANT this is already set using wpa_set_pmk*/
433         //res = eapol_sm_get_key(sm->eapol, sm->pmk, PMK_LEN);
434         if (wpa_key_mgmt_sha384(sm->key_mgmt))
435             pmk_len = PMK_LEN_SUITE_B_192;
436         else
437             pmk_len = PMK_LEN;
438 
439         if(!sm->pmk_len) {
440             res = -1;
441         }
442 
443         if (res == 0) {
444             struct rsn_pmksa_cache_entry *sa = NULL;
445             wpa_hexdump_key(MSG_DEBUG, "WPA: PMK from EAPOL state "
446                     "machines", sm->pmk, pmk_len);
447             sm->pmk_len = pmk_len;
448             //wpa_supplicant_key_mgmt_set_pmk(sm);
449             if (sm->proto == WPA_PROTO_RSN &&
450                     !wpa_key_mgmt_suite_b(sm->key_mgmt) &&
451                     !wpa_key_mgmt_ft(sm->key_mgmt)) {
452                 sa = pmksa_cache_add(sm->pmksa, sm->pmk, pmk_len,
453                                      NULL, NULL, 0, src_addr, sm->own_addr,
454                                      sm->network_ctx, sm->key_mgmt);
455             }
456             if (!sm->cur_pmksa && pmkid &&
457                 pmksa_cache_get(sm->pmksa, src_addr, pmkid, NULL))
458             {
459                 wpa_printf( MSG_DEBUG,
460                     "RSN: the new PMK matches with the "
461                     "PMKID");
462                 abort_cached = 0;
463             } else if (sa && !sm->cur_pmksa && pmkid) {
464                 /*
465                  * It looks like the authentication server
466                  * derived mismatching MSK. This should not
467                  * really happen, but bugs happen.. There is not
468                  * much we can do here without knowing what
469                  * exactly caused the server to misbehave.
470                  */
471                 wpa_printf( MSG_INFO,
472                     "RSN: PMKID mismatch - authentication server may have derived different MSK?!");
473                 return -1;
474             }
475 
476             if (!sm->cur_pmksa)
477                 sm->cur_pmksa = sa;
478         } else {
479             wpa_printf( MSG_WARNING,
480                 "WPA: Failed to get master session key from "
481                 "EAPOL state machines - key handshake "
482                 "aborted");
483             if (sm->cur_pmksa) {
484                 wpa_printf( MSG_DEBUG,
485                     "RSN: Cancelled PMKSA caching "
486                     "attempt");
487                 sm->cur_pmksa = NULL;
488                 abort_cached = 1;
489             } else if (!abort_cached) {
490                 return -1;
491             }
492         }
493     }
494 
495     if (abort_cached && wpa_key_mgmt_wpa_ieee8021x(sm->key_mgmt) &&
496         !wpa_key_mgmt_suite_b(sm->key_mgmt) &&
497         !wpa_key_mgmt_ft(sm->key_mgmt) && sm->key_mgmt != WPA_KEY_MGMT_OSEN)
498     {
499         /* Send EAPOL-Start to trigger full EAP authentication. */
500         u8 *buf;
501         size_t buflen;
502 
503         wpa_printf( MSG_DEBUG,
504             "RSN: no PMKSA entry found - trigger "
505             "full EAP authentication");
506         buf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_START,
507                      NULL, 0, &buflen, NULL);
508         if (buf) {
509             wpa_sm_ether_send(sm, sm->bssid, ETH_P_EAPOL,
510                       buf, buflen);
511             os_free(buf);
512             return -2;
513         }
514 
515         return -1;
516     }
517 
518     return 0;
519 }
520 
521 
522 /**
523  * wpa_supplicant_send_2_of_4 - Send message 2 of WPA/RSN 4-Way Handshake
524  * @sm: Pointer to WPA state machine data from wpa_sm_init()
525  * @dst: Destination address for the frame
526  * @key: Pointer to the EAPOL-Key frame header
527  * @ver: Version bits from EAPOL-Key Key Info
528  * @nonce: Nonce value for the EAPOL-Key frame
529  * @wpa_ie: WPA/RSN IE
530  * @wpa_ie_len: Length of the WPA/RSN IE
531  * @ptk: PTK to use for keyed hash and encryption
532  * Returns: 0 on success, -1 on failure
533  */
wpa_supplicant_send_2_of_4(struct wpa_sm * sm,const unsigned char * dst,const struct wpa_eapol_key * key,int ver,const u8 * nonce,const u8 * wpa_ie,size_t wpa_ie_len,struct wpa_ptk * ptk)534 int   wpa_supplicant_send_2_of_4(struct wpa_sm *sm, const unsigned char *dst,
535                    const struct wpa_eapol_key *key,
536                    int ver, const u8 *nonce,
537                    const u8 *wpa_ie, size_t wpa_ie_len,
538                    struct wpa_ptk *ptk)
539 {
540     size_t mic_len, hdrlen, rlen;
541     struct wpa_eapol_key *reply;
542     struct wpa_eapol_key_192 *reply192;
543     u8 *rbuf, *key_mic;
544 
545     if (wpa_ie == NULL) {
546        #ifdef DEBUG_PRINT
547         wpa_printf(MSG_ERROR, "WPA: No wpa_ie set - cannot "
548                "generate msg 2/4");
549        #endif
550         return -1;
551     }
552 
553     wpa_hexdump(MSG_MSGDUMP, "WPA: WPA IE for msg 2/4\n", wpa_ie, wpa_ie_len);
554 
555     mic_len = wpa_mic_len(sm->key_mgmt);
556     hdrlen = mic_len == 24 ? sizeof(*reply192) : sizeof(*reply);
557     rbuf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_KEY,
558                   NULL, hdrlen + wpa_ie_len,
559                   &rlen, (void *) &reply);
560     if (rbuf == NULL) {
561         return -1;
562     }
563     reply192 = (struct wpa_eapol_key_192 *) reply;
564 
565     reply->type = sm->proto == WPA_PROTO_RSN ?
566         EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
567     WPA_PUT_BE16(reply->key_info,
568              ver | WPA_KEY_INFO_KEY_TYPE | WPA_KEY_INFO_MIC);
569     if (sm->proto == WPA_PROTO_RSN)
570         WPA_PUT_BE16(reply->key_length, 0);
571     else
572         memcpy(reply->key_length, key->key_length, 2);
573 
574     memcpy(reply->replay_counter, key->replay_counter,
575           WPA_REPLAY_COUNTER_LEN);
576 
577     key_mic = reply192->key_mic; /* same offset for reply and reply192 */
578     if (mic_len == 24) {
579         WPA_PUT_BE16(reply192->key_data_length, wpa_ie_len);
580         os_memcpy(reply192 + 1, wpa_ie, wpa_ie_len);
581     } else {
582         WPA_PUT_BE16(reply->key_data_length, wpa_ie_len);
583         os_memcpy(reply + 1, wpa_ie, wpa_ie_len);
584     }
585 
586     memcpy(reply->key_nonce, nonce, WPA_NONCE_LEN);
587 
588     wpa_printf(MSG_DEBUG, "WPA Send EAPOL-Key 2/4\n");
589 
590     wpa_eapol_key_send(sm, ptk->kck, ptk->kck_len, ver, dst, ETH_P_EAPOL,
591                rbuf, rlen, key_mic);
592     wpa_sm_free_eapol(rbuf);
593 
594     return 0;
595 }
596 
wpa_derive_ptk(struct wpa_sm * sm,const unsigned char * src_addr,const struct wpa_eapol_key * key,struct wpa_ptk * ptk)597 static int wpa_derive_ptk(struct wpa_sm *sm, const unsigned char *src_addr,
598               const struct wpa_eapol_key *key, struct wpa_ptk *ptk)
599 {
600     return wpa_pmk_to_ptk(sm->pmk, sm->pmk_len, "Pairwise key expansion",
601                   sm->own_addr, sm->bssid, sm->snonce,
602                   key->key_nonce, ptk, sm->key_mgmt,
603                   sm->pairwise_cipher);
604 }
605 
wpa_supplicant_process_1_of_4(struct wpa_sm * sm,const unsigned char * src_addr,const struct wpa_eapol_key * key,u16 ver,const u8 * key_data,size_t key_data_len)606 void wpa_supplicant_process_1_of_4(struct wpa_sm *sm,
607                       const unsigned char *src_addr,
608                       const struct wpa_eapol_key *key,
609                       u16 ver, const u8 *key_data,
610                       size_t key_data_len)
611 {
612     struct wpa_eapol_ie_parse ie;
613     struct wpa_ptk *ptk;
614     int res;
615 
616     wpa_sm_set_state(WPA_FIRST_HALF_4WAY_HANDSHAKE);
617 
618     wpa_printf(MSG_DEBUG, "WPA 1/4-Way Handshake\n");
619 
620     memset(&ie, 0, sizeof(ie));
621 
622     if (sm->proto == WPA_PROTO_RSN) {
623         /* RSN: msg 1/4 should contain PMKID for the selected PMK */
624         wpa_hexdump(MSG_DEBUG, "RSN: msg 1/4 key data",
625                 key_data, key_data_len);
626         if (wpa_supplicant_parse_ies(key_data, key_data_len, &ie) < 0)
627             goto failed;
628         if (ie.pmkid) {
629             wpa_hexdump(MSG_DEBUG, "RSN: PMKID from "
630                     "Authenticator", ie.pmkid, PMKID_LEN);
631         }
632     }
633     res = wpa_supplicant_get_pmk(sm, src_addr, ie.pmkid);
634 
635     if (res == -2) {
636           #ifdef DEBUG_PRINT
637          wpa_printf(MSG_DEBUG, "RSN: Do not reply to msg 1/4 - "
638                "requesting full EAP authentication");
639           #endif
640         return;
641     }
642     if (res)
643         goto failed;
644 
645     if (is_wpa2_enterprise_connection()) {
646         pmksa_cache_set_current(sm, NULL, sm->bssid, 0, 0);
647     }
648 
649     if (sm->renew_snonce) {
650         if (os_get_random(sm->snonce, WPA_NONCE_LEN)) {
651          #ifdef DEBUG_PRINT
652             wpa_printf(MSG_DEBUG, "WPA: Failed to get random data for SNonce");
653          #endif
654             goto failed;
655         }
656 
657         sm->renew_snonce = 0;
658         wpa_hexdump(MSG_DEBUG, "WPA: Renewed SNonce",
659                 sm->snonce, WPA_NONCE_LEN);
660     }
661 
662     /* Calculate PTK which will be stored as a temporary PTK until it has
663      * been verified when processing message 3/4. */
664     ptk = &sm->tptk;
665     wpa_derive_ptk(sm, src_addr, key, ptk);
666     /* Supplicant: swap tx/rx Mic keys */
667     sm->tptk_set = 1;
668     sm->ptk_set = 0;
669     sm->key_install = true;
670 
671     if (wpa_supplicant_send_2_of_4(sm, sm->bssid, key, ver, sm->snonce,
672                        sm->assoc_wpa_ie, sm->assoc_wpa_ie_len,
673                        ptk))
674         goto failed;
675 
676     memcpy(sm->anonce, key->key_nonce, WPA_NONCE_LEN);
677     return;
678 
679 failed:
680     wpa_sm_deauthenticate(sm, WLAN_REASON_UNSPECIFIED);
681 }
682 
wpa_sm_rekey_ptk(void * eloop_ctx,void * timeout_ctx)683 static void wpa_sm_rekey_ptk(void *eloop_ctx, void *timeout_ctx)
684 {
685     struct wpa_sm *sm = eloop_ctx;
686 
687    #ifdef DEBUG_PRINT
688     wpa_printf(MSG_DEBUG, "WPA: Request PTK rekeying");
689    #endif
690     wpa_sm_key_request(sm, 0, 1);
691 }
692 
693 
wpa_supplicant_install_ptk(struct wpa_sm * sm,enum key_flag key_flag)694 static int wpa_supplicant_install_ptk(struct wpa_sm *sm, enum key_flag key_flag)
695 {
696     int keylen;
697     enum wpa_alg alg;
698 
699     wpa_printf(MSG_DEBUG, "WPA: Installing PTK to the driver.\n");
700 
701     alg = wpa_cipher_to_alg(sm->pairwise_cipher);
702     keylen = wpa_cipher_key_len(sm->pairwise_cipher);
703 
704     if (alg == WIFI_WPA_ALG_NONE) {
705         wpa_printf(MSG_DEBUG, "WPA: Pairwise Cipher Suite: "
706                "NONE - do not use pairwise keys");
707         return 0;
708     }
709     if (wpa_sm_set_key(&(sm->install_ptk), alg, sm->bssid, 0, 1, (sm->install_ptk).seq, WPA_KEY_RSC_LEN,
710                        sm->ptk.tk, keylen, KEY_FLAG_PAIRWISE | key_flag) < 0) {
711         #ifdef DEBUG_PRINT
712         wpa_printf(MSG_DEBUG, "WPA: Failed to set PTK to the "
713                "driver (alg=%d keylen=%d bssid=" MACSTR ")",
714                alg, keylen, MAC2STR(sm->bssid));
715         #endif
716         return -1;
717     }
718 
719     if (sm->wpa_ptk_rekey) {
720         eloop_cancel_timeout(wpa_sm_rekey_ptk, sm, NULL);
721         eloop_register_timeout(sm->wpa_ptk_rekey, 0, wpa_sm_rekey_ptk,
722                        sm, NULL);
723     }
724 
725     return 0;
726 }
727 
wpa_supplicant_check_group_cipher(struct wpa_sm * sm,int group_cipher,int keylen,int maxkeylen,int * key_rsc_len,enum wpa_alg * alg)728 static int wpa_supplicant_check_group_cipher(struct wpa_sm *sm,
729                          int group_cipher,
730                          int keylen, int maxkeylen,
731                          int *key_rsc_len,
732                          enum wpa_alg *alg)
733 {
734     int klen;
735 
736     *alg = wpa_cipher_to_alg(group_cipher);
737     if (*alg == WIFI_WPA_ALG_NONE) {
738             wpa_printf(MSG_WARNING,
739                     "WPA: Unsupported Group Cipher %d",
740                     group_cipher);
741             return -1;
742     }
743     *key_rsc_len = 6;
744 
745     klen = wpa_cipher_key_len(group_cipher);
746     if (keylen != klen || maxkeylen < klen) {
747             wpa_printf(MSG_WARNING,
748                     "WPA: Unsupported %s Group Cipher key length %d (%d)",
749                     wpa_cipher_txt(group_cipher), keylen, maxkeylen);
750             return -1;
751     }
752     return 0;
753 }
754 
wpa_supplicant_key_neg_complete(struct wpa_sm * sm,const u8 * addr,int secure)755 void   wpa_supplicant_key_neg_complete(struct wpa_sm *sm,
756                         const u8 *addr, int secure)
757 {
758 #ifdef DEBUG_PRINT
759     wpa_printf(MSG_DEBUG, "WPA: Key negotiation completed with "
760           MACSTR " [PTK=%s GTK=%s]\n", MAC2STR(addr),
761           wpa_cipher_txt(sm->pairwise_cipher),
762           wpa_cipher_txt(sm->group_cipher));
763 #endif
764     wpa_sm_cancel_auth_timeout(sm);
765     wpa_sm_set_state(WPA_COMPLETED);
766 
767     sm->wpa_neg_complete();
768 
769     if (secure) {
770         wpa_sm_mlme_setprotection(
771             sm, addr, MLME_SETPROTECTION_PROTECT_TYPE_RX_TX,
772             MLME_SETPROTECTION_KEY_TYPE_PAIRWISE);
773 
774         if (wpa_key_mgmt_wpa_psk(sm->key_mgmt))
775             eapol_sm_notify_eap_success(TRUE);
776         /*
777          * Start preauthentication after a short wait to avoid a
778          * possible race condition between the data receive and key
779          * configuration after the 4-Way Handshake. This increases the
780          * likelyhood of the first preauth EAPOL-Start frame getting to
781          * the target AP.
782          */
783     }
784 
785 }
786 
wpa_supplicant_install_gtk(struct wpa_sm * sm,struct wpa_gtk_data * gd)787 static int wpa_supplicant_install_gtk(struct wpa_sm *sm,
788                       struct wpa_gtk_data *gd)
789 {
790     u8 *_gtk = gd->gtk;
791     u8 gtk_buf[32];
792     u8 *key_rsc=(sm->install_gtk).seq;
793 
794     wpa_hexdump(MSG_DEBUG, "WPA: Group Key", gd->gtk, gd->gtk_len);
795 
796     /* Detect possible key reinstallation */
797     if (wpa_supplicant_gtk_in_use(sm, &(sm->gd))) {
798             wpa_printf(MSG_DEBUG,
799                     "WPA: Not reinstalling already in-use GTK to the driver (keyidx=%d tx=%d len=%d)",
800                     gd->keyidx, gd->tx, gd->gtk_len);
801             return 0;
802     }
803     wpa_printf(MSG_DEBUG, "WPA: Installing GTK to the driver "
804            "(keyidx=%d tx=%d len=%d).\n", gd->keyidx, gd->tx,
805            gd->gtk_len);
806 
807     wpa_hexdump(MSG_DEBUG, "WPA: RSC", key_rsc, gd->key_rsc_len);
808     if (sm->group_cipher == WPA_CIPHER_TKIP) {
809         /* Swap Tx/Rx keys for Michael MIC */
810         memcpy(gtk_buf, gd->gtk, 16);
811         memcpy(gtk_buf + 16, gd->gtk + 16, 8);
812         memcpy(gtk_buf + 24, gd->gtk + 24, 8);
813         _gtk = gtk_buf;
814     }
815     if (sm->pairwise_cipher == WPA_CIPHER_NONE) {
816         if (wpa_sm_set_key(&(sm->install_gtk), gd->alg,
817                    sm->bssid, //(u8 *) "\xff\xff\xff\xff\xff\xff",
818                    gd->keyidx, 1, key_rsc, gd->key_rsc_len,
819                    _gtk, gd->gtk_len, (KEY_FLAG_GROUP | KEY_FLAG_RX | KEY_FLAG_TX)) < 0) {
820             wpa_printf(MSG_DEBUG, "WPA: Failed to set "
821                    "GTK to the driver (Group only).");
822             return -1;
823         }
824     } else if (wpa_sm_set_key(&(sm->install_gtk), gd->alg,
825                   sm->bssid, //(u8 *) "\xff\xff\xff\xff\xff\xff",
826                   gd->keyidx, gd->tx, key_rsc, gd->key_rsc_len,
827                   _gtk, gd->gtk_len, KEY_FLAG_GROUP | KEY_FLAG_RX) < 0) {
828         wpa_printf(MSG_DEBUG, "WPA: Failed to set GTK to "
829                "the driver (alg=%d keylen=%d keyidx=%d)",
830                gd->alg, gd->gtk_len, gd->keyidx);
831         return -1;
832     }
833 
834     return 0;
835 }
836 
wpa_supplicant_gtk_in_use(struct wpa_sm * sm,struct wpa_gtk_data * gd)837 static bool wpa_supplicant_gtk_in_use(struct wpa_sm *sm, struct wpa_gtk_data *gd)
838 {
839     u8 *_gtk = gd->gtk;
840     u8 gtk_buf[32];
841     u8 gtk_get[32] = {0};
842     u8 ifx;
843     int alg;
844     u8 bssid[6];
845     int keyidx = gd->keyidx;
846 
847     #ifdef DEBUG_PRINT
848     wpa_printf(MSG_DEBUG, "WPA: Judge GTK: (keyidx=%d len=%d).", gd->keyidx, gd->gtk_len);
849     #endif
850 
851     if (sm->group_cipher == WPA_CIPHER_TKIP) {
852         /* Swap Tx/Rx keys for Michael MIC */
853         memcpy(gtk_buf, gd->gtk, 16);
854         memcpy(gtk_buf + 16, gd->gtk + 16, 8);
855         memcpy(gtk_buf + 24, gd->gtk + 24, 8);
856         _gtk = gtk_buf;
857     }
858 
859     if (wpa_sm_get_key(&ifx, &alg, bssid, &keyidx, gtk_get, gd->gtk_len, KEY_FLAG_GROUP) == 0) {
860         if (ifx == 0 && alg == gd->alg && memcmp(bssid, sm->bssid, ETH_ALEN) == 0 &&
861                 memcmp(_gtk, gtk_get, gd->gtk_len) == 0) {
862             wpa_printf(MSG_DEBUG, "GTK %d is already in use, it may be an attack, ignore it.", gd->keyidx);
863             return true;
864         }
865     }
866 
867     return false;
868 }
869 
wpa_supplicant_gtk_tx_bit_workaround(const struct wpa_sm * sm,int tx)870 int wpa_supplicant_gtk_tx_bit_workaround(const struct wpa_sm *sm,
871                         int tx)
872 {
873     if (tx && sm->pairwise_cipher != WPA_CIPHER_NONE) {
874         /* Ignore Tx bit for GTK if a pairwise key is used. One AP
875          * seemed to set this bit (incorrectly, since Tx is only when
876          * doing Group Key only APs) and without this workaround, the
877          * data connection does not work because wpa_supplicant
878          * configured non-zero keyidx to be used for unicast. */
879         #ifdef DEBUG_PRINT
880         wpa_printf(MSG_DEBUG, "WPA: Tx bit set for GTK, but pairwise "
881                "keys are used - ignore Tx bit");
882         #endif
883         return 0;
884     }
885     return tx;
886 }
887 
wpa_supplicant_pairwise_gtk(struct wpa_sm * sm,const u8 * gtk,size_t gtk_len,int key_info)888 int wpa_supplicant_pairwise_gtk(struct wpa_sm *sm,
889                        const u8 *gtk, size_t gtk_len,
890                        int key_info)
891 {
892     struct wpa_gtk_data *gd=&(sm->gd);
893 
894     /*
895      * IEEE Std 802.11i-2004 - 8.5.2 EAPOL-Key frames - Figure 43x
896      * GTK KDE format:
897      * KeyID[bits 0-1], Tx [bit 2], Reserved [bits 3-7]
898      * Reserved [bits 0-7]
899      * GTK
900      */
901 
902     memset(gd, 0, sizeof(struct wpa_gtk_data));
903     wpa_hexdump(MSG_DEBUG, "RSN: received GTK in pairwise handshake",
904             gtk, gtk_len);
905 
906     if (gtk_len < 2 || gtk_len - 2 > sizeof(gd->gtk))
907         return -1;
908 
909     gd->keyidx = gtk[0] & 0x3;
910     gd->tx = wpa_supplicant_gtk_tx_bit_workaround(sm,
911                              !!(gtk[0] & BIT(2)));
912     gtk += 2;
913     gtk_len -= 2;
914 
915     memcpy(gd->gtk, gtk, gtk_len);
916     gd->gtk_len = gtk_len;
917 
918     if (wpa_supplicant_check_group_cipher(sm, sm->group_cipher,
919                           gtk_len, gtk_len,
920                           &(gd->key_rsc_len), &(gd->alg))) {
921             #ifdef DEBUG_PRINT
922         wpa_printf(MSG_DEBUG, "RSN: Failed to install GTK");
923         #endif
924         return -1;
925     }
926     return 0;
927 }
928 
929 #ifdef DEBUG_PRINT
wpa_report_ie_mismatch(struct wpa_sm * sm,const char * reason,const u8 * src_addr,const u8 * wpa_ie,size_t wpa_ie_len,const u8 * rsn_ie,size_t rsn_ie_len)930 void wpa_report_ie_mismatch(struct wpa_sm *sm,
931                    const char *reason, const u8 *src_addr,
932                    const u8 *wpa_ie, size_t wpa_ie_len,
933                    const u8 *rsn_ie, size_t rsn_ie_len)
934 #else
935 void wpa_report_ie_mismatch(struct wpa_sm *sm, const u8 *src_addr,
936                    const u8 *wpa_ie, size_t wpa_ie_len,
937                    const u8 *rsn_ie, size_t rsn_ie_len)
938 #endif
939 {
940     #ifdef DEBUG_PRINT
941     wpa_printf(MSG_DEBUG, "WPA: %s (src=" MACSTR ")",
942         reason, MAC2STR(src_addr));
943     #endif
944     if (sm->ap_wpa_ie) {
945         wpa_hexdump(MSG_INFO, "WPA: WPA IE in Beacon/ProbeResp",
946                 sm->ap_wpa_ie, sm->ap_wpa_ie_len);
947     }
948     if (wpa_ie) {
949         if (!sm->ap_wpa_ie) {
950             #ifdef DEBUG_PRINT
951             wpa_printf(MSG_DEBUG, "WPA: No WPA IE in "
952                    "Beacon/ProbeResp");
953             #endif
954         }
955         wpa_hexdump(MSG_INFO, "WPA: WPA IE in 3/4 msg",
956                 wpa_ie, wpa_ie_len);
957     }
958 
959     if (sm->ap_rsn_ie) {
960         wpa_hexdump(MSG_INFO, "WPA: RSN IE in Beacon/ProbeResp",
961                 sm->ap_rsn_ie, sm->ap_rsn_ie_len);
962     }
963     if (rsn_ie) {
964         if (!sm->ap_rsn_ie) {
965             #ifdef DEBUG_PRINT
966             wpa_printf(MSG_DEBUG, "WPA: No RSN IE in "
967                    "Beacon/ProbeResp");
968             #endif
969         }
970         wpa_hexdump(MSG_INFO, "WPA: RSN IE in 3/4 msg",
971                 rsn_ie, rsn_ie_len);
972     }
973 
974     wpa_sm_disassociate(sm, WLAN_REASON_IE_IN_4WAY_DIFFERS);
975 }
976 
ieee80211w_set_keys(struct wpa_sm * sm,struct wpa_eapol_ie_parse * ie)977 static int ieee80211w_set_keys(struct wpa_sm *sm,
978                    struct wpa_eapol_ie_parse *ie)
979 {
980 #ifdef CONFIG_IEEE80211W
981     size_t len;
982 
983     if (!wpa_cipher_valid_mgmt_group(sm->mgmt_group_cipher))
984         return 0;
985 
986     if (ie->igtk) {
987         const wifi_wpa_igtk_t *igtk;
988         uint16_t keyidx;
989 #define WPA_IGTK_KDE_PREFIX_LEN (2 + 6)
990         len = wpa_cipher_key_len(sm->mgmt_group_cipher);
991         if (ie->igtk_len != WPA_IGTK_KDE_PREFIX_LEN + len) {
992             return -1;
993         }
994 
995         igtk = (const wifi_wpa_igtk_t*)ie->igtk;
996         keyidx = WPA_GET_LE16(igtk->keyid);
997         if (keyidx > 4095) {
998             return -1;
999         }
1000         wpa_printf(MSG_DEBUG, "WPA: Installing IGTK to the driver.\n");
1001         return esp_wifi_set_igtk_internal(WIFI_IF_STA, igtk);
1002     }
1003 #endif
1004     return 0;
1005 }
1006 
wpa_supplicant_validate_ie(struct wpa_sm * sm,const unsigned char * src_addr,struct wpa_eapol_ie_parse * ie)1007 static int wpa_supplicant_validate_ie(struct wpa_sm *sm,
1008                       const unsigned char *src_addr,
1009                       struct wpa_eapol_ie_parse *ie)
1010 {
1011     if (ie->wpa_ie == NULL && ie->rsn_ie == NULL &&
1012         (sm->ap_wpa_ie || sm->ap_rsn_ie)) {
1013 #ifdef DEBUG_PRINT
1014         wpa_report_ie_mismatch(sm, "IE in 3/4 msg does not match "
1015                        "with IE in Beacon/ProbeResp (no IE?)",
1016                        src_addr, ie->wpa_ie, ie->wpa_ie_len,
1017                        ie->rsn_ie, ie->rsn_ie_len);
1018 #else
1019         wpa_report_ie_mismatch(sm,
1020                        src_addr, ie->wpa_ie, ie->wpa_ie_len,
1021                        ie->rsn_ie, ie->rsn_ie_len);
1022 #endif
1023         return -1;
1024     }
1025 
1026     if ((ie->wpa_ie && sm->ap_wpa_ie &&
1027          (ie->wpa_ie_len != sm->ap_wpa_ie_len ||
1028          memcmp(ie->wpa_ie, sm->ap_wpa_ie, ie->wpa_ie_len) != 0)) ||
1029         (ie->rsn_ie && sm->ap_rsn_ie &&
1030          wpa_compare_rsn_ie(wpa_key_mgmt_ft(sm->key_mgmt),
1031                 sm->ap_rsn_ie, sm->ap_rsn_ie_len,
1032                 ie->rsn_ie, ie->rsn_ie_len))) {
1033 #ifdef DEBUG_PRINT
1034         wpa_report_ie_mismatch(sm, "IE in 3/4 msg does not match "
1035                        "with IE in Beacon/ProbeResp",
1036                        src_addr, ie->wpa_ie, ie->wpa_ie_len,
1037                        ie->rsn_ie, ie->rsn_ie_len);
1038 #else
1039         wpa_report_ie_mismatch(sm,
1040                        src_addr, ie->wpa_ie, ie->wpa_ie_len,
1041                        ie->rsn_ie, ie->rsn_ie_len);
1042 #endif
1043         return -1;
1044     }
1045 
1046     if (sm->proto == WPA_PROTO_WPA &&
1047         ie->rsn_ie && sm->ap_rsn_ie == NULL && sm->rsn_enabled) {
1048 #ifdef DEBUG_PRINT
1049         wpa_report_ie_mismatch(sm, "Possible downgrade attack "
1050                        "detected - RSN was enabled and RSN IE "
1051                        "was in msg 3/4, but not in "
1052                        "Beacon/ProbeResp",
1053                        src_addr, ie->wpa_ie, ie->wpa_ie_len,
1054                        ie->rsn_ie, ie->rsn_ie_len);
1055 #else
1056         wpa_report_ie_mismatch(sm,
1057                                src_addr, ie->wpa_ie, ie->wpa_ie_len,
1058                                ie->rsn_ie, ie->rsn_ie_len);
1059 #endif
1060         return -1;
1061     }
1062 
1063     return 0;
1064 }
1065 
1066 /**
1067  * wpa_supplicant_send_4_of_4 - Send message 4 of WPA/RSN 4-Way Handshake
1068  * @sm: Pointer to WPA state machine data from wpa_sm_init()
1069  * @dst: Destination address for the frame
1070  * @key: Pointer to the EAPOL-Key frame header
1071  * @ver: Version bits from EAPOL-Key Key Info
1072  * @key_info: Key Info
1073  * @ptk: PTK to use for keyed hash and encryption
1074  * Returns: 0 on success, -1 on failure
1075  */
wpa_supplicant_send_4_of_4(struct wpa_sm * sm,const unsigned char * dst,const struct wpa_eapol_key * key,u16 ver,u16 key_info,struct wpa_ptk * ptk)1076 static int wpa_supplicant_send_4_of_4(struct wpa_sm *sm, const unsigned char *dst,
1077                    const struct wpa_eapol_key *key,
1078                    u16 ver, u16 key_info,
1079                    struct wpa_ptk *ptk)
1080 {
1081     size_t mic_len, hdrlen, rlen;
1082     struct wpa_eapol_key *reply;
1083     struct wpa_eapol_key_192 *reply192;
1084     u8 *rbuf, *key_mic;
1085 
1086     mic_len = wpa_mic_len(sm->key_mgmt);
1087     hdrlen = mic_len == 24 ? sizeof(*reply192) : sizeof(*reply);
1088 
1089     rbuf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_KEY, NULL,
1090                   hdrlen,
1091                   &rlen, (void *) &reply);
1092     if (rbuf == NULL)
1093         return -1;
1094 
1095     sm->txcb_flags |= WPA_4_4_HANDSHAKE_BIT;
1096     wpa_printf(MSG_DEBUG, "tx 4/4 txcb_flags=%d\n", sm->txcb_flags);
1097 
1098     reply192 = (struct wpa_eapol_key_192 *) reply;
1099     reply->type = sm->proto == WPA_PROTO_RSN ?
1100         EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
1101     key_info &= WPA_KEY_INFO_SECURE;
1102     key_info |= ver | WPA_KEY_INFO_KEY_TYPE | WPA_KEY_INFO_MIC;
1103     WPA_PUT_BE16(reply->key_info, key_info);
1104     if (sm->proto == WPA_PROTO_RSN)
1105         WPA_PUT_BE16(reply->key_length, 0);
1106     else
1107         memcpy(reply->key_length, key->key_length, 2);
1108     memcpy(reply->replay_counter, key->replay_counter,
1109           WPA_REPLAY_COUNTER_LEN);
1110 
1111     key_mic = reply192->key_mic; /* same offset for reply and reply192 */
1112     if (mic_len == 24)
1113         WPA_PUT_BE16(reply192->key_data_length, 0);
1114     else
1115         WPA_PUT_BE16(reply->key_data_length, 0);
1116 
1117     wpa_printf(MSG_DEBUG, "WPA Send EAPOL-Key 4/4\n");
1118     wpa_eapol_key_send(sm, ptk->kck, ptk->kck_len, ver, dst, ETH_P_EAPOL,
1119                rbuf, rlen, key_mic);
1120     wpa_sm_free_eapol(rbuf);
1121 
1122     return 0;
1123 }
1124 
wpa_sm_set_seq(struct wpa_sm * sm,struct wpa_eapol_key * key,u8 isptk)1125 static void wpa_sm_set_seq(struct wpa_sm *sm, struct wpa_eapol_key *key, u8 isptk)
1126 {
1127     u8 *key_rsc, *seq;
1128     u8 null_rsc[WPA_KEY_RSC_LEN];
1129 
1130     os_bzero(null_rsc, WPA_KEY_RSC_LEN);
1131 
1132     if (sm->proto == WPA_PROTO_RSN) {
1133         key_rsc = null_rsc;
1134     } else {
1135         key_rsc = key->key_rsc;
1136         wpa_hexdump(MSG_DEBUG, "WPA: RSC", key_rsc, WPA_KEY_RSC_LEN);
1137     }
1138 
1139     seq=(isptk) ? (sm->install_ptk).seq : (sm->install_gtk).seq;
1140     memcpy(seq, key_rsc, WPA_KEY_RSC_LEN);
1141 }
1142 
wpa_supplicant_process_3_of_4(struct wpa_sm * sm,struct wpa_eapol_key * key,u16 ver,const u8 * key_data,size_t key_data_len)1143 static void wpa_supplicant_process_3_of_4(struct wpa_sm *sm,
1144                       struct wpa_eapol_key *key,
1145                       u16 ver, const u8 *key_data,
1146                       size_t key_data_len)
1147 {
1148     u16 key_info, keylen;
1149     struct wpa_eapol_ie_parse ie;
1150 
1151     wpa_sm_set_state(WPA_LAST_HALF_4WAY_HANDSHAKE);
1152     wpa_printf(MSG_DEBUG, "WPA 3/4-Way Handshake\n");
1153 
1154     key_info = WPA_GET_BE16(key->key_info);
1155 
1156     if (wpa_supplicant_parse_ies(key_data, key_data_len, &ie) < 0)
1157         goto failed;
1158     if (wpa_supplicant_validate_ie(sm, sm->bssid, &ie) < 0)
1159         goto failed;
1160 
1161     if (ie.gtk && !(key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
1162         #ifdef DEBUG_PRINT
1163         wpa_printf(MSG_DEBUG, "WPA: GTK IE in unencrypted key data");
1164         #endif
1165         goto failed;
1166     }
1167 
1168     wpa_hexdump(MSG_DEBUG, "WPA: IE KeyData", key_data, key_data_len);
1169     if (memcmp(sm->anonce, key->key_nonce, WPA_NONCE_LEN) != 0) {
1170        #ifdef DEBUG_PRINT
1171         wpa_printf(MSG_DEBUG, "WPA: ANonce from message 1 of 4-Way "
1172                "Handshake differs from 3 of 4-Way Handshake - drop"
1173                " packet (src=" MACSTR ")", MAC2STR(sm->bssid));
1174      #endif
1175         goto failed;
1176     }
1177 
1178     keylen = WPA_GET_BE16(key->key_length);
1179     switch (sm->pairwise_cipher) {
1180     case WPA_CIPHER_CCMP:
1181         if (keylen != 16) {
1182             #ifdef DEBUG_PRINT
1183             wpa_printf(MSG_DEBUG, "WPA: Invalid CCMP key length "
1184                    "%d (src=" MACSTR ")",
1185                    keylen, MAC2STR(sm->bssid));
1186             #endif
1187             goto failed;
1188         }
1189         break;
1190     case WPA_CIPHER_TKIP:
1191         if (keylen != 32) {
1192             #ifdef DEBUG_PRINT
1193             wpa_printf(MSG_DEBUG, "WPA: Invalid TKIP key length "
1194                    "%d (src=" MACSTR ")",
1195                    keylen, MAC2STR(sm->bssid));
1196             #endif
1197             goto failed;
1198         }
1199         break;
1200     }
1201 
1202 
1203     /* SNonce was successfully used in msg 3/4, so mark it to be renewed
1204      * for the next 4-Way Handshake. If msg 3 is received again, the old
1205      * SNonce will still be used to avoid changing PTK. */
1206     sm->renew_snonce = 1;
1207 
1208     /*ready for txcallback , set seq and set txcallback param*/
1209     wpa_sm_set_seq(sm, key, 1);
1210     sm->key_info=key_info;
1211     (sm->gd).gtk_len=0; //used as flag if gtk is installed in callback
1212     if (ie.gtk) {
1213         wpa_sm_set_seq(sm, key, 0);
1214            if (wpa_supplicant_pairwise_gtk(sm,
1215                     ie.gtk, ie.gtk_len, key_info) < 0) {
1216         #ifdef DEBUG_PRINT
1217         wpa_printf(MSG_DEBUG, "RSN: Failed to configure GTK");
1218         #endif
1219         goto failed;
1220         }
1221     }
1222 
1223     if (sm->pmf_cfg.capable && ieee80211w_set_keys(sm, &ie) < 0) {
1224         #ifdef DEBUG_PRINT
1225         wpa_printf(MSG_DEBUG, "RSN: Failed to configure IGTK");
1226         #endif
1227         goto failed;
1228     }
1229 
1230     if (sm->key_install && sm->key_info & WPA_KEY_INFO_INSTALL) {
1231         wpa_supplicant_install_ptk(sm, KEY_FLAG_RX);
1232     }
1233     /*after txover, callback will continue run remain task*/
1234     if (wpa_supplicant_send_4_of_4(sm, sm->bssid, key, ver, key_info,
1235                        &sm->ptk)) {
1236         goto failed;
1237     }
1238 
1239     return;
1240 
1241 failed:
1242     wpa_sm_deauthenticate(sm, WLAN_REASON_UNSPECIFIED);
1243 }
1244 
wpa_supplicant_activate_ptk(struct wpa_sm * sm)1245 static int wpa_supplicant_activate_ptk(struct wpa_sm *sm)
1246 {
1247     int keylen;
1248     enum wpa_alg alg;
1249 
1250     alg = wpa_cipher_to_alg(sm->pairwise_cipher);
1251     keylen = wpa_cipher_key_len(sm->pairwise_cipher);
1252 
1253     if (alg == WIFI_WPA_ALG_NONE) {
1254         wpa_printf(MSG_DEBUG, "WPA: Pairwise Cipher Suite: "
1255                "NONE - do not use pairwise keys");
1256         return 0;
1257     }
1258 
1259     wpa_printf(MSG_DEBUG,
1260             "WPA: Activate PTK bssid=" MACSTR ")",
1261             MAC2STR(sm->bssid));
1262 
1263     if (wpa_sm_set_key(&(sm->install_ptk), alg, sm->bssid, 0, 1, (sm->install_ptk).seq,
1264                        WPA_KEY_RSC_LEN, sm->ptk.tk, keylen,
1265                        (KEY_FLAG_MODIFY | KEY_FLAG_PAIRWISE | KEY_FLAG_RX | KEY_FLAG_TX)) < 0) {
1266             wpa_printf(MSG_WARNING,
1267                     "WPA: Failed to activate PTK for TX (idx=%d bssid="
1268                     MACSTR ")", 0, MAC2STR(sm->bssid));
1269             return -1;
1270     }
1271     return 0;
1272 }
1273 
wpa_supplicant_send_4_of_4_txcallback(struct wpa_sm * sm)1274 static int wpa_supplicant_send_4_of_4_txcallback(struct wpa_sm *sm)
1275 {
1276        u16 key_info=sm->key_info;
1277 
1278     if (sm->key_install && key_info & WPA_KEY_INFO_INSTALL) {
1279         if (wpa_supplicant_activate_ptk(sm))
1280             goto failed;
1281     }
1282     else if (sm->key_install == false) {
1283         wpa_printf(MSG_DEBUG, "PTK has been installed, it may be an attack, ignor it.");
1284     }
1285 
1286     wpa_sm_set_state(WPA_GROUP_HANDSHAKE);
1287 
1288     if ((sm->gd).gtk_len) {
1289         if (sm->key_install) {
1290             if (wpa_supplicant_install_gtk(sm, &(sm->gd)))
1291                 goto failed;
1292         }
1293         else {
1294             wpa_printf(MSG_DEBUG, "GTK has been installed, it may be an attack, ignor it.");
1295         }
1296         wpa_supplicant_key_neg_complete(sm, sm->bssid,
1297                     key_info & WPA_KEY_INFO_SECURE);
1298     }
1299 
1300     if (key_info & WPA_KEY_INFO_SECURE) {
1301         wpa_sm_mlme_setprotection(
1302             sm, sm->bssid, MLME_SETPROTECTION_PROTECT_TYPE_RX,
1303             MLME_SETPROTECTION_KEY_TYPE_PAIRWISE);
1304     }
1305 
1306     sm->key_install = false;
1307 
1308 #if defined(CONFIG_SUITEB192) || defined (CONFIG_SUITEB)
1309     /* Add PMKSA cache entry for Suite B AKMs here since PMKID can be
1310      * calculated only after KCK has been derived. Though, do not replace an
1311      * existing PMKSA entry after each 4-way handshake (i.e., new KCK/PMKID)
1312      * to avoid unnecessary changes of PMKID while continuing to use the
1313      * same PMK. */
1314     if (sm->proto == WPA_PROTO_RSN && wpa_key_mgmt_suite_b(sm->key_mgmt) &&
1315         !sm->cur_pmksa) {
1316         struct rsn_pmksa_cache_entry *sa;
1317 
1318         sa = pmksa_cache_add(sm->pmksa, sm->pmk, sm->pmk_len, NULL,
1319                              sm->ptk.kck, sm->ptk.kck_len,
1320                              sm->bssid, sm->own_addr,
1321                              sm->network_ctx, sm->key_mgmt);
1322         if (!sm->cur_pmksa)
1323             sm->cur_pmksa = sa;
1324     }
1325 #endif
1326 
1327     return 0;
1328 
1329 failed:
1330        return WLAN_REASON_UNSPECIFIED;
1331 }
1332 
wpa_supplicant_process_1_of_2_rsn(struct wpa_sm * sm,const u8 * keydata,size_t keydatalen,u16 key_info,struct wpa_gtk_data * gd)1333 static int wpa_supplicant_process_1_of_2_rsn(struct wpa_sm *sm,
1334                          const u8 *keydata,
1335                          size_t keydatalen,
1336                          u16 key_info,
1337                          struct wpa_gtk_data *gd)
1338 {
1339     int maxkeylen;
1340     struct wpa_eapol_ie_parse ie;
1341 
1342     wpa_hexdump(MSG_DEBUG, "RSN: msg 1/2 key data", keydata, keydatalen);
1343     wpa_supplicant_parse_ies(keydata, keydatalen, &ie);
1344     if (ie.gtk && !(key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
1345         #ifdef DEBUG_PRINT
1346         wpa_printf(MSG_DEBUG, "WPA: GTK IE in unencrypted key data");
1347       #endif
1348         return -1;
1349     }
1350     if (ie.gtk == NULL) {
1351          #ifdef DEBUG_PRINT
1352         wpa_printf(MSG_DEBUG, "WPA: No GTK IE in Group Key msg 1/2");
1353        #endif
1354         return -1;
1355     }
1356     maxkeylen = gd->gtk_len = ie.gtk_len - 2;
1357 
1358     if (wpa_supplicant_check_group_cipher(sm, sm->group_cipher,
1359                           gd->gtk_len, maxkeylen,
1360                           &gd->key_rsc_len, &gd->alg))
1361         return -1;
1362 
1363     wpa_hexdump(MSG_DEBUG, "RSN: received GTK in group key handshake",
1364             ie.gtk, ie.gtk_len);
1365     gd->keyidx = ie.gtk[0] & 0x3;
1366     gd->tx = wpa_supplicant_gtk_tx_bit_workaround(sm,
1367                               !!(ie.gtk[0] & BIT(2)));
1368     if (ie.gtk_len - 2 > sizeof(gd->gtk)) {
1369          #ifdef DEBUG_PRINT
1370         wpa_printf(MSG_DEBUG, "RSN: Too long GTK in GTK IE "
1371                "(len=%lu)", (unsigned long) ie.gtk_len - 2);
1372       #endif
1373         return -1;
1374     }
1375     memcpy(gd->gtk, ie.gtk + 2, ie.gtk_len - 2);
1376 
1377     if (ieee80211w_set_keys(sm, &ie) < 0)
1378     {
1379         #ifdef DEBUG_PRINT
1380         wpa_printf(MSG_DEBUG, "RSN: Failed to configure IGTK");
1381             #endif
1382     }
1383     return 0;
1384 }
1385 
wpa_supplicant_process_1_of_2_wpa(struct wpa_sm * sm,const struct wpa_eapol_key * key,const u8 * key_data,size_t key_data_len,u16 key_info,u16 ver,struct wpa_gtk_data * gd)1386 static int wpa_supplicant_process_1_of_2_wpa(struct wpa_sm *sm,
1387                          const struct wpa_eapol_key *key,
1388                          const u8 *key_data,
1389                          size_t key_data_len, u16 key_info,
1390                          u16 ver, struct wpa_gtk_data *gd)
1391 {
1392     size_t maxkeylen;
1393     u8 ek[32];
1394 
1395     gd->gtk_len = WPA_GET_BE16(key->key_length);
1396     maxkeylen = key_data_len;
1397     if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1398         if (maxkeylen < 8) {
1399               #ifdef DEBUG_PRINT
1400             wpa_printf(MSG_DEBUG, "WPA: Too short maxkeylen (%lu)",
1401                    (unsigned long) maxkeylen);
1402         #endif
1403             return -1;
1404         }
1405         maxkeylen -= 8;
1406     }
1407 
1408     if (wpa_supplicant_check_group_cipher(sm, sm->group_cipher,
1409                           gd->gtk_len, maxkeylen,
1410                           &gd->key_rsc_len, &gd->alg))
1411         return -1;
1412 
1413     gd->keyidx = (key_info & WPA_KEY_INFO_KEY_INDEX_MASK) >>
1414         WPA_KEY_INFO_KEY_INDEX_SHIFT;
1415     if (ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 && sm->ptk.kek_len == 16) {
1416         os_memcpy(ek, key->key_iv, 16);
1417         os_memcpy(ek + 16, sm->ptk.kek, sm->ptk.kek_len);
1418         if (key_data_len > sizeof(gd->gtk)) {
1419             #ifdef DEBUG_PRINT
1420             wpa_printf(MSG_DEBUG, "WPA: RC4 key data "
1421                    "too long (%lu)",
1422                 (unsigned long) key_data_len);
1423             #endif
1424             return -1;
1425         }
1426         os_memcpy(gd->gtk, key_data, key_data_len);
1427         if (rc4_skip(ek, 32, 256, gd->gtk, key_data_len)) {
1428             #ifdef DEBUG_PRINT
1429             wpa_printf(MSG_DEBUG, "WPA: RC4 failed");
1430             #endif
1431             return -1;
1432         }
1433     } else if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1434         if (maxkeylen % 8) {
1435             #ifdef DEBUG_PRINT
1436             wpa_printf(MSG_DEBUG,
1437                 "WPA: Unsupported AES-WRAP len %lu",
1438                 (unsigned long) maxkeylen);
1439              #endif
1440             return -1;
1441         }
1442         if (maxkeylen > sizeof(gd->gtk)) {
1443                  #ifdef DEBUG_PRINT
1444             wpa_printf(MSG_DEBUG, "WPA: AES-WRAP key data "
1445                    "too long (keydatalen=%lu maxkeylen=%lu)",
1446                 (unsigned long) key_data_len,
1447                    (unsigned long) maxkeylen);
1448             #endif
1449             return -1;
1450         }
1451         if (aes_unwrap(sm->ptk.kek, sm->ptk.kek_len, maxkeylen / 8, key_data, gd->gtk)) {
1452             #ifdef DEBUG_PRINT
1453             wpa_printf(MSG_DEBUG, "WPA: AES unwrap "
1454                 "failed - could not decrypt GTK");
1455             #endif
1456             return -1;
1457         }
1458     } else {
1459         #ifdef DEBUG_PRINT
1460         wpa_printf(MSG_DEBUG, "WPA: Unsupported key_info type %d",
1461                ver);
1462          #endif
1463         return -1;
1464     }
1465     gd->tx = wpa_supplicant_gtk_tx_bit_workaround(
1466         sm, !!(key_info & WPA_KEY_INFO_TXRX));
1467 
1468     return 0;
1469 }
1470 
wpa_supplicant_send_2_of_2(struct wpa_sm * sm,const struct wpa_eapol_key * key,int ver,u16 key_info)1471 static int wpa_supplicant_send_2_of_2(struct wpa_sm *sm,
1472                       const struct wpa_eapol_key *key,
1473                       int ver, u16 key_info)
1474 {
1475     size_t mic_len, hdrlen, rlen;
1476     struct wpa_eapol_key *reply;
1477     struct wpa_eapol_key_192 *reply192;
1478     u8 *rbuf, *key_mic;
1479 
1480     mic_len = wpa_mic_len(sm->key_mgmt);
1481     hdrlen = mic_len == 24 ? sizeof(*reply192) : sizeof(*reply);
1482 
1483     rbuf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_KEY, NULL,
1484                               hdrlen, &rlen, (void *) &reply);
1485     if (rbuf == NULL)
1486         return -1;
1487 
1488     sm->txcb_flags |= WPA_GROUP_HANDSHAKE_BIT;
1489     wpa_printf(MSG_DEBUG, "2/2 txcb_flags=%d\n", sm->txcb_flags);
1490 
1491     reply192 = (struct wpa_eapol_key_192 *) reply;
1492     reply->type = sm->proto == WPA_PROTO_RSN ?
1493         EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
1494     key_info &= WPA_KEY_INFO_KEY_INDEX_MASK;
1495     key_info |= ver | WPA_KEY_INFO_MIC | WPA_KEY_INFO_SECURE;
1496     WPA_PUT_BE16(reply->key_info, key_info);
1497     if (sm->proto == WPA_PROTO_RSN)
1498         WPA_PUT_BE16(reply->key_length, 0);
1499     else
1500         memcpy(reply->key_length, key->key_length, 2);
1501     memcpy(reply->replay_counter, key->replay_counter,
1502           WPA_REPLAY_COUNTER_LEN);
1503 
1504     key_mic = reply192->key_mic; /* same offset for reply and reply192 */
1505     if (mic_len == 24)
1506         WPA_PUT_BE16(reply192->key_data_length, 0);
1507     else
1508         WPA_PUT_BE16(reply->key_data_length, 0);
1509 
1510     wpa_printf(MSG_DEBUG, "WPA Send 2/2 Group key\n");
1511 
1512     wpa_eapol_key_send(sm, sm->ptk.kck, sm->ptk.kck_len, ver, sm->bssid, ETH_P_EAPOL,
1513                rbuf, rlen, key_mic);
1514     wpa_sm_free_eapol(rbuf);
1515 
1516     return 0;
1517 }
1518 
wpa_supplicant_process_1_of_2(struct wpa_sm * sm,const unsigned char * src_addr,struct wpa_eapol_key * key,const u8 * key_data,size_t key_data_len,u16 ver)1519 static void wpa_supplicant_process_1_of_2(struct wpa_sm *sm,
1520                       const unsigned char *src_addr,
1521                       struct wpa_eapol_key *key,
1522                       const u8 *key_data,
1523                       size_t key_data_len, u16 ver)
1524 {
1525     u16 key_info;
1526     int  ret;
1527     struct wpa_gtk_data *gd=&(sm->gd);
1528 
1529     memset(gd, 0, sizeof(struct wpa_gtk_data));
1530 
1531     wpa_printf(MSG_DEBUG, "WPA 1/2 Group Key Handshake\n");
1532 
1533     key_info = WPA_GET_BE16(key->key_info);
1534 
1535     if (sm->proto == WPA_PROTO_RSN) {
1536         ret = wpa_supplicant_process_1_of_2_rsn(sm, key_data,
1537                                                 key_data_len, key_info, gd);
1538     } else {
1539         ret = wpa_supplicant_process_1_of_2_wpa(sm, key, key_data,
1540                                                 key_data_len, key_info, ver, gd);
1541     }
1542 
1543     wpa_sm_set_state(WPA_GROUP_HANDSHAKE);
1544 
1545     if (ret)
1546         goto failed;
1547 
1548     /*before callback, set seq for add param difficult in callback*/
1549     wpa_sm_set_seq(sm, key, 0);
1550     sm->key_info=key_info;
1551 
1552     if (wpa_supplicant_send_2_of_2(sm, key, ver, key_info))
1553         goto failed;
1554 
1555     return;
1556 
1557 failed:
1558     wpa_sm_deauthenticate(sm, WLAN_REASON_UNSPECIFIED);
1559 }
1560 
wpa_supplicant_send_2_of_2_txcallback(struct wpa_sm * sm)1561 static int wpa_supplicant_send_2_of_2_txcallback(struct wpa_sm *sm)
1562 {
1563     u16 key_info=sm->key_info;
1564     u16 rekey= (WPA_SM_STATE(sm) == WPA_COMPLETED);
1565 
1566     if((sm->gd).gtk_len) {
1567         if (wpa_supplicant_install_gtk(sm, &(sm->gd)))
1568             goto failed;
1569     } else {
1570         goto failed;
1571     }
1572 
1573     if (rekey) {
1574 #ifdef MSG_PRINT
1575         wpa_printf(MSG_DEBUG, "WPA: Group rekeying "
1576             "completed with " MACSTR " [GTK=%s]",
1577             MAC2STR(sm->bssid), wpa_cipher_txt(sm->group_cipher));
1578 #endif
1579         wpa_sm_cancel_auth_timeout(sm);
1580         wpa_sm_set_state(WPA_COMPLETED);
1581     } else
1582         wpa_supplicant_key_neg_complete(sm, sm->bssid,
1583                         key_info &WPA_KEY_INFO_SECURE);
1584     return 0;
1585 
1586 failed:
1587     return WLAN_REASON_UNSPECIFIED;
1588 }
1589 
wpa_supplicant_verify_eapol_key_mic(struct wpa_sm * sm,struct wpa_eapol_key_192 * key,u16 ver,const u8 * buf,size_t len)1590 static int wpa_supplicant_verify_eapol_key_mic(struct wpa_sm *sm,
1591                            struct wpa_eapol_key_192 *key,
1592                            u16 ver,
1593                            const u8 *buf, size_t len)
1594 {
1595     u8 mic[WPA_EAPOL_KEY_MIC_MAX_LEN];
1596     int ok = 0;
1597     size_t mic_len = wpa_mic_len(sm->key_mgmt);
1598 
1599     os_memcpy(mic, key->key_mic, mic_len);
1600     if (sm->tptk_set) {
1601         os_memset(key->key_mic, 0, mic_len);
1602         wpa_eapol_key_mic(sm->tptk.kck, sm->tptk.kck_len, sm->key_mgmt,
1603                           ver, buf, len, key->key_mic);
1604         if (os_memcmp_const(mic, key->key_mic, mic_len) != 0) {
1605            #ifdef DEBUG_PRINT
1606             wpa_printf(MSG_DEBUG, "WPA: Invalid EAPOL-Key MIC "
1607                    "when using TPTK - ignoring TPTK");
1608            #endif
1609         } else {
1610             ok = 1;
1611             sm->tptk_set = 0;
1612             sm->ptk_set = 1;
1613             memcpy(&sm->ptk, &sm->tptk, sizeof(sm->ptk));
1614         }
1615     }
1616 
1617     if (!ok && sm->ptk_set) {
1618         os_memset(key->key_mic, 0, mic_len);
1619         wpa_eapol_key_mic(sm->ptk.kck, sm->ptk.kck_len, sm->key_mgmt,
1620                           ver, buf, len, key->key_mic);
1621         if (os_memcmp_const(mic, key->key_mic, mic_len) != 0) {
1622             #ifdef DEBUG_PRINT
1623             wpa_printf(MSG_DEBUG, "WPA: Invalid EAPOL-Key MIC "
1624                    "- dropping packet");
1625              #endif
1626             return -1;
1627         }
1628         ok = 1;
1629     }
1630 
1631     if (!ok) {
1632         #ifdef DEBUG_PRINT
1633         wpa_printf(MSG_DEBUG, "WPA: Could not verify EAPOL-Key MIC "
1634                "- dropping packet");
1635          #endif
1636         return -1;
1637     }
1638 
1639     memcpy(sm->rx_replay_counter, key->replay_counter,
1640           WPA_REPLAY_COUNTER_LEN);
1641     sm->rx_replay_counter_set = 1;
1642     /*update request_counter for mic failure report*/
1643     memcpy(sm->request_counter, key->replay_counter,
1644           WPA_REPLAY_COUNTER_LEN);
1645     return 0;
1646 }
1647 
1648 
1649 /* Decrypt RSN EAPOL-Key key data (RC4 or AES-WRAP) */
wpa_supplicant_decrypt_key_data(struct wpa_sm * sm,struct wpa_eapol_key * key,u16 ver,u8 * key_data,size_t * key_data_len)1650 static int wpa_supplicant_decrypt_key_data(struct wpa_sm *sm,
1651                                            struct wpa_eapol_key *key, u16 ver,
1652                                            u8 *key_data, size_t *key_data_len)
1653 {
1654     wpa_hexdump(MSG_DEBUG, "RSN: encrypted key data",
1655                 key_data, *key_data_len);
1656     if (!sm->ptk_set) {
1657         #ifdef DEBUG_PRINT
1658         wpa_printf(MSG_DEBUG, "WPA: PTK not available, "
1659                "cannot decrypt EAPOL-Key key data.");
1660         #endif
1661         return -1;
1662     }
1663 
1664     /* Decrypt key data here so that this operation does not need
1665      * to be implemented separately for each message type. */
1666     if (ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 && sm->ptk.kek_len == 16) {
1667         u8 ek[32];
1668         os_memcpy(ek, key->key_iv, 16);
1669         os_memcpy(ek + 16, sm->ptk.kek, sm->ptk.kek_len);
1670         if (rc4_skip(ek, 32, 256, key_data, *key_data_len)) {
1671             #ifdef DEBUG_PRINT
1672             wpa_printf(MSG_DEBUG, "WPA: RC4 failed");
1673             #endif
1674             return -1;
1675         }
1676     } else if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES ||
1677                ver == WPA_KEY_INFO_TYPE_AES_128_CMAC ||
1678                sm->key_mgmt == WPA_KEY_MGMT_OSEN ||
1679                wpa_key_mgmt_suite_b(sm->key_mgmt) ||
1680                sm->key_mgmt == WPA_KEY_MGMT_SAE) {
1681         u8 *buf;
1682         if (*key_data_len < 8 || *key_data_len % 8) {
1683             #ifdef DEBUG_PRINT
1684             wpa_printf(MSG_DEBUG, "WPA: Unsupported "
1685                    "AES-WRAP len %u", (unsigned int) *key_data_len);
1686             #endif
1687             return -1;
1688         }
1689 
1690         *key_data_len -= 8; /* AES-WRAP adds 8 bytes */
1691         /*replaced by xxx to remove malloc*/
1692         buf = ((u8 *) (key+1))+ 8;
1693              /*
1694         buf = os_wifi_malloc(keydatalen);
1695         if (buf == NULL) {
1696             #ifdef DEBUG_PRINT
1697             wpa_printf(MSG_DEBUG, "WPA: No memory for "
1698                    "AES-UNWRAP buffer");
1699              #endif
1700             return -1;
1701         }
1702         */
1703         if (aes_unwrap(sm->ptk.kek, sm->ptk.kek_len, *key_data_len / 8,
1704                        key_data, buf)) {
1705             #ifdef DEBUG_PRINT
1706             wpa_printf(MSG_DEBUG, "WPA: AES unwrap failed - "
1707                        "could not decrypt EAPOL-Key key data");
1708             #endif
1709             return -1;
1710         }
1711         os_memcpy(key_data, buf, *key_data_len);
1712         WPA_PUT_BE16(key->key_data_length, *key_data_len);
1713     } else {
1714         #ifdef DEBUG_PRINT
1715         wpa_printf(MSG_DEBUG, "WPA: Unsupported key_info type %d",
1716                ver);
1717          #endif
1718         return -1;
1719     }
1720     wpa_hexdump(MSG_DEBUG, "WPA: decrypted EAPOL-Key key data",
1721                 key_data, *key_data_len);
1722     return 0;
1723 }
1724 
1725 
wpa_eapol_key_dump(struct wpa_sm * sm,const struct wpa_eapol_key * key,unsigned int key_data_len,const u8 * mic,unsigned int mic_len)1726 static void wpa_eapol_key_dump(struct wpa_sm *sm,
1727                                const struct wpa_eapol_key *key,
1728                                unsigned int key_data_len,
1729                                const u8 *mic, unsigned int mic_len)
1730 {
1731 #ifdef DEBUG_PRINT
1732 
1733     u16 key_info = WPA_GET_BE16(key->key_info);
1734 
1735     wpa_printf(MSG_DEBUG, "  EAPOL-Key type=%d\n", key->type);
1736     wpa_printf(MSG_DEBUG, "  key_info 0x%x (ver=%d keyidx=%d rsvd=%d %s"
1737            "%s%s%s%s%s%s%s)\n",
1738            key_info, (u32)(key_info & WPA_KEY_INFO_TYPE_MASK),
1739            (u32)((key_info & WPA_KEY_INFO_KEY_INDEX_MASK) >>
1740            WPA_KEY_INFO_KEY_INDEX_SHIFT),
1741            (u32)((key_info & (BIT(13) | BIT(14) | BIT(15))) >> 13),
1742            key_info & WPA_KEY_INFO_KEY_TYPE ? "Pairwise" : "Group",
1743            key_info & WPA_KEY_INFO_INSTALL ? " Install" : "",
1744            key_info & WPA_KEY_INFO_ACK ? " Ack" : "",
1745            key_info & WPA_KEY_INFO_MIC ? " MIC" : "",
1746            key_info & WPA_KEY_INFO_SECURE ? " Secure" : "",
1747            key_info & WPA_KEY_INFO_ERROR ? " Error" : "",
1748            key_info & WPA_KEY_INFO_REQUEST ? " Request" : "",
1749            key_info & WPA_KEY_INFO_ENCR_KEY_DATA ? " Encr" : "");
1750     wpa_printf(MSG_DEBUG, "  key_length=%u key_data_length=%u\n",
1751                WPA_GET_BE16(key->key_length), key_data_len);
1752     wpa_hexdump(MSG_DEBUG, "  replay_counter",
1753                 key->replay_counter, WPA_REPLAY_COUNTER_LEN);
1754     wpa_hexdump(MSG_DEBUG, "  key_nonce", key->key_nonce, WPA_NONCE_LEN);
1755     wpa_hexdump(MSG_DEBUG, "  key_iv", key->key_iv, 16);
1756     wpa_hexdump(MSG_DEBUG, "  key_rsc", key->key_rsc, 8);
1757     wpa_hexdump(MSG_DEBUG, "  key_id (reserved)", key->key_id, 8);
1758     wpa_hexdump(MSG_DEBUG, "  key_mic", mic, mic_len);
1759 
1760 #endif
1761 }
1762 
1763 /**
1764  * wpa_sm_rx_eapol - Process received WPA EAPOL frames
1765  * @sm: Pointer to WPA state machine data from wpa_sm_init()
1766  * @src_addr: Source MAC address of the EAPOL packet
1767  * @buf: Pointer to the beginning of the EAPOL data (EAPOL header)
1768  * @len: Length of the EAPOL frame
1769  * Returns: 1 = WPA EAPOL-Key processed, 0 = not a WPA EAPOL-Key, -1 failure
1770  *
1771  * This function is called for each received EAPOL frame. Other than EAPOL-Key
1772  * frames can be skipped if filtering is done elsewhere. wpa_sm_rx_eapol() is
1773  * only processing WPA and WPA2 EAPOL-Key frames.
1774  *
1775  * The received EAPOL-Key packets are validated and valid packets are replied
1776  * to. In addition, key material (PTK, GTK) is configured at the end of a
1777  * successful key handshake.
1778  * buf begin from version, so remove mac header ,snap header and ether_type
1779  */
wpa_sm_rx_eapol(u8 * src_addr,u8 * buf,u32 len)1780 int wpa_sm_rx_eapol(u8 *src_addr, u8 *buf, u32 len)
1781 {
1782     struct wpa_sm *sm = &gWpaSm;
1783     size_t plen, data_len, key_data_len;
1784     struct ieee802_1x_hdr *hdr;
1785     struct wpa_eapol_key *key;
1786     struct wpa_eapol_key_192 *key192;
1787     u16 key_info, ver;
1788     u8 *tmp;
1789     int ret = -1;
1790     size_t mic_len, keyhdrlen;
1791     u8 *key_data;
1792 
1793     mic_len = wpa_mic_len(sm->key_mgmt);
1794     keyhdrlen = mic_len == 24 ? sizeof(*key192) : sizeof(*key);
1795 
1796     if (len < sizeof(*hdr) + keyhdrlen) {
1797 #ifdef DEBUG_PRINT
1798         wpa_printf(MSG_DEBUG, "WPA: EAPOL frame too short to be a WPA "
1799                             "EAPOL-Key (len %lu, expecting at least %lu)",
1800                             (unsigned long) len,
1801                             (unsigned long) sizeof(*hdr) + sizeof(*key));
1802 #endif
1803         return 0;
1804     }
1805 
1806     tmp = buf;
1807 
1808     hdr = (struct ieee802_1x_hdr *) tmp;
1809     key = (struct wpa_eapol_key *) (hdr + 1);
1810     key192 = (struct wpa_eapol_key_192 *)
1811             (tmp + sizeof(struct ieee802_1x_hdr));
1812     if (mic_len == 24)
1813         key_data = (u8 *) (key192 + 1);
1814     else
1815         key_data = (u8 *) (key + 1);
1816 
1817     plen = be_to_host16(hdr->length);
1818     data_len = plen + sizeof(*hdr);
1819 
1820 #ifdef DEBUG_PRINT
1821     wpa_printf(MSG_DEBUG, "IEEE 802.1X RX: version=%d type=%d length=%d\n",
1822            hdr->version, hdr->type, plen);
1823 #endif
1824 
1825     if (hdr->version < EAPOL_VERSION) {
1826         /* TODO: backwards compatibility */
1827     }
1828     if (hdr->type != IEEE802_1X_TYPE_EAPOL_KEY) {
1829 #ifdef DEBUG_PRINT
1830         wpa_printf(MSG_DEBUG, "WPA: EAPOL frame (type %u) discarded, "
1831             "not a Key frame", hdr->type);
1832 #endif
1833         ret = 0;
1834         goto out;
1835     }
1836     if (plen > len - sizeof(*hdr) || plen < keyhdrlen) {
1837 #ifdef DEBUG_PRINT
1838         wpa_printf(MSG_DEBUG, "WPA: EAPOL frame payload size %lu "
1839                "invalid (frame size %lu)",
1840                (unsigned long) plen, (unsigned long) len);
1841 #endif
1842         ret = 0;
1843         goto out;
1844     }
1845 
1846     if (key->type != EAPOL_KEY_TYPE_WPA && key->type != EAPOL_KEY_TYPE_RSN) {
1847 #ifdef DEBUG_PRINT
1848         wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key type (%d) unknown, "
1849                "discarded", key->type);
1850 #endif
1851         ret = 0;
1852         goto out;
1853     }
1854 
1855     wpa_hexdump(MSG_MSGDUMP, "WPA: RX EAPOL-Key", tmp, len);
1856 
1857     if (data_len < len) {
1858 #ifdef DEBUG_PRINT
1859         wpa_printf(MSG_DEBUG, "WPA: ignoring %lu bytes after the IEEE "
1860                "802.1X data\n", (unsigned long) len - data_len);
1861 #endif
1862     }
1863     key_info = WPA_GET_BE16(key->key_info);
1864     ver = key_info & WPA_KEY_INFO_TYPE_MASK;
1865 
1866     if (ver != WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 &&
1867 #ifdef CONFIG_IEEE80211W
1868         ver != WPA_KEY_INFO_TYPE_AES_128_CMAC &&
1869 #ifdef CONFIG_WPA3_SAE
1870         sm->key_mgmt != WPA_KEY_MGMT_SAE &&
1871 #endif
1872         !wpa_key_mgmt_suite_b(sm->key_mgmt) &&
1873 #endif
1874         ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1875 #ifdef DEBUG_PRINT
1876         wpa_printf(MSG_DEBUG, "WPA: Unsupported EAPOL-Key descriptor "
1877                "version %d.", ver);
1878 #endif
1879         goto out;
1880     }
1881     if (wpa_key_mgmt_suite_b(sm->key_mgmt) &&
1882         ver != WPA_KEY_INFO_TYPE_AKM_DEFINED) {
1883         wpa_msg(NULL, MSG_INFO,
1884                 "RSN: Unsupported EAPOL-Key descriptor version %d (expected AKM defined = 0)",
1885                 ver);
1886         goto out;
1887     }
1888 
1889 #ifdef CONFIG_IEEE80211W
1890     if (wpa_key_mgmt_sha256(sm->key_mgmt)) {
1891         if (ver != WPA_KEY_INFO_TYPE_AES_128_CMAC &&
1892             sm->key_mgmt != WPA_KEY_MGMT_OSEN &&
1893             !wpa_key_mgmt_suite_b(sm->key_mgmt) &&
1894             sm->key_mgmt != WPA_KEY_MGMT_SAE) {
1895             goto out;
1896         }
1897     } else
1898 #endif
1899 
1900     if (sm->pairwise_cipher == WPA_CIPHER_CCMP &&
1901         !wpa_key_mgmt_suite_b(sm->key_mgmt) &&
1902         ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES &&
1903         sm->key_mgmt != WPA_KEY_MGMT_SAE) {
1904 #ifdef DEBUG_PRINT
1905         wpa_printf(MSG_DEBUG, "WPA: CCMP is used, but EAPOL-Key "
1906                "descriptor version (%d) is not 2.", ver);
1907 #endif
1908         if (sm->group_cipher != WPA_CIPHER_CCMP &&
1909             !(key_info & WPA_KEY_INFO_KEY_TYPE)) {
1910             /* Earlier versions of IEEE 802.11i did not explicitly
1911              * require version 2 descriptor for all EAPOL-Key
1912              * packets, so allow group keys to use version 1 if
1913              * CCMP is not used for them. */
1914             #ifdef DEBUG_PRINT
1915               wpa_printf(MSG_DEBUG, "WPA: Backwards compatibility: "
1916                    "allow invalid version for non-CCMP group "
1917                    "keys");
1918             #endif
1919         } else
1920             goto out;
1921     }
1922 
1923 #ifdef CONFIG_GCMP
1924     if (sm->pairwise_cipher == WPA_CIPHER_GCMP &&
1925         !wpa_key_mgmt_suite_b(sm->key_mgmt) &&
1926         ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1927         wpa_msg(NULL, MSG_INFO,
1928                 "WPA: GCMP is used, but EAPOL-Key "
1929                 "descriptor version (%d) is not 2", ver);
1930         goto out;
1931     }
1932 #endif
1933 
1934     if (sm->rx_replay_counter_set &&
1935         os_memcmp(key->replay_counter, sm->rx_replay_counter,
1936         WPA_REPLAY_COUNTER_LEN) <= 0) {
1937         #ifdef DEBUG_PRINT
1938         wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key Replay Counter did not"
1939                " increase - dropping packet");
1940         #endif
1941         goto out;
1942     }
1943 
1944     if (!(key_info & (WPA_KEY_INFO_ACK | WPA_KEY_INFO_SMK_MESSAGE))) {
1945         #ifdef DEBUG_PRINT
1946         wpa_printf(MSG_DEBUG, "WPA: No Ack bit in key_info");
1947          #endif
1948         goto out;
1949     }
1950 
1951     if (key_info & WPA_KEY_INFO_REQUEST) {
1952         #ifdef DEBUG_PRINT
1953         wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key with Request bit - dropped");
1954         #endif
1955         goto out;
1956     }
1957 
1958     if ((key_info & WPA_KEY_INFO_MIC) &&
1959         wpa_supplicant_verify_eapol_key_mic(sm, key192, ver, tmp, data_len))
1960         goto out;
1961 
1962 
1963     if (mic_len == 24)
1964         key_data_len = WPA_GET_BE16(key192->key_data_length);
1965     else
1966         key_data_len = WPA_GET_BE16(key->key_data_length);
1967 
1968     wpa_eapol_key_dump(sm, key, key_data_len, key192->key_mic, mic_len);
1969 
1970 
1971     if (key_data_len > plen - keyhdrlen) {
1972 #ifdef DEBUG_PRINT
1973         wpa_printf(MSG_DEBUG, "WPA: Invalid EAPOL-Key "
1974                               "frame - key_data overflow (%u > %u)",
1975                               (unsigned int) key_data_len,
1976                               (unsigned int) (plen - keyhdrlen));
1977 #endif
1978         goto out;
1979     }
1980 
1981     if (sm->proto == WPA_PROTO_RSN &&
1982         (key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
1983         if (wpa_supplicant_decrypt_key_data(sm, key, ver, key_data,
1984                                             &key_data_len))
1985             goto out;
1986     }
1987 
1988     if (key_info & WPA_KEY_INFO_KEY_TYPE) {
1989         if (key_info & WPA_KEY_INFO_KEY_INDEX_MASK) {
1990              #ifdef DEBUG_PRINT
1991             wpa_printf(MSG_DEBUG, "WPA: Ignored EAPOL-Key "
1992                    "(Pairwise) with non-zero key index");
1993           #endif
1994             goto out;
1995         }
1996 
1997         if (key_info & WPA_KEY_INFO_MIC) {
1998             /* 3/4 4-Way Handshake */
1999            wpa_supplicant_process_3_of_4(sm, key, ver, key_data,
2000                                          key_data_len);
2001         } else {
2002             /* 1/4 4-Way Handshake */
2003             sm->eapol1_count++;
2004             if (sm->eapol1_count > MAX_EAPOL_RETRIES) {
2005 #ifdef DEBUG_PRINT
2006                 wpa_printf(MSG_INFO, "EAPOL1 received for %d times, sending deauth", sm->eapol1_count);
2007 #endif
2008                 esp_wifi_internal_issue_disconnect(WLAN_REASON_4WAY_HANDSHAKE_TIMEOUT);
2009                 goto out;
2010             }
2011             wpa_supplicant_process_1_of_4(sm, src_addr, key,
2012                                           ver, key_data,
2013                                           key_data_len);
2014         }
2015     } else {
2016         if (key_info & WPA_KEY_INFO_MIC) {
2017             /* 1/2 Group Key Handshake */
2018             wpa_supplicant_process_1_of_2(sm, src_addr, key,
2019                                           key_data, key_data_len,
2020                                           ver);
2021         } else {
2022          #ifdef DEBUG_PRINT
2023             wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key (Group) "
2024                    "without Mic bit - dropped");
2025          #endif
2026         }
2027     }
2028 
2029     ret = 1;
2030 
2031 out:
2032 
2033     return ret;
2034 }
2035 
2036 /**
2037  * wpa_supplicant_set_state - Set current connection state
2038  * @wpa_s: Pointer to wpa_supplicant data
2039  * @state: The new connection state
2040  *
2041  * This function is called whenever the connection state changes, e.g.,
2042  * association is completed for WPA/WPA2 4-Way Handshake is started.
2043  */
wpa_sm_set_state(enum wpa_states state)2044 void wpa_sm_set_state(enum wpa_states state)
2045 {
2046        struct wpa_sm *sm = &gWpaSm;
2047     if(WPA_MIC_FAILURE==WPA_SM_STATE(sm))
2048         ets_timer_disarm(&(sm->cm_timer));
2049     sm->wpa_state= state;
2050 }
2051 
2052 
2053 /**
2054  * wpa_sm_set_pmk - Set PMK
2055  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2056  * @pmk: The new PMK
2057  * @pmk_len: The length of the new PMK in bytes
2058  * @bssid: AA to add into PMKSA cache or %NULL to not cache the PMK
2059  *
2060  * Configure the PMK for WPA state machine.
2061  */
wpa_sm_set_pmk(struct wpa_sm * sm,const u8 * pmk,size_t pmk_len,const u8 * pmkid,const u8 * bssid)2062 void wpa_sm_set_pmk(struct wpa_sm *sm, const u8 *pmk, size_t pmk_len,
2063                     const u8 *pmkid, const u8 *bssid)
2064 {
2065     if (sm == NULL)
2066         return;
2067 
2068     sm->pmk_len = pmk_len;
2069     os_memcpy(sm->pmk, pmk, pmk_len);
2070 
2071 #ifdef CONFIG_IEEE80211R
2072     /* Set XXKey to be PSK for FT key derivation */
2073     sm->xxkey_len = pmk_len;
2074     os_memcpy(sm->xxkey, pmk, pmk_len);
2075 #endif /* CONFIG_IEEE80211R */
2076 
2077     if (bssid) {
2078         pmksa_cache_add(sm->pmksa, pmk, pmk_len, pmkid, NULL, 0,
2079                         bssid, sm->own_addr,
2080                         sm->network_ctx, sm->key_mgmt);
2081     }
2082 }
2083 
2084 
2085 /**
2086  * wpa_sm_set_pmk_from_pmksa - Set PMK based on the current PMKSA
2087  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2088  *
2089  * Take the PMK from the current PMKSA into use. If no PMKSA is active, the PMK
2090  * will be cleared.
2091  */
wpa_sm_set_pmk_from_pmksa(struct wpa_sm * sm)2092 void wpa_sm_set_pmk_from_pmksa(struct wpa_sm *sm)
2093 {
2094     if (sm == NULL)
2095         return;
2096 
2097     if (sm->cur_pmksa) {
2098         sm->pmk_len = sm->cur_pmksa->pmk_len;
2099         os_memcpy(sm->pmk, sm->cur_pmksa->pmk, sm->pmk_len);
2100     } else {
2101         sm->pmk_len = PMK_LEN_MAX;
2102         os_memset(sm->pmk, 0, PMK_LEN_MAX);
2103     }
2104 }
2105 
2106 
2107 
2108 
2109 #ifdef ESP_SUPPLICANT
wpa_sm_init(char * payload,WPA_SEND_FUNC snd_func,WPA_SET_ASSOC_IE set_assoc_ie_func,WPA_INSTALL_KEY ppinstallkey,WPA_GET_KEY ppgetkey,WPA_DEAUTH_FUNC wpa_deauth,WPA_NEG_COMPLETE wpa_neg_complete)2110 bool wpa_sm_init(char * payload, WPA_SEND_FUNC snd_func,
2111                    WPA_SET_ASSOC_IE set_assoc_ie_func, WPA_INSTALL_KEY ppinstallkey, WPA_GET_KEY ppgetkey, WPA_DEAUTH_FUNC wpa_deauth,
2112                    WPA_NEG_COMPLETE wpa_neg_complete)
2113 {
2114     struct wpa_sm *sm = &gWpaSm;
2115     u16 spp_attrubute = 0;
2116 
2117     sm->eapol_version = 0x1;   /* DEFAULT_EAPOL_VERSION */
2118     sm->sendto = snd_func;
2119     sm->config_assoc_ie = set_assoc_ie_func;
2120     sm->install_ppkey = ppinstallkey;
2121     sm->get_ppkey = ppgetkey;
2122     sm->wpa_deauthenticate = wpa_deauth;
2123     sm->wpa_neg_complete = wpa_neg_complete;
2124     sm->key_install = false;
2125 
2126     spp_attrubute = esp_wifi_get_spp_attrubute_internal(WIFI_IF_STA);
2127     sm->spp_sup.capable = ((spp_attrubute & WPA_CAPABILITY_SPP_CAPABLE) ? SPP_AMSDU_CAP_ENABLE : SPP_AMSDU_CAP_DISABLE);
2128     sm->spp_sup.require = ((spp_attrubute & WPA_CAPABILITY_SPP_REQUIRED) ? SPP_AMSDU_REQ_ENABLE : SPP_AMSDU_REQ_DISABLE);
2129 
2130     wpa_sm_set_state(WPA_INACTIVE);
2131 
2132     sm->pmksa = pmksa_cache_init(wpa_sm_pmksa_free_cb, sm, sm);
2133     if (sm->pmksa == NULL) {
2134         wpa_printf(MSG_ERROR,
2135                 "RSN: PMKSA cache initialization failed");
2136         return false;
2137     }
2138     return true;
2139 }
2140 
2141 /**
2142  *  * wpa_sm_deinit - Deinitialize WPA state machine
2143  *    */
wpa_sm_deinit(void)2144 void wpa_sm_deinit(void)
2145 {
2146     struct wpa_sm *sm = &gWpaSm;
2147     pmksa_cache_deinit(sm->pmksa);
2148 }
2149 
2150 
wpa_set_profile(u32 wpa_proto,u8 auth_mode)2151 void wpa_set_profile(u32 wpa_proto, u8 auth_mode)
2152 {
2153     struct wpa_sm *sm = &gWpaSm;
2154 
2155     sm->proto = wpa_proto;
2156     if (auth_mode == WPA2_AUTH_ENT) {
2157         sm->key_mgmt = WPA_KEY_MGMT_IEEE8021X; /* for wpa2 enterprise */
2158     } else if (auth_mode == WPA2_AUTH_ENT_SHA256) {
2159         sm->key_mgmt = WPA_KEY_MGMT_IEEE8021X_SHA256; /* for wpa2 enterprise sha256 */
2160     } else if (auth_mode == WPA2_AUTH_PSK_SHA256) {
2161         sm->key_mgmt = WPA_KEY_MGMT_PSK_SHA256;
2162     } else if (auth_mode == WPA3_AUTH_PSK) {
2163          sm->key_mgmt = WPA_KEY_MGMT_SAE; /* for WPA3 PSK */
2164     } else if (auth_mode == WAPI_AUTH_PSK) {
2165          sm->key_mgmt = WPA_KEY_MGMT_WAPI_PSK; /* for WAPI PSK */
2166     } else if (auth_mode == WPA2_AUTH_ENT_SHA384_SUITE_B) {
2167          sm->key_mgmt = WPA_KEY_MGMT_IEEE8021X_SUITE_B_192;
2168     } else {
2169         sm->key_mgmt = WPA_KEY_MGMT_PSK;  /* fixed to PSK for now */
2170     }
2171 }
2172 
wpa_set_pmk(uint8_t * pmk,const u8 * pmkid,bool cache_pmksa)2173 void wpa_set_pmk(uint8_t *pmk, const u8 *pmkid, bool cache_pmksa)
2174 {
2175     struct wpa_sm *sm = &gWpaSm;
2176     int pmk_len;
2177 
2178     if (wpa_key_mgmt_sha384(sm->key_mgmt))
2179         pmk_len = PMK_LEN_SUITE_B_192;
2180     else
2181         pmk_len = PMK_LEN;
2182 
2183     memcpy(sm->pmk, pmk, pmk_len);
2184     sm->pmk_len = pmk_len;
2185 
2186     if (cache_pmksa) {
2187         pmksa_cache_add(sm->pmksa, pmk, PMK_LEN, pmkid, NULL, 0,
2188                         sm->bssid, sm->own_addr,
2189                         sm->network_ctx, sm->key_mgmt);
2190     }
2191 }
2192 
wpa_set_bss(char * macddr,char * bssid,u8 pairwise_cipher,u8 group_cipher,char * passphrase,u8 * ssid,size_t ssid_len)2193 int wpa_set_bss(char *macddr, char * bssid, u8 pairwise_cipher, u8 group_cipher, char *passphrase, u8 *ssid, size_t ssid_len)
2194 {
2195     int res = 0;
2196     struct wpa_sm *sm = &gWpaSm;
2197 
2198     sm->pairwise_cipher = BIT(pairwise_cipher);
2199     sm->group_cipher = BIT(group_cipher);
2200     sm->rx_replay_counter_set = 0;  //init state not intall replay counter value
2201     memset(sm->rx_replay_counter, 0, WPA_REPLAY_COUNTER_LEN);
2202     sm->wpa_ptk_rekey = 0;
2203     sm->renew_snonce = 1;
2204     memcpy(sm->own_addr, macddr, ETH_ALEN);
2205     memcpy(sm->bssid, bssid, ETH_ALEN);
2206     sm->ap_notify_completed_rsne = esp_wifi_sta_is_ap_notify_completed_rsne_internal();
2207 
2208     if (sm->key_mgmt == WPA_KEY_MGMT_SAE ||
2209         is_wpa2_enterprise_connection()) {
2210         if (!esp_wifi_skip_supp_pmkcaching()) {
2211             pmksa_cache_set_current(sm, NULL, (const u8*) bssid, 0, 0);
2212             wpa_sm_set_pmk_from_pmksa(sm);
2213         } else {
2214             struct rsn_pmksa_cache_entry *entry = NULL;
2215 
2216             if (sm->pmksa) {
2217                 entry = pmksa_cache_get(sm->pmksa, (const u8 *)bssid, NULL, NULL);
2218             }
2219             if (entry) {
2220                 pmksa_cache_flush(sm->pmksa, NULL, entry->pmk, entry->pmk_len);
2221             }
2222         }
2223     }
2224 
2225     sm->eapol1_count = 0;
2226 #ifdef CONFIG_IEEE80211W
2227     if (esp_wifi_sta_pmf_enabled()) {
2228         wifi_config_t wifi_cfg;
2229         wifi_cipher_type_t mgmt_cipher = esp_wifi_sta_get_mgmt_group_cipher();
2230 
2231         esp_wifi_get_config(WIFI_IF_STA, &wifi_cfg);
2232         sm->pmf_cfg = wifi_cfg.sta.pmf_cfg;
2233         sm->mgmt_group_cipher = cipher_type_map_public_to_supp(mgmt_cipher);
2234         if (sm->mgmt_group_cipher == WPA_CIPHER_NONE) {
2235                 wpa_printf(MSG_ERROR, "mgmt_cipher %d not supported", mgmt_cipher);
2236                 return -1;
2237 	}
2238 #ifdef CONFIG_SUITEB192
2239         extern bool g_wpa_suiteb_certification;
2240         if (g_wpa_suiteb_certification) {
2241             if (mgmt_cipher != WIFI_CIPHER_TYPE_AES_GMAC256) {
2242                 wpa_printf(MSG_ERROR, "suite-b 192bit certification, only GMAC256 is supported");
2243                 return -1;
2244             }
2245         }
2246 #endif
2247     } else {
2248         memset(&sm->pmf_cfg, 0, sizeof(sm->pmf_cfg));
2249         sm->mgmt_group_cipher = WPA_CIPHER_NONE;
2250     }
2251 #endif
2252     set_assoc_ie(assoc_ie_buf); /* use static buffer */
2253     res = wpa_gen_wpa_ie(sm, sm->assoc_wpa_ie, sm->assoc_wpa_ie_len);
2254     if (res < 0)
2255         return -1;
2256     sm->assoc_wpa_ie_len = res;
2257     wpa_set_passphrase(passphrase, ssid, ssid_len);
2258     return 0;
2259 }
2260 
2261 /*
2262  *  Call after set ssid since we calc pmk inside this routine directly
2263  */
2264   void
wpa_set_passphrase(char * passphrase,u8 * ssid,size_t ssid_len)2265 wpa_set_passphrase(char * passphrase, u8 *ssid, size_t ssid_len)
2266 {
2267     struct wifi_ssid *sta_ssid = esp_wifi_sta_get_prof_ssid_internal();
2268     struct wpa_sm *sm = &gWpaSm;
2269 
2270     if (passphrase == NULL) return;
2271 
2272     /*
2273      *  Here only handle passphrase string.  Need extra step to handle 32B, 64Hex raw
2274      *    PMK.
2275      */
2276     if (sm->key_mgmt == WPA_KEY_MGMT_SAE)
2277         return;
2278 
2279     /* This is really SLOW, so just re cacl while reset param */
2280     if (esp_wifi_sta_get_reset_param_internal() != 0) {
2281         // check it's psk
2282         if (strlen((char *)esp_wifi_sta_get_prof_password_internal()) == 64) {
2283             if (hexstr2bin((char *)esp_wifi_sta_get_prof_password_internal(),
2284                            esp_wifi_sta_get_ap_info_prof_pmk_internal(), PMK_LEN) != 0)
2285                 return;
2286         } else {
2287             pbkdf2_sha1((char *)esp_wifi_sta_get_prof_password_internal(), sta_ssid->ssid, (size_t)sta_ssid->len,
2288                         4096, esp_wifi_sta_get_ap_info_prof_pmk_internal(), PMK_LEN);
2289         }
2290         esp_wifi_sta_update_ap_info_internal();
2291         esp_wifi_sta_set_reset_param_internal(0);
2292     }
2293 
2294     if (sm->key_mgmt == WPA_KEY_MGMT_IEEE8021X) {
2295     /* TODO nothing */
2296     } else {
2297         memcpy(sm->pmk, esp_wifi_sta_get_ap_info_prof_pmk_internal(), PMK_LEN);
2298         sm->pmk_len = PMK_LEN;
2299     }
2300 }
2301 
2302   void
set_assoc_ie(u8 * assoc_buf)2303 set_assoc_ie(u8 * assoc_buf)
2304 {
2305     struct wpa_sm *sm = &gWpaSm;
2306 
2307     sm->assoc_wpa_ie = assoc_buf + 2;
2308     //wpa_ie insert OUI 4 byte before ver, but RSN have 2 bytes of RSN capability,
2309     // so wpa_ie have two more bytes than rsn_ie
2310     if ( sm->proto == WPA_PROTO_WPA)
2311          sm->assoc_wpa_ie_len = ASSOC_IE_LEN;
2312     else
2313          sm->assoc_wpa_ie_len = ASSOC_IE_LEN - 2;
2314 
2315     sm->config_assoc_ie(sm->proto, assoc_buf, sm->assoc_wpa_ie_len);
2316 }
2317 
2318 static int
wpa_sm_set_key(struct install_key * key_sm,enum wpa_alg alg,u8 * addr,int key_idx,int set_tx,u8 * seq,size_t seq_len,u8 * key,size_t key_len,enum key_flag key_flag)2319 wpa_sm_set_key(struct install_key *key_sm, enum wpa_alg alg,
2320         u8 *addr, int key_idx, int set_tx,
2321         u8 *seq, size_t seq_len,
2322         u8 *key, size_t key_len,
2323         enum key_flag key_flag)
2324 {
2325     struct wpa_sm *sm = &gWpaSm;
2326 
2327     /*gtk or ptk both need check countermeasures*/
2328     if (alg == WIFI_WPA_ALG_TKIP && key_len == 32) {
2329         /* Clear the MIC error counter when setting a new PTK. */
2330         key_sm->mic_errors_seen = 0;
2331     }
2332 
2333     key_sm->keys_cleared = 0;
2334     key_sm->alg = alg;
2335     memcpy(key_sm->addr, addr, ETH_ALEN);
2336     key_sm->key_idx = key_idx;
2337     key_sm->set_tx = set_tx;
2338     memcpy(key_sm->key, key, key_len);
2339 
2340     sm->install_ppkey(alg, addr, key_idx, set_tx, seq, seq_len, key, key_len, key_flag);
2341     return 0;
2342 }
2343 
2344 static int
wpa_sm_get_key(uint8_t * ifx,int * alg,u8 * addr,int * key_idx,u8 * key,size_t key_len,enum key_flag key_flag)2345 wpa_sm_get_key(uint8_t *ifx, int *alg, u8 *addr, int *key_idx, u8 *key, size_t key_len, enum key_flag key_flag)
2346 {
2347     struct wpa_sm *sm = &gWpaSm;
2348     return sm->get_ppkey(ifx, alg, addr, key_idx, key, key_len, key_flag);
2349 }
2350 
wpa_supplicant_clr_countermeasures(u16 * pisunicast)2351 void wpa_supplicant_clr_countermeasures(u16 *pisunicast)
2352 {
2353        struct wpa_sm *sm = &gWpaSm;
2354        (sm->install_ptk).mic_errors_seen=0;
2355     (sm->install_gtk).mic_errors_seen=0;
2356     ets_timer_done(&(sm->cm_timer));
2357     wpa_printf(MSG_DEBUG, "WPA: TKIP countermeasures clean\n");
2358 }
2359 
2360 /*recovery from countermeasures state, countermeasures state is period that stop connection with ap
2361   also used in wpa_init after connecting with ap
2362 */
wpa_supplicant_stop_countermeasures(u16 * pisunicast)2363 void wpa_supplicant_stop_countermeasures(u16 *pisunicast)
2364 {
2365        struct wpa_sm *sm = &gWpaSm;
2366 
2367        ets_timer_done(&(sm->cm_timer));
2368     if (sm->countermeasures) {
2369         sm->countermeasures = 0;
2370               wpa_supplicant_clr_countermeasures(NULL);
2371 
2372         wpa_printf(MSG_DEBUG, "WPA: TKIP countermeasures stopped\n");
2373               /*renew scan preocess, this isn't done now*/
2374     }
2375        wpa_sm_set_state(WPA_DISCONNECTED);
2376 }
2377 
wpa_michael_mic_failure(u16 isunicast)2378 int wpa_michael_mic_failure(u16 isunicast)
2379 {
2380        struct wpa_sm *sm = &gWpaSm;
2381        int *pmic_errors_seen=(isunicast)? &((sm->install_ptk).mic_errors_seen) : &((sm->install_gtk).mic_errors_seen);
2382 
2383     wpa_printf(MSG_DEBUG, "\nTKIP MIC failure occur\n");
2384 
2385        /*both unicast and multicast mic_errors_seen need statistics*/
2386     if ((sm->install_ptk).mic_errors_seen + (sm->install_gtk).mic_errors_seen) {
2387         /* Send the new MIC error report immediately since we are going
2388          * to start countermeasures and AP better do the same.
2389          */
2390         wpa_sm_set_state(WPA_TKIP_COUNTERMEASURES);
2391         wpa_sm_key_request(sm, 1, 0);
2392 
2393         /* initialize countermeasures */
2394         sm->countermeasures = 1;
2395         wpa_printf(MSG_DEBUG, "TKIP countermeasures started\n");
2396 
2397         /*
2398          * Need to wait for completion of request frame. We do not get
2399          * any callback for the message completion, so just wait a
2400          * short while and hope for the best. */
2401          esp_rom_delay_us(10000);
2402 
2403         /*deauthenticate AP*/
2404 
2405         /*stop monitor next mic_failure timer,disconnect for 60sec, then stop contermeasures*/
2406         ets_timer_disarm(&(sm->cm_timer));
2407         ets_timer_done(&(sm->cm_timer));
2408         ets_timer_setfn(&(sm->cm_timer), (ETSTimerFunc *)wpa_supplicant_stop_countermeasures, NULL);
2409         ets_timer_arm(&(sm->cm_timer), 60*1000, false);
2410 
2411         /* TODO: mark the AP rejected for 60 second. STA is
2412          * allowed to associate with another AP.. */
2413     } else {
2414         *pmic_errors_seen=(*pmic_errors_seen)+1;
2415         wpa_sm_set_state(WPA_MIC_FAILURE);
2416         wpa_sm_key_request(sm, 1, 0);
2417         /*start 60sec counter to monitor whether next mic_failure occur in this period, or clear mic_errors_seen*/
2418         ets_timer_disarm(&(sm->cm_timer));
2419         ets_timer_done(&(sm->cm_timer));
2420         ets_timer_setfn(&(sm->cm_timer), (ETSTimerFunc *)wpa_supplicant_clr_countermeasures, NULL);
2421         ets_timer_arm(&(sm->cm_timer), 60*1000, false);
2422     }
2423 
2424     return 0;
2425 }
2426 
2427 /*
2428    eapol tx callback function to make sure new key
2429     install after 4-way handoff
2430 */
eapol_txcb(void * eb)2431 void eapol_txcb(void *eb)
2432 {
2433     struct wpa_sm *sm = &gWpaSm;
2434     u8 isdeauth = 0;  //no_zero value is the reason for deauth
2435 
2436     if (false == esp_wifi_sta_is_running_internal()){
2437         return;
2438     }
2439 
2440     switch(WPA_SM_STATE(sm)) {
2441         case WPA_FIRST_HALF_4WAY_HANDSHAKE:
2442             break;
2443         case WPA_LAST_HALF_4WAY_HANDSHAKE:
2444             if (sm->txcb_flags & WPA_4_4_HANDSHAKE_BIT) {
2445                 sm->txcb_flags &= ~WPA_4_4_HANDSHAKE_BIT;
2446                 isdeauth = wpa_supplicant_send_4_of_4_txcallback(sm);
2447             } else {
2448                 wpa_printf(MSG_DEBUG, "4/4 txcb, flags=%d\n", sm->txcb_flags);
2449             }
2450             break;
2451         case WPA_GROUP_HANDSHAKE:
2452             if (sm->txcb_flags & WPA_GROUP_HANDSHAKE_BIT) {
2453                 sm->txcb_flags &= ~WPA_GROUP_HANDSHAKE_BIT;
2454                 isdeauth = wpa_supplicant_send_2_of_2_txcallback(sm);
2455             } else {
2456                 wpa_printf(MSG_DEBUG, "2/2 txcb, flags=%d\n", sm->txcb_flags);
2457             }
2458             break;
2459         case WPA_TKIP_COUNTERMEASURES: isdeauth=WLAN_REASON_MICHAEL_MIC_FAILURE;
2460             break;
2461         default: break;
2462     }
2463 
2464     if(isdeauth) {
2465         wpa_sm_deauthenticate(sm, isdeauth);
2466     }
2467 }
2468 
wpa_sta_in_4way_handshake(void)2469 bool wpa_sta_in_4way_handshake(void)
2470 {
2471     struct wpa_sm *sm = &gWpaSm;
2472     if ( WPA_SM_STATE(sm) == WPA_MIC_FAILURE || WPA_SM_STATE(sm) == WPA_FIRST_HALF_4WAY_HANDSHAKE
2473         || WPA_SM_STATE(sm) == WPA_LAST_HALF_4WAY_HANDSHAKE) {
2474         return true;
2475     }
2476     return false;
2477 }
2478 
wpa_sta_is_cur_pmksa_set(void)2479 bool wpa_sta_is_cur_pmksa_set(void) {
2480     struct wpa_sm *sm = &gWpaSm;
2481     return (pmksa_cache_get_current(sm) != NULL);
2482 }
2483 
wpa_sta_cur_pmksa_matches_akm(void)2484 bool wpa_sta_cur_pmksa_matches_akm(void) {
2485     struct wpa_sm *sm = &gWpaSm;
2486     struct rsn_pmksa_cache_entry *pmksa;
2487 
2488     pmksa = pmksa_cache_get_current(sm);
2489     return (pmksa != NULL  &&
2490             sm->key_mgmt == pmksa->akmp);
2491 }
2492 
wpa_sta_clear_curr_pmksa(void)2493 void wpa_sta_clear_curr_pmksa(void) {
2494     struct wpa_sm *sm = &gWpaSm;
2495 
2496     if (sm->pmksa)
2497         pmksa_cache_flush(sm->pmksa, NULL, sm->pmk, sm->pmk_len);
2498     pmksa_cache_clear_current(sm);
2499 }
2500 
2501 #endif // ESP_SUPPLICANT
2502