]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/wpa_supplicant/wpa.c
This commit was generated by cvs2svn to compensate for changes in r168609,
[FreeBSD/FreeBSD.git] / contrib / wpa_supplicant / wpa.c
1 /*
2  * WPA Supplicant - WPA state machine and EAPOL-Key processing
3  * Copyright (c) 2003-2005, Jouni Malinen <jkmaline@cc.hut.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 <stdlib.h>
16 #include <stdio.h>
17 #ifndef CONFIG_NATIVE_WINDOWS
18 #include <netinet/in.h>
19 #endif /* CONFIG_NATIVE_WINDOWS */
20 #include <string.h>
21
22 #include "common.h"
23 #include "md5.h"
24 #include "sha1.h"
25 #include "rc4.h"
26 #include "aes_wrap.h"
27 #include "wpa.h"
28 #include "eloop.h"
29 #include "wpa_supplicant.h"
30 #include "config.h"
31 #include "l2_packet.h"
32 #include "eapol_sm.h"
33 #include "preauth.h"
34 #include "wpa_i.h"
35
36
37 static const int WPA_SELECTOR_LEN = 4;
38 static const u8 WPA_OUI_TYPE[] = { 0x00, 0x50, 0xf2, 1 };
39 static const u16 WPA_VERSION = 1;
40 static const u8 WPA_AUTH_KEY_MGMT_NONE[] = { 0x00, 0x50, 0xf2, 0 };
41 static const u8 WPA_AUTH_KEY_MGMT_UNSPEC_802_1X[] = { 0x00, 0x50, 0xf2, 1 };
42 static const u8 WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X[] = { 0x00, 0x50, 0xf2, 2 };
43 static const u8 WPA_CIPHER_SUITE_NONE[] = { 0x00, 0x50, 0xf2, 0 };
44 static const u8 WPA_CIPHER_SUITE_WEP40[] = { 0x00, 0x50, 0xf2, 1 };
45 static const u8 WPA_CIPHER_SUITE_TKIP[] = { 0x00, 0x50, 0xf2, 2 };
46 static const u8 WPA_CIPHER_SUITE_WRAP[] = { 0x00, 0x50, 0xf2, 3 };
47 static const u8 WPA_CIPHER_SUITE_CCMP[] = { 0x00, 0x50, 0xf2, 4 };
48 static const u8 WPA_CIPHER_SUITE_WEP104[] = { 0x00, 0x50, 0xf2, 5 };
49
50 /* WPA IE version 1
51  * 00-50-f2:1 (OUI:OUI type)
52  * 0x01 0x00 (version; little endian)
53  * (all following fields are optional:)
54  * Group Suite Selector (4 octets) (default: TKIP)
55  * Pairwise Suite Count (2 octets, little endian) (default: 1)
56  * Pairwise Suite List (4 * n octets) (default: TKIP)
57  * Authenticated Key Management Suite Count (2 octets, little endian)
58  *    (default: 1)
59  * Authenticated Key Management Suite List (4 * n octets)
60  *    (default: unspec 802.1X)
61  * WPA Capabilities (2 octets, little endian) (default: 0)
62  */
63
64 struct wpa_ie_hdr {
65         u8 elem_id;
66         u8 len;
67         u8 oui[3];
68         u8 oui_type;
69         u8 version[2];
70 } __attribute__ ((packed));
71
72
73 static const int RSN_SELECTOR_LEN = 4;
74 static const u16 RSN_VERSION = 1;
75 static const u8 RSN_AUTH_KEY_MGMT_UNSPEC_802_1X[] = { 0x00, 0x0f, 0xac, 1 };
76 static const u8 RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X[] = { 0x00, 0x0f, 0xac, 2 };
77 static const u8 RSN_CIPHER_SUITE_NONE[] = { 0x00, 0x0f, 0xac, 0 };
78 static const u8 RSN_CIPHER_SUITE_WEP40[] = { 0x00, 0x0f, 0xac, 1 };
79 static const u8 RSN_CIPHER_SUITE_TKIP[] = { 0x00, 0x0f, 0xac, 2 };
80 static const u8 RSN_CIPHER_SUITE_WRAP[] = { 0x00, 0x0f, 0xac, 3 };
81 static const u8 RSN_CIPHER_SUITE_CCMP[] = { 0x00, 0x0f, 0xac, 4 };
82 static const u8 RSN_CIPHER_SUITE_WEP104[] = { 0x00, 0x0f, 0xac, 5 };
83
84 /* EAPOL-Key Key Data Encapsulation
85  * GroupKey and STAKey require encryption, otherwise, encryption is optional.
86  */
87 static const u8 RSN_KEY_DATA_GROUPKEY[] = { 0x00, 0x0f, 0xac, 1 };
88 static const u8 RSN_KEY_DATA_STAKEY[] = { 0x00, 0x0f, 0xac, 2 };
89 static const u8 RSN_KEY_DATA_MAC_ADDR[] = { 0x00, 0x0f, 0xac, 3 };
90 static const u8 RSN_KEY_DATA_PMKID[] = { 0x00, 0x0f, 0xac, 4 };
91
92 /* 1/4: PMKID
93  * 2/4: RSN IE
94  * 3/4: one or two RSN IEs + GTK IE (encrypted)
95  * 4/4: empty
96  * 1/2: GTK IE (encrypted)
97  * 2/2: empty
98  */
99
100 /* RSN IE version 1
101  * 0x01 0x00 (version; little endian)
102  * (all following fields are optional:)
103  * Group Suite Selector (4 octets) (default: CCMP)
104  * Pairwise Suite Count (2 octets, little endian) (default: 1)
105  * Pairwise Suite List (4 * n octets) (default: CCMP)
106  * Authenticated Key Management Suite Count (2 octets, little endian)
107  *    (default: 1)
108  * Authenticated Key Management Suite List (4 * n octets)
109  *    (default: unspec 802.1X)
110  * RSN Capabilities (2 octets, little endian) (default: 0)
111  * PMKID Count (2 octets) (default: 0)
112  * PMKID List (16 * n octets)
113  */
114
115 struct rsn_ie_hdr {
116         u8 elem_id; /* WLAN_EID_RSN */
117         u8 len;
118         u8 version[2];
119 } __attribute__ ((packed));
120
121
122 struct wpa_eapol_key {
123         u8 type;
124         /* Note: key_info, key_length, and key_data_length are unaligned */
125         u8 key_info[2];
126         u8 key_length[2];
127         u8 replay_counter[WPA_REPLAY_COUNTER_LEN];
128         u8 key_nonce[WPA_NONCE_LEN];
129         u8 key_iv[16];
130         u8 key_rsc[8];
131         u8 key_id[8]; /* Reserved in IEEE 802.11i/RSN */
132         u8 key_mic[16];
133         u8 key_data_length[2];
134         /* followed by key_data_length bytes of key_data */
135 } __attribute__ ((packed));
136
137 #define WPA_KEY_INFO_TYPE_MASK (BIT(0) | BIT(1) | BIT(2))
138 #define WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 BIT(0)
139 #define WPA_KEY_INFO_TYPE_HMAC_SHA1_AES BIT(1)
140 #define WPA_KEY_INFO_KEY_TYPE BIT(3) /* 1 = Pairwise, 0 = Group key */
141 /* bit4..5 is used in WPA, but is reserved in IEEE 802.11i/RSN */
142 #define WPA_KEY_INFO_KEY_INDEX_MASK (BIT(4) | BIT(5))
143 #define WPA_KEY_INFO_KEY_INDEX_SHIFT 4
144 #define WPA_KEY_INFO_INSTALL BIT(6) /* pairwise */
145 #define WPA_KEY_INFO_TXRX BIT(6) /* group */
146 #define WPA_KEY_INFO_ACK BIT(7)
147 #define WPA_KEY_INFO_MIC BIT(8)
148 #define WPA_KEY_INFO_SECURE BIT(9)
149 #define WPA_KEY_INFO_ERROR BIT(10)
150 #define WPA_KEY_INFO_REQUEST BIT(11)
151 #define WPA_KEY_INFO_ENCR_KEY_DATA BIT(12) /* IEEE 802.11i/RSN only */
152
153
154
155 /**
156  * wpa_cipher_txt - Convert cipher suite to a text string
157  * @cipher: Cipher suite (WPA_CIPHER_* enum)
158  * Returns: Pointer to a text string of the cipher suite name
159  */
160 static const char * wpa_cipher_txt(int cipher)
161 {
162         switch (cipher) {
163         case WPA_CIPHER_NONE:
164                 return "NONE";
165         case WPA_CIPHER_WEP40:
166                 return "WEP-40";
167         case WPA_CIPHER_WEP104:
168                 return "WEP-104";
169         case WPA_CIPHER_TKIP:
170                 return "TKIP";
171         case WPA_CIPHER_CCMP:
172                 return "CCMP";
173         default:
174                 return "UNKNOWN";
175         }
176 }
177
178
179 /**
180  * wpa_key_mgmt_txt - Convert key management suite to a text string
181  * @key_mgmt: Key management suite (WPA_KEY_MGMT_* enum)
182  * @proto: WPA/WPA2 version (WPA_PROTO_*)
183  * Returns: Pointer to a text string of the key management suite name
184  */
185 static const char * wpa_key_mgmt_txt(int key_mgmt, int proto)
186 {
187         switch (key_mgmt) {
188         case WPA_KEY_MGMT_IEEE8021X:
189                 return proto == WPA_PROTO_RSN ?
190                         "WPA2/IEEE 802.1X/EAP" : "WPA/IEEE 802.1X/EAP";
191         case WPA_KEY_MGMT_PSK:
192                 return proto == WPA_PROTO_RSN ?
193                         "WPA2-PSK" : "WPA-PSK";
194         case WPA_KEY_MGMT_NONE:
195                 return "NONE";
196         case WPA_KEY_MGMT_IEEE8021X_NO_WPA:
197                 return "IEEE 802.1X (no WPA)";
198         default:
199                 return "UNKNOWN";
200         }
201 }
202
203
204 static int wpa_selector_to_bitfield(const u8 *s)
205 {
206         if (memcmp(s, WPA_CIPHER_SUITE_NONE, WPA_SELECTOR_LEN) == 0)
207                 return WPA_CIPHER_NONE;
208         if (memcmp(s, WPA_CIPHER_SUITE_WEP40, WPA_SELECTOR_LEN) == 0)
209                 return WPA_CIPHER_WEP40;
210         if (memcmp(s, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN) == 0)
211                 return WPA_CIPHER_TKIP;
212         if (memcmp(s, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN) == 0)
213                 return WPA_CIPHER_CCMP;
214         if (memcmp(s, WPA_CIPHER_SUITE_WEP104, WPA_SELECTOR_LEN) == 0)
215                 return WPA_CIPHER_WEP104;
216         return 0;
217 }
218
219
220 static int wpa_key_mgmt_to_bitfield(const u8 *s)
221 {
222         if (memcmp(s, WPA_AUTH_KEY_MGMT_UNSPEC_802_1X, WPA_SELECTOR_LEN) == 0)
223                 return WPA_KEY_MGMT_IEEE8021X;
224         if (memcmp(s, WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X, WPA_SELECTOR_LEN) ==
225             0)
226                 return WPA_KEY_MGMT_PSK;
227         if (memcmp(s, WPA_AUTH_KEY_MGMT_NONE, WPA_SELECTOR_LEN) == 0)
228                 return WPA_KEY_MGMT_WPA_NONE;
229         return 0;
230 }
231
232
233 static int rsn_selector_to_bitfield(const u8 *s)
234 {
235         if (memcmp(s, RSN_CIPHER_SUITE_NONE, RSN_SELECTOR_LEN) == 0)
236                 return WPA_CIPHER_NONE;
237         if (memcmp(s, RSN_CIPHER_SUITE_WEP40, RSN_SELECTOR_LEN) == 0)
238                 return WPA_CIPHER_WEP40;
239         if (memcmp(s, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN) == 0)
240                 return WPA_CIPHER_TKIP;
241         if (memcmp(s, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN) == 0)
242                 return WPA_CIPHER_CCMP;
243         if (memcmp(s, RSN_CIPHER_SUITE_WEP104, RSN_SELECTOR_LEN) == 0)
244                 return WPA_CIPHER_WEP104;
245         return 0;
246 }
247
248
249 static int rsn_key_mgmt_to_bitfield(const u8 *s)
250 {
251         if (memcmp(s, RSN_AUTH_KEY_MGMT_UNSPEC_802_1X, RSN_SELECTOR_LEN) == 0)
252                 return WPA_KEY_MGMT_IEEE8021X;
253         if (memcmp(s, RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X, RSN_SELECTOR_LEN) ==
254             0)
255                 return WPA_KEY_MGMT_PSK;
256         return 0;
257 }
258
259
260 static int wpa_parse_wpa_ie_wpa(const u8 *wpa_ie, size_t wpa_ie_len,
261                                 struct wpa_ie_data *data)
262 {
263         const struct wpa_ie_hdr *hdr;
264         const u8 *pos;
265         int left;
266         int i, count;
267
268         data->proto = WPA_PROTO_WPA;
269         data->pairwise_cipher = WPA_CIPHER_TKIP;
270         data->group_cipher = WPA_CIPHER_TKIP;
271         data->key_mgmt = WPA_KEY_MGMT_IEEE8021X;
272         data->capabilities = 0;
273         data->pmkid = NULL;
274         data->num_pmkid = 0;
275
276         if (wpa_ie_len == 0) {
277                 /* No WPA IE - fail silently */
278                 return -1;
279         }
280
281         if (wpa_ie_len < sizeof(struct wpa_ie_hdr)) {
282                 wpa_printf(MSG_DEBUG, "%s: ie len too short %lu",
283                            __func__, (unsigned long) wpa_ie_len);
284                 return -1;
285         }
286
287         hdr = (const struct wpa_ie_hdr *) wpa_ie;
288
289         if (hdr->elem_id != GENERIC_INFO_ELEM ||
290             hdr->len != wpa_ie_len - 2 ||
291             memcmp(&hdr->oui, WPA_OUI_TYPE, WPA_SELECTOR_LEN) != 0 ||
292             WPA_GET_LE16(hdr->version) != WPA_VERSION) {
293                 wpa_printf(MSG_DEBUG, "%s: malformed ie or unknown version",
294                            __func__);
295                 return -1;
296         }
297
298         pos = (const u8 *) (hdr + 1);
299         left = wpa_ie_len - sizeof(*hdr);
300
301         if (left >= WPA_SELECTOR_LEN) {
302                 data->group_cipher = wpa_selector_to_bitfield(pos);
303                 pos += WPA_SELECTOR_LEN;
304                 left -= WPA_SELECTOR_LEN;
305         } else if (left > 0) {
306                 wpa_printf(MSG_DEBUG, "%s: ie length mismatch, %u too much",
307                            __func__, left);
308                 return -1;
309         }
310
311         if (left >= 2) {
312                 data->pairwise_cipher = 0;
313                 count = WPA_GET_LE16(pos);
314                 pos += 2;
315                 left -= 2;
316                 if (count == 0 || left < count * WPA_SELECTOR_LEN) {
317                         wpa_printf(MSG_DEBUG, "%s: ie count botch (pairwise), "
318                                    "count %u left %u", __func__, count, left);
319                         return -1;
320                 }
321                 for (i = 0; i < count; i++) {
322                         data->pairwise_cipher |= wpa_selector_to_bitfield(pos);
323                         pos += WPA_SELECTOR_LEN;
324                         left -= WPA_SELECTOR_LEN;
325                 }
326         } else if (left == 1) {
327                 wpa_printf(MSG_DEBUG, "%s: ie too short (for key mgmt)",
328                            __func__);
329                 return -1;
330         }
331
332         if (left >= 2) {
333                 data->key_mgmt = 0;
334                 count = WPA_GET_LE16(pos);
335                 pos += 2;
336                 left -= 2;
337                 if (count == 0 || left < count * WPA_SELECTOR_LEN) {
338                         wpa_printf(MSG_DEBUG, "%s: ie count botch (key mgmt), "
339                                    "count %u left %u", __func__, count, left);
340                         return -1;
341                 }
342                 for (i = 0; i < count; i++) {
343                         data->key_mgmt |= wpa_key_mgmt_to_bitfield(pos);
344                         pos += WPA_SELECTOR_LEN;
345                         left -= WPA_SELECTOR_LEN;
346                 }
347         } else if (left == 1) {
348                 wpa_printf(MSG_DEBUG, "%s: ie too short (for capabilities)",
349                            __func__);
350                 return -1;
351         }
352
353         if (left >= 2) {
354                 data->capabilities = WPA_GET_LE16(pos);
355                 pos += 2;
356                 left -= 2;
357         }
358
359         if (left > 0) {
360                 wpa_printf(MSG_DEBUG, "%s: ie has %u trailing bytes",
361                            __func__, left);
362                 return -1;
363         }
364
365         return 0;
366 }
367
368
369 static int wpa_parse_wpa_ie_rsn(const u8 *rsn_ie, size_t rsn_ie_len,
370                                 struct wpa_ie_data *data)
371 {
372         const struct rsn_ie_hdr *hdr;
373         const u8 *pos;
374         int left;
375         int i, count;
376
377         data->proto = WPA_PROTO_RSN;
378         data->pairwise_cipher = WPA_CIPHER_CCMP;
379         data->group_cipher = WPA_CIPHER_CCMP;
380         data->key_mgmt = WPA_KEY_MGMT_IEEE8021X;
381         data->capabilities = 0;
382         data->pmkid = NULL;
383         data->num_pmkid = 0;
384
385         if (rsn_ie_len == 0) {
386                 /* No RSN IE - fail silently */
387                 return -1;
388         }
389
390         if (rsn_ie_len < sizeof(struct rsn_ie_hdr)) {
391                 wpa_printf(MSG_DEBUG, "%s: ie len too short %lu",
392                            __func__, (unsigned long) rsn_ie_len);
393                 return -1;
394         }
395
396         hdr = (const struct rsn_ie_hdr *) rsn_ie;
397
398         if (hdr->elem_id != RSN_INFO_ELEM ||
399             hdr->len != rsn_ie_len - 2 ||
400             WPA_GET_LE16(hdr->version) != RSN_VERSION) {
401                 wpa_printf(MSG_DEBUG, "%s: malformed ie or unknown version",
402                            __func__);
403                 return -1;
404         }
405
406         pos = (const u8 *) (hdr + 1);
407         left = rsn_ie_len - sizeof(*hdr);
408
409         if (left >= RSN_SELECTOR_LEN) {
410                 data->group_cipher = rsn_selector_to_bitfield(pos);
411                 pos += RSN_SELECTOR_LEN;
412                 left -= RSN_SELECTOR_LEN;
413         } else if (left > 0) {
414                 wpa_printf(MSG_DEBUG, "%s: ie length mismatch, %u too much",
415                            __func__, left);
416                 return -1;
417         }
418
419         if (left >= 2) {
420                 data->pairwise_cipher = 0;
421                 count = WPA_GET_LE16(pos);
422                 pos += 2;
423                 left -= 2;
424                 if (count == 0 || left < count * RSN_SELECTOR_LEN) {
425                         wpa_printf(MSG_DEBUG, "%s: ie count botch (pairwise), "
426                                    "count %u left %u", __func__, count, left);
427                         return -1;
428                 }
429                 for (i = 0; i < count; i++) {
430                         data->pairwise_cipher |= rsn_selector_to_bitfield(pos);
431                         pos += RSN_SELECTOR_LEN;
432                         left -= RSN_SELECTOR_LEN;
433                 }
434         } else if (left == 1) {
435                 wpa_printf(MSG_DEBUG, "%s: ie too short (for key mgmt)",
436                            __func__);
437                 return -1;
438         }
439
440         if (left >= 2) {
441                 data->key_mgmt = 0;
442                 count = WPA_GET_LE16(pos);
443                 pos += 2;
444                 left -= 2;
445                 if (count == 0 || left < count * RSN_SELECTOR_LEN) {
446                         wpa_printf(MSG_DEBUG, "%s: ie count botch (key mgmt), "
447                                    "count %u left %u", __func__, count, left);
448                         return -1;
449                 }
450                 for (i = 0; i < count; i++) {
451                         data->key_mgmt |= rsn_key_mgmt_to_bitfield(pos);
452                         pos += RSN_SELECTOR_LEN;
453                         left -= RSN_SELECTOR_LEN;
454                 }
455         } else if (left == 1) {
456                 wpa_printf(MSG_DEBUG, "%s: ie too short (for capabilities)",
457                            __func__);
458                 return -1;
459         }
460
461         if (left >= 2) {
462                 data->capabilities = WPA_GET_LE16(pos);
463                 pos += 2;
464                 left -= 2;
465         }
466
467         if (left >= 2) {
468                 data->num_pmkid = WPA_GET_LE16(pos);
469                 pos += 2;
470                 left -= 2;
471                 if (left < data->num_pmkid * PMKID_LEN) {
472                         wpa_printf(MSG_DEBUG, "%s: PMKID underflow "
473                                    "(num_pmkid=%d left=%d)",
474                                    __func__, data->num_pmkid, left);
475                         data->num_pmkid = 0;
476                 } else {
477                         data->pmkid = pos;
478                         pos += data->num_pmkid * PMKID_LEN;
479                         left -= data->num_pmkid * PMKID_LEN;
480                 }
481         }
482
483         if (left > 0) {
484                 wpa_printf(MSG_DEBUG, "%s: ie has %u trailing bytes - ignored",
485                            __func__, left);
486         }
487
488         return 0;
489 }
490
491
492 /**
493  * wpa_parse_wpa_ie - Parse WPA/RSN IE
494  * @wpa_ie: Pointer to WPA or RSN IE
495  * @wpa_ie_len: Length of the WPA/RSN IE
496  * @data: Pointer to data area for parsing results
497  * Returns: 0 on success, -1 on failure
498  *
499  * Parse the contents of WPA or RSN IE and write the parsed data into data.
500  */
501 int wpa_parse_wpa_ie(const u8 *wpa_ie, size_t wpa_ie_len,
502                      struct wpa_ie_data *data)
503 {
504         if (wpa_ie_len >= 1 && wpa_ie[0] == RSN_INFO_ELEM)
505                 return wpa_parse_wpa_ie_rsn(wpa_ie, wpa_ie_len, data);
506         else
507                 return wpa_parse_wpa_ie_wpa(wpa_ie, wpa_ie_len, data);
508 }
509
510
511 static int wpa_gen_wpa_ie_wpa(u8 *wpa_ie, size_t wpa_ie_len,
512                               int pairwise_cipher, int group_cipher,
513                               int key_mgmt)
514 {
515         u8 *pos;
516         struct wpa_ie_hdr *hdr;
517
518         if (wpa_ie_len < sizeof(*hdr) + WPA_SELECTOR_LEN +
519             2 + WPA_SELECTOR_LEN + 2 + WPA_SELECTOR_LEN)
520                 return -1;
521
522         hdr = (struct wpa_ie_hdr *) wpa_ie;
523         hdr->elem_id = GENERIC_INFO_ELEM;
524         memcpy(&hdr->oui, WPA_OUI_TYPE, WPA_SELECTOR_LEN);
525         WPA_PUT_LE16(hdr->version, WPA_VERSION);
526         pos = (u8 *) (hdr + 1);
527
528         if (group_cipher == WPA_CIPHER_CCMP) {
529                 memcpy(pos, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN);
530         } else if (group_cipher == WPA_CIPHER_TKIP) {
531                 memcpy(pos, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN);
532         } else if (group_cipher == WPA_CIPHER_WEP104) {
533                 memcpy(pos, WPA_CIPHER_SUITE_WEP104, WPA_SELECTOR_LEN);
534         } else if (group_cipher == WPA_CIPHER_WEP40) {
535                 memcpy(pos, WPA_CIPHER_SUITE_WEP40, WPA_SELECTOR_LEN);
536         } else {
537                 wpa_printf(MSG_WARNING, "Invalid group cipher (%d).",
538                            group_cipher);
539                 return -1;
540         }
541         pos += WPA_SELECTOR_LEN;
542
543         *pos++ = 1;
544         *pos++ = 0;
545         if (pairwise_cipher == WPA_CIPHER_CCMP) {
546                 memcpy(pos, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN);
547         } else if (pairwise_cipher == WPA_CIPHER_TKIP) {
548                 memcpy(pos, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN);
549         } else if (pairwise_cipher == WPA_CIPHER_NONE) {
550                 memcpy(pos, WPA_CIPHER_SUITE_NONE, WPA_SELECTOR_LEN);
551         } else {
552                 wpa_printf(MSG_WARNING, "Invalid pairwise cipher (%d).",
553                            pairwise_cipher);
554                 return -1;
555         }
556         pos += WPA_SELECTOR_LEN;
557
558         *pos++ = 1;
559         *pos++ = 0;
560         if (key_mgmt == WPA_KEY_MGMT_IEEE8021X) {
561                 memcpy(pos, WPA_AUTH_KEY_MGMT_UNSPEC_802_1X, WPA_SELECTOR_LEN);
562         } else if (key_mgmt == WPA_KEY_MGMT_PSK) {
563                 memcpy(pos, WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X,
564                        WPA_SELECTOR_LEN);
565         } else if (key_mgmt == WPA_KEY_MGMT_WPA_NONE) {
566                 memcpy(pos, WPA_AUTH_KEY_MGMT_NONE, WPA_SELECTOR_LEN);
567         } else {
568                 wpa_printf(MSG_WARNING, "Invalid key management type (%d).",
569                            key_mgmt);
570                 return -1;
571         }
572         pos += WPA_SELECTOR_LEN;
573
574         /* WPA Capabilities; use defaults, so no need to include it */
575
576         hdr->len = (pos - wpa_ie) - 2;
577
578         WPA_ASSERT(pos - wpa_ie <= wpa_ie_len);
579
580         return pos - wpa_ie;
581 }
582
583
584 static int wpa_gen_wpa_ie_rsn(u8 *rsn_ie, size_t rsn_ie_len,
585                               int pairwise_cipher, int group_cipher,
586                               int key_mgmt, struct wpa_sm *sm)
587 {
588         u8 *pos;
589         struct rsn_ie_hdr *hdr;
590
591         if (rsn_ie_len < sizeof(*hdr) + RSN_SELECTOR_LEN +
592             2 + RSN_SELECTOR_LEN + 2 + RSN_SELECTOR_LEN + 2 +
593             (sm->cur_pmksa ? 2 + PMKID_LEN : 0))
594                 return -1;
595
596         hdr = (struct rsn_ie_hdr *) rsn_ie;
597         hdr->elem_id = RSN_INFO_ELEM;
598         WPA_PUT_LE16(hdr->version, RSN_VERSION);
599         pos = (u8 *) (hdr + 1);
600
601         if (group_cipher == WPA_CIPHER_CCMP) {
602                 memcpy(pos, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN);
603         } else if (group_cipher == WPA_CIPHER_TKIP) {
604                 memcpy(pos, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN);
605         } else if (group_cipher == WPA_CIPHER_WEP104) {
606                 memcpy(pos, RSN_CIPHER_SUITE_WEP104, RSN_SELECTOR_LEN);
607         } else if (group_cipher == WPA_CIPHER_WEP40) {
608                 memcpy(pos, RSN_CIPHER_SUITE_WEP40, RSN_SELECTOR_LEN);
609         } else {
610                 wpa_printf(MSG_WARNING, "Invalid group cipher (%d).",
611                            group_cipher);
612                 return -1;
613         }
614         pos += RSN_SELECTOR_LEN;
615
616         *pos++ = 1;
617         *pos++ = 0;
618         if (pairwise_cipher == WPA_CIPHER_CCMP) {
619                 memcpy(pos, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN);
620         } else if (pairwise_cipher == WPA_CIPHER_TKIP) {
621                 memcpy(pos, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN);
622         } else if (pairwise_cipher == WPA_CIPHER_NONE) {
623                 memcpy(pos, RSN_CIPHER_SUITE_NONE, RSN_SELECTOR_LEN);
624         } else {
625                 wpa_printf(MSG_WARNING, "Invalid pairwise cipher (%d).",
626                            pairwise_cipher);
627                 return -1;
628         }
629         pos += RSN_SELECTOR_LEN;
630
631         *pos++ = 1;
632         *pos++ = 0;
633         if (key_mgmt == WPA_KEY_MGMT_IEEE8021X) {
634                 memcpy(pos, RSN_AUTH_KEY_MGMT_UNSPEC_802_1X, RSN_SELECTOR_LEN);
635         } else if (key_mgmt == WPA_KEY_MGMT_PSK) {
636                 memcpy(pos, RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X,
637                        RSN_SELECTOR_LEN);
638         } else {
639                 wpa_printf(MSG_WARNING, "Invalid key management type (%d).",
640                            key_mgmt);
641                 return -1;
642         }
643         pos += RSN_SELECTOR_LEN;
644
645         /* RSN Capabilities */
646         *pos++ = 0;
647         *pos++ = 0;
648
649         if (sm->cur_pmksa) {
650                 /* PMKID Count (2 octets, little endian) */
651                 *pos++ = 1;
652                 *pos++ = 0;
653                 /* PMKID */
654                 memcpy(pos, sm->cur_pmksa->pmkid, PMKID_LEN);
655                 pos += PMKID_LEN;
656         }
657
658         hdr->len = (pos - rsn_ie) - 2;
659
660         WPA_ASSERT(pos - rsn_ie <= rsn_ie_len);
661
662         return pos - rsn_ie;
663 }
664
665
666 /**
667  * wpa_gen_wpa_ie - Generate WPA/RSN IE based on current security policy
668  * @sm: Pointer to WPA state machine data from wpa_sm_init()
669  * @wpa_ie: Pointer to memory area for the generated WPA/RSN IE
670  * @wpa_ie_len: Maximum length of the generated WPA/RSN IE
671  * Returns: Length of the generated WPA/RSN IE or -1 on failure
672  */
673 static int wpa_gen_wpa_ie(struct wpa_sm *sm, u8 *wpa_ie, size_t wpa_ie_len)
674 {
675         if (sm->proto == WPA_PROTO_RSN)
676                 return wpa_gen_wpa_ie_rsn(wpa_ie, wpa_ie_len,
677                                           sm->pairwise_cipher,
678                                           sm->group_cipher,
679                                           sm->key_mgmt, sm);
680         else
681                 return wpa_gen_wpa_ie_wpa(wpa_ie, wpa_ie_len,
682                                           sm->pairwise_cipher,
683                                           sm->group_cipher,
684                                           sm->key_mgmt);
685 }
686
687
688 /**
689  * wpa_pmk_to_ptk - Calculate PTK from PMK, addresses, and nonces
690  * @pmk: Pairwise master key
691  * @addr1: AA or SA
692  * @addr2: SA or AA
693  * @nonce1: ANonce or SNonce
694  * @nonce2: SNonce or ANonce
695  * @ptk: Buffer for pairwise transient key
696  * @ptk_len: Length of PTK
697  *
698  * IEEE Std 802.11i-2004 - 8.5.1.2 Pairwise key hierarchy
699  * PTK = PRF-X(PMK, "Pairwise key expansion",
700  *             Min(AA, SA) || Max(AA, SA) ||
701  *             Min(ANonce, SNonce) || Max(ANonce, SNonce))
702  */
703 static void wpa_pmk_to_ptk(const u8 *pmk, size_t pmk_len,
704                            const u8 *addr1, const u8 *addr2,
705                            const u8 *nonce1, const u8 *nonce2,
706                            u8 *ptk, size_t ptk_len)
707 {
708         u8 data[2 * ETH_ALEN + 2 * 32];
709
710         if (memcmp(addr1, addr2, ETH_ALEN) < 0) {
711                 memcpy(data, addr1, ETH_ALEN);
712                 memcpy(data + ETH_ALEN, addr2, ETH_ALEN);
713         } else {
714                 memcpy(data, addr2, ETH_ALEN);
715                 memcpy(data + ETH_ALEN, addr1, ETH_ALEN);
716         }
717
718         if (memcmp(nonce1, nonce2, 32) < 0) {
719                 memcpy(data + 2 * ETH_ALEN, nonce1, 32);
720                 memcpy(data + 2 * ETH_ALEN + 32, nonce2, 32);
721         } else {
722                 memcpy(data + 2 * ETH_ALEN, nonce2, 32);
723                 memcpy(data + 2 * ETH_ALEN + 32, nonce1, 32);
724         }
725
726         sha1_prf(pmk, pmk_len, "Pairwise key expansion", data, sizeof(data),
727                  ptk, ptk_len);
728
729         wpa_hexdump_key(MSG_DEBUG, "WPA: PMK", pmk, pmk_len);
730         wpa_hexdump_key(MSG_DEBUG, "WPA: PTK", ptk, ptk_len);
731 }
732
733
734 /**
735  * wpa_eapol_key_mic - Calculate EAPOL-Key MIC
736  * @key: EAPOL-Key Key Confirmation Key (KCK)
737  * @ver: Key descriptor version (WPA_KEY_INFO_TYPE_*)
738  * @buf: Pointer to the beginning of the EAPOL header (version field)
739  * @len: Length of the EAPOL frame (from EAPOL header to the end of the frame)
740  * @mic: Pointer to the buffer to which the EAPOL-Key MIC is written
741  *
742  * Calculate EAPOL-Key MIC for an EAPOL-Key packet. The EAPOL-Key MIC field has
743  * to be cleared (all zeroes) when calling this function.
744  *
745  * Note: 'IEEE Std 802.11i-2004 - 8.5.2 EAPOL-Key frames' has an error in the
746  * description of the Key MIC calculation. It includes packet data from the
747  * beginning of the EAPOL-Key header, not EAPOL header. This incorrect change
748  * happened during final editing of the standard and the correct behavior is
749  * defined in the last draft (IEEE 802.11i/D10).
750  */
751 static void wpa_eapol_key_mic(const u8 *key, int ver,
752                               const u8 *buf, size_t len, u8 *mic)
753 {
754         if (ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4) {
755                 hmac_md5(key, 16, buf, len, mic);
756         } else if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
757                 u8 hash[SHA1_MAC_LEN];
758                 hmac_sha1(key, 16, buf, len, hash);
759                 memcpy(mic, hash, MD5_MAC_LEN);
760         }
761 }
762
763
764 static void wpa_eapol_key_send(struct wpa_sm *sm, const u8 *kck,
765                                int ver, const u8 *dest, u16 proto,
766                                u8 *msg, size_t msg_len, u8 *key_mic)
767 {
768         if (key_mic) {
769                 wpa_eapol_key_mic(kck, ver, msg, msg_len, key_mic);
770         }
771         wpa_hexdump(MSG_MSGDUMP, "WPA: TX EAPOL-Key", msg, msg_len);
772         wpa_sm_ether_send(sm, dest, proto, msg, msg_len);
773         eapol_sm_notify_tx_eapol_key(sm->eapol);
774         free(msg);
775 }
776
777
778 /**
779  * wpa_sm_key_request - Send EAPOL-Key Request
780  * @sm: Pointer to WPA state machine data from wpa_sm_init()
781  * @error: Indicate whether this is an Michael MIC error report
782  * @pairwise: 1 = error report for pairwise packet, 0 = for group packet
783  * Returns: Pointer to the current network structure or %NULL on failure
784  *
785  * Send an EAPOL-Key Request to the current authenticator. This function is
786  * used to request rekeying and it is usually called when a local Michael MIC
787  * failure is detected.
788  */
789 void wpa_sm_key_request(struct wpa_sm *sm, int error, int pairwise)
790 {
791         size_t rlen;
792         struct wpa_eapol_key *reply;
793         int key_info, ver;
794         u8 bssid[ETH_ALEN], *rbuf;
795
796         if (sm->pairwise_cipher == WPA_CIPHER_CCMP)
797                 ver = WPA_KEY_INFO_TYPE_HMAC_SHA1_AES;
798         else
799                 ver = WPA_KEY_INFO_TYPE_HMAC_MD5_RC4;
800
801         if (wpa_sm_get_bssid(sm, bssid) < 0) {
802                 wpa_printf(MSG_WARNING, "Failed to read BSSID for EAPOL-Key "
803                            "request");
804                 return;
805         }
806
807         rbuf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_KEY, NULL,
808                                   sizeof(*reply), &rlen, (void *) &reply);
809         if (rbuf == NULL)
810                 return;
811
812         reply->type = sm->proto == WPA_PROTO_RSN ?
813                 EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
814         key_info = WPA_KEY_INFO_REQUEST | ver;
815         if (sm->ptk_set)
816                 key_info |= WPA_KEY_INFO_MIC;
817         if (error)
818                 key_info |= WPA_KEY_INFO_ERROR;
819         if (pairwise)
820                 key_info |= WPA_KEY_INFO_KEY_TYPE;
821         WPA_PUT_BE16(reply->key_info, key_info);
822         WPA_PUT_BE16(reply->key_length, 0);
823         memcpy(reply->replay_counter, sm->request_counter,
824                WPA_REPLAY_COUNTER_LEN);
825         inc_byte_array(sm->request_counter, WPA_REPLAY_COUNTER_LEN);
826
827         WPA_PUT_BE16(reply->key_data_length, 0);
828
829         wpa_printf(MSG_INFO, "WPA: Sending EAPOL-Key Request (error=%d "
830                    "pairwise=%d ptk_set=%d len=%lu)",
831                    error, pairwise, sm->ptk_set, (unsigned long) rlen);
832         wpa_eapol_key_send(sm, sm->ptk.kck, ver, bssid, ETH_P_EAPOL,
833                            rbuf, rlen, key_info & WPA_KEY_INFO_MIC ?
834                            reply->key_mic : NULL);
835 }
836
837
838 struct wpa_eapol_ie_parse {
839         const u8 *wpa_ie;
840         size_t wpa_ie_len;
841         const u8 *rsn_ie;
842         size_t rsn_ie_len;
843         const u8 *pmkid;
844         const u8 *gtk;
845         size_t gtk_len;
846 };
847
848
849 /**
850  * wpa_supplicant_parse_generic - Parse EAPOL-Key Key Data Generic IEs
851  * @pos: Pointer to the IE header
852  * @end: Pointer to the end of the Key Data buffer
853  * @ie: Pointer to parsed IE data
854  * Returns: 0 on success, 1 if end mark is found, -1 on failure
855  */
856 static int wpa_supplicant_parse_generic(const u8 *pos, const u8 *end,
857                                         struct wpa_eapol_ie_parse *ie)
858 {
859         if (pos[1] == 0)
860                 return 1;
861
862         if (pos[1] >= 6 &&
863             memcmp(pos + 2, WPA_OUI_TYPE, WPA_SELECTOR_LEN) == 0 &&
864             pos[2 + WPA_SELECTOR_LEN] == 1 &&
865             pos[2 + WPA_SELECTOR_LEN + 1] == 0) {
866                 ie->wpa_ie = pos;
867                 ie->wpa_ie_len = pos[1] + 2;
868                 return 0;
869         }
870
871         if (pos + 1 + RSN_SELECTOR_LEN < end &&
872             pos[1] >= RSN_SELECTOR_LEN + PMKID_LEN &&
873             memcmp(pos + 2, RSN_KEY_DATA_PMKID, RSN_SELECTOR_LEN) == 0) {
874                 ie->pmkid = pos + 2 + RSN_SELECTOR_LEN;
875                 return 0;
876         }
877
878         if (pos[1] > RSN_SELECTOR_LEN + 2 &&
879             memcmp(pos + 2, RSN_KEY_DATA_GROUPKEY, RSN_SELECTOR_LEN) == 0) {
880                 ie->gtk = pos + 2 + RSN_SELECTOR_LEN;
881                 ie->gtk_len = pos[1] - RSN_SELECTOR_LEN;
882         }
883
884         return 0;
885 }
886
887
888 /**
889  * wpa_supplicant_parse_ies - Parse EAPOL-Key Key Data IEs
890  * @buf: Pointer to the Key Data buffer
891  * @len: Key Data Length
892  * @ie: Pointer to parsed IE data
893  * Returns: 0 on success, -1 on failure
894  */
895 static int wpa_supplicant_parse_ies(const u8 *buf, size_t len,
896                                     struct wpa_eapol_ie_parse *ie)
897 {
898         const u8 *pos, *end;
899         int ret = 0;
900
901         memset(ie, 0, sizeof(*ie));
902         for (pos = buf, end = pos + len; pos + 1 < end; pos += 2 + pos[1]) {
903                 if (pos + 2 + pos[1] > end) {
904                         wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key Key Data "
905                                    "underflow (ie=%d len=%d)", pos[0], pos[1]);
906                         ret = -1;
907                         break;
908                 }
909                 if (*pos == RSN_INFO_ELEM) {
910                         ie->rsn_ie = pos;
911                         ie->rsn_ie_len = pos[1] + 2;
912                 } else if (*pos == GENERIC_INFO_ELEM) {
913                         ret = wpa_supplicant_parse_generic(pos, end, ie);
914                         if (ret < 0)
915                                 break;
916                         if (ret > 0) {
917                                 ret = 0;
918                                 break;
919                         }
920                 } else {
921                         wpa_hexdump(MSG_DEBUG, "WPA: Unrecognized EAPOL-Key "
922                                     "Key Data IE", pos, 2 + pos[1]);
923                 }
924         }
925
926         return ret;
927 }
928
929
930 static int wpa_supplicant_get_pmk(struct wpa_sm *sm,
931                                   const unsigned char *src_addr,
932                                   const u8 *pmkid)
933 {
934         int abort_cached = 0;
935
936         if (pmkid && !sm->cur_pmksa) {
937                 /* When using drivers that generate RSN IE, wpa_supplicant may
938                  * not have enough time to get the association information
939                  * event before receiving this 1/4 message, so try to find a
940                  * matching PMKSA cache entry here. */
941                 sm->cur_pmksa = pmksa_cache_get(sm, src_addr, pmkid);
942                 if (sm->cur_pmksa) {
943                         wpa_printf(MSG_DEBUG, "RSN: found matching PMKID from "
944                                    "PMKSA cache");
945                 } else {
946                         wpa_printf(MSG_DEBUG, "RSN: no matching PMKID found");
947                         abort_cached = 1;
948                 }
949         }
950
951         if (pmkid && sm->cur_pmksa &&
952             memcmp(pmkid, sm->cur_pmksa->pmkid, PMKID_LEN) == 0) {
953                 wpa_hexdump(MSG_DEBUG, "RSN: matched PMKID", pmkid, PMKID_LEN);
954                 wpa_sm_set_pmk_from_pmksa(sm);
955                 wpa_hexdump_key(MSG_DEBUG, "RSN: PMK from PMKSA cache",
956                                 sm->pmk, sm->pmk_len);
957                 eapol_sm_notify_cached(sm->eapol);
958         } else if (sm->key_mgmt == WPA_KEY_MGMT_IEEE8021X && sm->eapol) {
959                 int res, pmk_len;
960                 pmk_len = PMK_LEN;
961                 res = eapol_sm_get_key(sm->eapol, sm->pmk, PMK_LEN);
962 #ifdef EAP_LEAP
963                 if (res) {
964                         res = eapol_sm_get_key(sm->eapol, sm->pmk, 16);
965                         pmk_len = 16;
966                 }
967 #endif /* EAP_LEAP */
968                 if (res == 0) {
969                         wpa_hexdump_key(MSG_DEBUG, "WPA: PMK from EAPOL state "
970                                         "machines", sm->pmk, pmk_len);
971                         sm->pmk_len = pmk_len;
972                         pmksa_cache_add(sm, sm->pmk, pmk_len, src_addr,
973                                         sm->own_addr, sm->cur_ssid);
974                         if (!sm->cur_pmksa && pmkid &&
975                             pmksa_cache_get(sm, src_addr, pmkid)) {
976                                 wpa_printf(MSG_DEBUG, "RSN: the new PMK "
977                                            "matches with the PMKID");
978                                 abort_cached = 0;
979                         }
980                 } else {
981                         wpa_msg(sm->ctx->ctx, MSG_WARNING,
982                                 "WPA: Failed to get master session key from "
983                                 "EAPOL state machines");
984                         wpa_msg(sm->ctx->ctx, MSG_WARNING,
985                                 "WPA: Key handshake aborted");
986                         if (sm->cur_pmksa) {
987                                 wpa_printf(MSG_DEBUG, "RSN: Cancelled PMKSA "
988                                            "caching attempt");
989                                 sm->cur_pmksa = NULL;
990                                 abort_cached = 1;
991                         } else {
992                                 return -1;
993                         }
994                 }
995         }
996
997         if (abort_cached && sm->key_mgmt == WPA_KEY_MGMT_IEEE8021X) {
998                 /* Send EAPOL-Start to trigger full EAP authentication. */
999                 u8 *buf;
1000                 size_t buflen;
1001
1002                 wpa_printf(MSG_DEBUG, "RSN: no PMKSA entry found - trigger "
1003                            "full EAP authentication");
1004                 buf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_START,
1005                                          NULL, 0, &buflen, NULL);
1006                 if (buf) {
1007                         wpa_sm_ether_send(sm, sm->bssid, ETH_P_EAPOL,
1008                                           buf, buflen);
1009                         free(buf);
1010                 }
1011
1012                 return -1;
1013         }
1014
1015         return 0;
1016 }
1017
1018
1019 static int wpa_supplicant_send_2_of_4(struct wpa_sm *sm,
1020                                       const unsigned char *src_addr,
1021                                       const struct wpa_eapol_key *key,
1022                                       int ver)
1023 {
1024         size_t rlen;
1025         struct wpa_eapol_key *reply;
1026         struct wpa_ptk *ptk;
1027         u8 buf[8], *rbuf, *wpa_ie;
1028         int wpa_ie_len;
1029
1030         if (sm->assoc_wpa_ie == NULL) {
1031                 wpa_printf(MSG_WARNING, "WPA: No assoc_wpa_ie set - cannot "
1032                            "generate msg 2/4");
1033                 return -1;
1034         }
1035
1036         wpa_ie = sm->assoc_wpa_ie;
1037         wpa_ie_len = sm->assoc_wpa_ie_len;
1038         wpa_hexdump(MSG_DEBUG, "WPA: WPA IE for msg 2/4", wpa_ie, wpa_ie_len);
1039
1040         rbuf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_KEY,
1041                                   NULL, sizeof(*reply) + wpa_ie_len,
1042                                   &rlen, (void *) &reply);
1043         if (rbuf == NULL)
1044                 return -1;
1045
1046         reply->type = sm->proto == WPA_PROTO_RSN ?
1047                 EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
1048         WPA_PUT_BE16(reply->key_info,
1049                      ver | WPA_KEY_INFO_KEY_TYPE | WPA_KEY_INFO_MIC);
1050         if (sm->proto == WPA_PROTO_RSN)
1051                 WPA_PUT_BE16(reply->key_length, 0);
1052         else
1053                 memcpy(reply->key_length, key->key_length, 2);
1054         memcpy(reply->replay_counter, key->replay_counter,
1055                WPA_REPLAY_COUNTER_LEN);
1056
1057         WPA_PUT_BE16(reply->key_data_length, wpa_ie_len);
1058         memcpy(reply + 1, wpa_ie, wpa_ie_len);
1059
1060         if (sm->renew_snonce) {
1061                 if (hostapd_get_rand(sm->snonce, WPA_NONCE_LEN)) {
1062                         wpa_msg(sm->ctx->ctx, MSG_WARNING,
1063                                 "WPA: Failed to get random data for SNonce");
1064                         free(rbuf);
1065                         return -1;
1066                 }
1067                 sm->renew_snonce = 0;
1068                 wpa_hexdump(MSG_DEBUG, "WPA: Renewed SNonce",
1069                             sm->snonce, WPA_NONCE_LEN);
1070         }
1071         memcpy(reply->key_nonce, sm->snonce, WPA_NONCE_LEN);
1072
1073         /* Calculate PTK which will be stored as a temporary PTK until it has
1074          * been verified when processing message 3/4. */
1075         ptk = &sm->tptk;
1076         wpa_pmk_to_ptk(sm->pmk, sm->pmk_len, sm->own_addr, src_addr,
1077                        sm->snonce, key->key_nonce,
1078                        (u8 *) ptk, sizeof(*ptk));
1079         /* Supplicant: swap tx/rx Mic keys */
1080         memcpy(buf, ptk->u.auth.tx_mic_key, 8);
1081         memcpy(ptk->u.auth.tx_mic_key, ptk->u.auth.rx_mic_key, 8);
1082         memcpy(ptk->u.auth.rx_mic_key, buf, 8);
1083         sm->tptk_set = 1;
1084
1085         wpa_printf(MSG_DEBUG, "WPA: Sending EAPOL-Key 2/4");
1086         wpa_eapol_key_send(sm, ptk->kck, ver, src_addr, ETH_P_EAPOL,
1087                            rbuf, rlen, reply->key_mic);
1088
1089         return 0;
1090 }
1091
1092
1093 static void wpa_supplicant_process_1_of_4(struct wpa_sm *sm,
1094                                           const unsigned char *src_addr,
1095                                           const struct wpa_eapol_key *key,
1096                                           u16 ver)
1097 {
1098         struct wpa_eapol_ie_parse ie;
1099
1100         if (wpa_sm_get_ssid(sm) == NULL) {
1101                 wpa_printf(MSG_WARNING, "WPA: No SSID info found (msg 1 of "
1102                            "4).");
1103                 return;
1104         }
1105
1106         wpa_sm_set_state(sm, WPA_4WAY_HANDSHAKE);
1107         wpa_printf(MSG_DEBUG, "WPA: RX message 1 of 4-Way Handshake from "
1108                    MACSTR " (ver=%d)", MAC2STR(src_addr), ver);
1109
1110         memset(&ie, 0, sizeof(ie));
1111
1112         if (sm->proto == WPA_PROTO_RSN) {
1113                 /* RSN: msg 1/4 should contain PMKID for the selected PMK */
1114                 const u8 *buf = (const u8 *) (key + 1);
1115                 size_t len = WPA_GET_BE16(key->key_data_length);
1116                 wpa_hexdump(MSG_DEBUG, "RSN: msg 1/4 key data", buf, len);
1117                 wpa_supplicant_parse_ies(buf, len, &ie);
1118                 if (ie.pmkid) {
1119                         wpa_hexdump(MSG_DEBUG, "RSN: PMKID from "
1120                                     "Authenticator", ie.pmkid, PMKID_LEN);
1121                 }
1122         }
1123
1124         if (wpa_supplicant_get_pmk(sm, src_addr, ie.pmkid))
1125                 return;
1126
1127         if (wpa_supplicant_send_2_of_4(sm, src_addr, key, ver))
1128                 return;
1129
1130         memcpy(sm->anonce, key->key_nonce, WPA_NONCE_LEN);
1131 }
1132
1133
1134 static void wpa_sm_start_preauth(void *eloop_ctx, void *timeout_ctx)
1135 {
1136         struct wpa_sm *sm = eloop_ctx;
1137         rsn_preauth_candidate_process(sm);
1138 }
1139
1140
1141 static void wpa_supplicant_key_neg_complete(struct wpa_sm *sm,
1142                                             const u8 *addr, int secure)
1143 {
1144         wpa_msg(sm->ctx->ctx, MSG_INFO, "WPA: Key negotiation completed with "
1145                 MACSTR " [PTK=%s GTK=%s]", MAC2STR(addr),
1146                 wpa_cipher_txt(sm->pairwise_cipher),
1147                 wpa_cipher_txt(sm->group_cipher));
1148         eloop_cancel_timeout(sm->ctx->scan, sm->ctx->ctx, NULL);
1149         wpa_sm_cancel_auth_timeout(sm);
1150         wpa_sm_set_state(sm, WPA_COMPLETED);
1151
1152         if (secure) {
1153                 /* MLME.SETPROTECTION.request(TA, Tx_Rx) */
1154                 eapol_sm_notify_portValid(sm->eapol, TRUE);
1155                 if (sm->key_mgmt == WPA_KEY_MGMT_PSK)
1156                         eapol_sm_notify_eap_success(sm->eapol, TRUE);
1157                 /*
1158                  * Start preauthentication after a short wait to avoid a
1159                  * possible race condition between the data receive and key
1160                  * configuration after the 4-Way Handshake. This increases the
1161                  * likelyhood of the first preauth EAPOL-Start frame getting to
1162                  * the target AP.
1163                  */
1164                 eloop_register_timeout(1, 0, wpa_sm_start_preauth, sm, NULL);
1165         }
1166
1167         if (sm->cur_pmksa && sm->cur_pmksa->opportunistic) {
1168                 wpa_printf(MSG_DEBUG, "RSN: Authenticator accepted "
1169                            "opportunistic PMKSA entry - marking it valid");
1170                 sm->cur_pmksa->opportunistic = 0;
1171         }
1172 }
1173
1174
1175 static int wpa_supplicant_install_ptk(struct wpa_sm *sm,
1176                                       const unsigned char *src_addr,
1177                                       const struct wpa_eapol_key *key)
1178 {
1179         int alg, keylen, rsclen;
1180         const u8 *key_rsc;
1181         u8 null_rsc[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1182
1183         wpa_printf(MSG_DEBUG, "WPA: Installing PTK to the driver.");
1184
1185         switch (sm->pairwise_cipher) {
1186         case WPA_CIPHER_CCMP:
1187                 alg = WPA_ALG_CCMP;
1188                 keylen = 16;
1189                 rsclen = 6;
1190                 break;
1191         case WPA_CIPHER_TKIP:
1192                 alg = WPA_ALG_TKIP;
1193                 keylen = 32;
1194                 rsclen = 6;
1195                 break;
1196         case WPA_CIPHER_NONE:
1197                 wpa_printf(MSG_DEBUG, "WPA: Pairwise Cipher Suite: "
1198                            "NONE - do not use pairwise keys");
1199                 return 0;
1200         default:
1201                 wpa_printf(MSG_WARNING, "WPA: Unsupported pairwise cipher %d",
1202                            sm->pairwise_cipher);
1203                 return -1;
1204         }
1205
1206         if (sm->proto == WPA_PROTO_RSN) {
1207                 key_rsc = null_rsc;
1208         } else {
1209                 key_rsc = key->key_rsc;
1210                 wpa_hexdump(MSG_DEBUG, "WPA: RSC", key_rsc, rsclen);
1211         }
1212
1213         if (wpa_sm_set_key(sm, alg, src_addr, 0, 1, key_rsc, rsclen,
1214                            (u8 *) &sm->ptk.tk1, keylen) < 0) {
1215                 wpa_printf(MSG_WARNING, "WPA: Failed to set PTK to the "
1216                            "driver.");
1217                 return -1;
1218         }
1219         return 0;
1220 }
1221
1222
1223 static int wpa_supplicant_check_group_cipher(int group_cipher,
1224                                              int keylen, int maxkeylen,
1225                                              int *key_rsc_len, int *alg)
1226 {
1227         int ret = 0;
1228
1229         switch (group_cipher) {
1230         case WPA_CIPHER_CCMP:
1231                 if (keylen != 16 || maxkeylen < 16) {
1232                         ret = -1;
1233                         break;
1234                 }
1235                 *key_rsc_len = 6;
1236                 *alg = WPA_ALG_CCMP;
1237                 break;
1238         case WPA_CIPHER_TKIP:
1239                 if (keylen != 32 || maxkeylen < 32) {
1240                         ret = -1;
1241                         break;
1242                 }
1243                 *key_rsc_len = 6;
1244                 *alg = WPA_ALG_TKIP;
1245                 break;
1246         case WPA_CIPHER_WEP104:
1247                 if (keylen != 13 || maxkeylen < 13) {
1248                         ret = -1;
1249                         break;
1250                 }
1251                 *key_rsc_len = 0;
1252                 *alg = WPA_ALG_WEP;
1253                 break;
1254         case WPA_CIPHER_WEP40:
1255                 if (keylen != 5 || maxkeylen < 5) {
1256                         ret = -1;
1257                         break;
1258                 }
1259                 *key_rsc_len = 0;
1260                 *alg = WPA_ALG_WEP;
1261                 break;
1262         default:
1263                 wpa_printf(MSG_WARNING, "WPA: Unsupported Group Cipher %d",
1264                            group_cipher);
1265                 return -1;
1266         }
1267
1268         if (ret < 0 ) {
1269                 wpa_printf(MSG_WARNING, "WPA: Unsupported %s Group Cipher key "
1270                            "length %d (%d).",
1271                            wpa_cipher_txt(group_cipher), keylen, maxkeylen);
1272         }
1273
1274         return ret;
1275 }
1276
1277
1278 struct wpa_gtk_data {
1279         int alg, tx, key_rsc_len, keyidx;
1280         u8 gtk[32];
1281         int gtk_len;
1282 };
1283
1284
1285 static int wpa_supplicant_install_gtk(struct wpa_sm *sm,
1286                                       const struct wpa_gtk_data *gd,
1287                                       const u8 *key_rsc)
1288 {
1289         const u8 *_gtk = gd->gtk;
1290         u8 gtk_buf[32];
1291
1292         wpa_hexdump_key(MSG_DEBUG, "WPA: Group Key", gd->gtk, gd->gtk_len);
1293         wpa_printf(MSG_DEBUG, "WPA: Installing GTK to the driver "
1294                    "(keyidx=%d tx=%d).", gd->keyidx, gd->tx);
1295         wpa_hexdump(MSG_DEBUG, "WPA: RSC", key_rsc, gd->key_rsc_len);
1296         if (sm->group_cipher == WPA_CIPHER_TKIP) {
1297                 /* Swap Tx/Rx keys for Michael MIC */
1298                 memcpy(gtk_buf, gd->gtk, 16);
1299                 memcpy(gtk_buf + 16, gd->gtk + 24, 8);
1300                 memcpy(gtk_buf + 24, gd->gtk + 16, 8);
1301                 _gtk = gtk_buf;
1302         }
1303         if (sm->pairwise_cipher == WPA_CIPHER_NONE) {
1304                 if (wpa_sm_set_key(sm, gd->alg,
1305                                    (u8 *) "\xff\xff\xff\xff\xff\xff",
1306                                    gd->keyidx, 1, key_rsc, gd->key_rsc_len,
1307                                    _gtk, gd->gtk_len) < 0) {
1308                         wpa_printf(MSG_WARNING, "WPA: Failed to set "
1309                                    "GTK to the driver (Group only).");
1310                         return -1;
1311                 }
1312         } else if (wpa_sm_set_key(sm, gd->alg,
1313                                   (u8 *) "\xff\xff\xff\xff\xff\xff",
1314                                   gd->keyidx, gd->tx, key_rsc, gd->key_rsc_len,
1315                                   _gtk, gd->gtk_len) < 0) {
1316                 wpa_printf(MSG_WARNING, "WPA: Failed to set GTK to "
1317                            "the driver.");
1318                 return -1;
1319         }
1320
1321         return 0;
1322 }
1323
1324
1325 static int wpa_supplicant_gtk_tx_bit_workaround(const struct wpa_sm *sm,
1326                                                 int tx)
1327 {
1328         if (tx && sm->pairwise_cipher != WPA_CIPHER_NONE) {
1329                 /* Ignore Tx bit for GTK if a pairwise key is used. One AP
1330                  * seemed to set this bit (incorrectly, since Tx is only when
1331                  * doing Group Key only APs) and without this workaround, the
1332                  * data connection does not work because wpa_supplicant
1333                  * configured non-zero keyidx to be used for unicast. */
1334                 wpa_printf(MSG_INFO, "WPA: Tx bit set for GTK, but pairwise "
1335                            "keys are used - ignore Tx bit");
1336                 return 0;
1337         }
1338         return tx;
1339 }
1340
1341
1342 static int wpa_supplicant_pairwise_gtk(struct wpa_sm *sm,
1343                                        const unsigned char *src_addr,
1344                                        const struct wpa_eapol_key *key,
1345                                        const u8 *gtk, int gtk_len,
1346                                        int key_info)
1347 {
1348         struct wpa_gtk_data gd;
1349
1350         /*
1351          * IEEE Std 802.11i-2004 - 8.5.2 EAPOL-Key frames - Figure 43x
1352          * GTK KDE format:
1353          * KeyID[bits 0-1], Tx [bit 2], Reserved [bits 3-7]
1354          * Reserved [bits 0-7]
1355          * GTK
1356          */
1357
1358         memset(&gd, 0, sizeof(gd));
1359         wpa_hexdump_key(MSG_DEBUG, "RSN: received GTK in pairwise handshake",
1360                         gtk, gtk_len);
1361
1362         if (gtk_len < 2 || gtk_len - 2 > sizeof(gd.gtk))
1363                 return -1;
1364
1365         gd.keyidx = gtk[0] & 0x3;
1366         gd.tx = wpa_supplicant_gtk_tx_bit_workaround(sm,
1367                                                      !!(gtk[0] & BIT(2)));
1368         gtk += 2;
1369         gtk_len -= 2;
1370
1371         memcpy(gd.gtk, gtk, gtk_len);
1372         gd.gtk_len = gtk_len;
1373
1374         if (wpa_supplicant_check_group_cipher(sm->group_cipher,
1375                                               gtk_len, gtk_len,
1376                                               &gd.key_rsc_len, &gd.alg) ||
1377             wpa_supplicant_install_gtk(sm, &gd, key->key_rsc)) {
1378                 wpa_printf(MSG_DEBUG, "RSN: Failed to install GTK");
1379                 return -1;
1380         }
1381
1382         wpa_supplicant_key_neg_complete(sm, src_addr,
1383                                         key_info & WPA_KEY_INFO_SECURE);
1384         return 0;
1385 }
1386
1387
1388 static void wpa_report_ie_mismatch(struct wpa_sm *sm,
1389                                    const char *reason, const u8 *src_addr,
1390                                    const u8 *wpa_ie, size_t wpa_ie_len,
1391                                    const u8 *rsn_ie, size_t rsn_ie_len)
1392 {
1393         wpa_msg(sm->ctx->ctx, MSG_WARNING, "WPA: %s (src=" MACSTR ")",
1394                 reason, MAC2STR(src_addr));
1395
1396         if (sm->ap_wpa_ie) {
1397                 wpa_hexdump(MSG_INFO, "WPA: WPA IE in Beacon/ProbeResp",
1398                             sm->ap_wpa_ie, sm->ap_wpa_ie_len);
1399         }
1400         if (wpa_ie) {
1401                 if (!sm->ap_wpa_ie) {
1402                         wpa_printf(MSG_INFO, "WPA: No WPA IE in "
1403                                    "Beacon/ProbeResp");
1404                 }
1405                 wpa_hexdump(MSG_INFO, "WPA: WPA IE in 3/4 msg",
1406                             wpa_ie, wpa_ie_len);
1407         }
1408
1409         if (sm->ap_rsn_ie) {
1410                 wpa_hexdump(MSG_INFO, "WPA: RSN IE in Beacon/ProbeResp",
1411                             sm->ap_rsn_ie, sm->ap_rsn_ie_len);
1412         }
1413         if (rsn_ie) {
1414                 if (!sm->ap_rsn_ie) {
1415                         wpa_printf(MSG_INFO, "WPA: No RSN IE in "
1416                                    "Beacon/ProbeResp");
1417                 }
1418                 wpa_hexdump(MSG_INFO, "WPA: RSN IE in 3/4 msg",
1419                             rsn_ie, rsn_ie_len);
1420         }
1421
1422         wpa_sm_disassociate(sm, REASON_IE_IN_4WAY_DIFFERS);
1423         wpa_sm_req_scan(sm, 0, 0);
1424 }
1425
1426
1427 static int wpa_supplicant_validate_ie(struct wpa_sm *sm,
1428                                       const unsigned char *src_addr,
1429                                       struct wpa_eapol_ie_parse *ie)
1430 {
1431         struct wpa_ssid *ssid = sm->cur_ssid;
1432
1433         if (sm->ap_wpa_ie == NULL && sm->ap_rsn_ie == NULL) {
1434                 wpa_printf(MSG_DEBUG, "WPA: No WPA/RSN IE for this AP known. "
1435                            "Trying to get from scan results");
1436                 if (wpa_sm_get_beacon_ie(sm) < 0) {
1437                         wpa_printf(MSG_WARNING, "WPA: Could not find AP from "
1438                                    "the scan results");
1439                 } else {
1440                         wpa_printf(MSG_DEBUG, "WPA: Found the current AP from "
1441                                    "updated scan results");
1442                 }
1443         }
1444
1445         if ((ie->wpa_ie && sm->ap_wpa_ie &&
1446              (ie->wpa_ie_len != sm->ap_wpa_ie_len ||
1447               memcmp(ie->wpa_ie, sm->ap_wpa_ie, ie->wpa_ie_len) != 0)) ||
1448             (ie->rsn_ie && sm->ap_rsn_ie &&
1449              (ie->rsn_ie_len != sm->ap_rsn_ie_len ||
1450               memcmp(ie->rsn_ie, sm->ap_rsn_ie, ie->rsn_ie_len) != 0))) {
1451                 wpa_report_ie_mismatch(sm, "IE in 3/4 msg does not match "
1452                                        "with IE in Beacon/ProbeResp",
1453                                        src_addr, ie->wpa_ie, ie->wpa_ie_len,
1454                                        ie->rsn_ie, ie->rsn_ie_len);
1455                 return -1;
1456         }
1457
1458         if (sm->proto == WPA_PROTO_WPA &&
1459             ie->rsn_ie && sm->ap_rsn_ie == NULL &&
1460             ssid && (ssid->proto & WPA_PROTO_RSN)) {
1461                 wpa_report_ie_mismatch(sm, "Possible downgrade attack "
1462                                        "detected - RSN was enabled and RSN IE "
1463                                        "was in msg 3/4, but not in "
1464                                        "Beacon/ProbeResp",
1465                                        src_addr, ie->wpa_ie, ie->wpa_ie_len,
1466                                        ie->rsn_ie, ie->rsn_ie_len);
1467                 return -1;
1468         }
1469
1470         return 0;
1471 }
1472
1473
1474 static int wpa_supplicant_send_4_of_4(struct wpa_sm *sm,
1475                                       const unsigned char *src_addr,
1476                                       const struct wpa_eapol_key *key,
1477                                       u16 ver, u16 key_info)
1478 {
1479         size_t rlen;
1480         struct wpa_eapol_key *reply;
1481         u8 *rbuf;
1482
1483         rbuf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_KEY, NULL,
1484                                   sizeof(*reply), &rlen, (void *) &reply);
1485         if (rbuf == NULL)
1486                 return -1;
1487
1488         reply->type = sm->proto == WPA_PROTO_RSN ?
1489                 EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
1490         key_info &= WPA_KEY_INFO_SECURE;
1491         key_info |= ver | WPA_KEY_INFO_KEY_TYPE | WPA_KEY_INFO_MIC;
1492         WPA_PUT_BE16(reply->key_info, key_info);
1493         if (sm->proto == WPA_PROTO_RSN)
1494                 WPA_PUT_BE16(reply->key_length, 0);
1495         else
1496                 memcpy(reply->key_length, key->key_length, 2);
1497         memcpy(reply->replay_counter, key->replay_counter,
1498                WPA_REPLAY_COUNTER_LEN);
1499
1500         WPA_PUT_BE16(reply->key_data_length, 0);
1501
1502         wpa_printf(MSG_DEBUG, "WPA: Sending EAPOL-Key 4/4");
1503         wpa_eapol_key_send(sm, sm->ptk.kck, ver, src_addr, ETH_P_EAPOL,
1504                            rbuf, rlen, reply->key_mic);
1505
1506         return 0;
1507 }
1508
1509
1510 static void wpa_supplicant_process_3_of_4(struct wpa_sm *sm,
1511                                           const unsigned char *src_addr,
1512                                           const struct wpa_eapol_key *key,
1513                                           int extra_len, u16 ver)
1514 {
1515         u16 key_info, keylen, len;
1516         const u8 *pos;
1517         struct wpa_eapol_ie_parse ie;
1518
1519         wpa_sm_set_state(sm, WPA_4WAY_HANDSHAKE);
1520         wpa_printf(MSG_DEBUG, "WPA: RX message 3 of 4-Way Handshake from "
1521                    MACSTR " (ver=%d)", MAC2STR(src_addr), ver);
1522
1523         key_info = WPA_GET_BE16(key->key_info);
1524
1525         pos = (const u8 *) (key + 1);
1526         len = WPA_GET_BE16(key->key_data_length);
1527         wpa_hexdump(MSG_DEBUG, "WPA: IE KeyData", pos, len);
1528         wpa_supplicant_parse_ies(pos, len, &ie);
1529         if (ie.gtk && !(key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
1530                 wpa_printf(MSG_WARNING, "WPA: GTK IE in unencrypted key data");
1531                 return;
1532         }
1533
1534         if (wpa_supplicant_validate_ie(sm, src_addr, &ie) < 0)
1535                 return;
1536
1537         if (memcmp(sm->anonce, key->key_nonce, WPA_NONCE_LEN) != 0) {
1538                 wpa_printf(MSG_WARNING, "WPA: ANonce from message 1 of 4-Way "
1539                            "Handshake differs from 3 of 4-Way Handshake - drop"
1540                            " packet (src=" MACSTR ")", MAC2STR(src_addr));
1541                 return;
1542         }
1543
1544         keylen = WPA_GET_BE16(key->key_length);
1545         switch (sm->pairwise_cipher) {
1546         case WPA_CIPHER_CCMP:
1547                 if (keylen != 16) {
1548                         wpa_printf(MSG_WARNING, "WPA: Invalid CCMP key length "
1549                                    "%d (src=" MACSTR ")",
1550                                    keylen, MAC2STR(src_addr));
1551                         return;
1552                 }
1553                 break;
1554         case WPA_CIPHER_TKIP:
1555                 if (keylen != 32) {
1556                         wpa_printf(MSG_WARNING, "WPA: Invalid TKIP key length "
1557                                    "%d (src=" MACSTR ")",
1558                                    keylen, MAC2STR(src_addr));
1559                         return;
1560                 }
1561                 break;
1562         }
1563
1564         if (wpa_supplicant_send_4_of_4(sm, src_addr, key, ver, key_info))
1565                 return;
1566
1567         /* SNonce was successfully used in msg 3/4, so mark it to be renewed
1568          * for the next 4-Way Handshake. If msg 3 is received again, the old
1569          * SNonce will still be used to avoid changing PTK. */
1570         sm->renew_snonce = 1;
1571
1572         if (key_info & WPA_KEY_INFO_INSTALL) {
1573                 wpa_supplicant_install_ptk(sm, src_addr, key);
1574         }
1575
1576         if (key_info & WPA_KEY_INFO_SECURE) {
1577                 /* MLME.SETPROTECTION.request(TA, Tx_Rx) */
1578                 eapol_sm_notify_portValid(sm->eapol, TRUE);
1579         }
1580         wpa_sm_set_state(sm, WPA_GROUP_HANDSHAKE);
1581
1582         if (ie.gtk &&
1583             wpa_supplicant_pairwise_gtk(sm, src_addr, key,
1584                                         ie.gtk, ie.gtk_len, key_info) < 0) {
1585                 wpa_printf(MSG_INFO, "RSN: Failed to configure GTK");
1586         }
1587 }
1588
1589
1590 static int wpa_supplicant_process_1_of_2_rsn(struct wpa_sm *sm,
1591                                              const u8 *keydata,
1592                                              size_t keydatalen,
1593                                              int key_info,
1594                                              struct wpa_gtk_data *gd)
1595 {
1596         int maxkeylen;
1597         struct wpa_eapol_ie_parse ie;
1598
1599         wpa_hexdump(MSG_DEBUG, "RSN: msg 1/2 key data", keydata, keydatalen);
1600         wpa_supplicant_parse_ies(keydata, keydatalen, &ie);
1601         if (ie.gtk && !(key_info & WPA_KEY_INFO_ENCR_KEY_DATA)) {
1602                 wpa_printf(MSG_WARNING, "WPA: GTK IE in unencrypted key data");
1603                 return -1;
1604         }
1605         if (ie.gtk == NULL) {
1606                 wpa_printf(MSG_INFO, "WPA: No GTK IE in Group Key msg 1/2");
1607                 return -1;
1608         }
1609         maxkeylen = gd->gtk_len = ie.gtk_len - 2;
1610
1611         if (wpa_supplicant_check_group_cipher(sm->group_cipher,
1612                                               gd->gtk_len, maxkeylen,
1613                                               &gd->key_rsc_len, &gd->alg))
1614                 return -1;
1615
1616         wpa_hexdump(MSG_DEBUG, "RSN: received GTK in group key handshake",
1617                     ie.gtk, ie.gtk_len);
1618         gd->keyidx = ie.gtk[0] & 0x3;
1619         gd->tx = wpa_supplicant_gtk_tx_bit_workaround(sm,
1620                                                       !!(ie.gtk[0] & BIT(2)));
1621         if (ie.gtk_len - 2 > sizeof(gd->gtk)) {
1622                 wpa_printf(MSG_INFO, "RSN: Too long GTK in GTK IE "
1623                            "(len=%lu)", (unsigned long) ie.gtk_len - 2);
1624                 return -1;
1625         }
1626         memcpy(gd->gtk, ie.gtk + 2, ie.gtk_len - 2);
1627
1628         return 0;
1629 }
1630
1631
1632 static int wpa_supplicant_process_1_of_2_wpa(struct wpa_sm *sm,
1633                                              const struct wpa_eapol_key *key,
1634                                              size_t keydatalen, int key_info,
1635                                              int extra_len, u16 ver,
1636                                              struct wpa_gtk_data *gd)
1637 {
1638         int maxkeylen;
1639         u8 ek[32];
1640
1641         gd->gtk_len = WPA_GET_BE16(key->key_length);
1642         maxkeylen = keydatalen;
1643         if (keydatalen > extra_len) {
1644                 wpa_printf(MSG_INFO, "WPA: Truncated EAPOL-Key packet:"
1645                            " key_data_length=%lu > extra_len=%d",
1646                            (unsigned long) keydatalen, extra_len);
1647                 return -1;
1648         }
1649         if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES)
1650                 maxkeylen -= 8;
1651
1652         if (wpa_supplicant_check_group_cipher(sm->group_cipher,
1653                                               gd->gtk_len, maxkeylen,
1654                                               &gd->key_rsc_len, &gd->alg))
1655                 return -1;
1656
1657         gd->keyidx = (key_info & WPA_KEY_INFO_KEY_INDEX_MASK) >>
1658                 WPA_KEY_INFO_KEY_INDEX_SHIFT;
1659         if (ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4) {
1660                 memcpy(ek, key->key_iv, 16);
1661                 memcpy(ek + 16, sm->ptk.kek, 16);
1662                 if (keydatalen > sizeof(gd->gtk)) {
1663                         wpa_printf(MSG_WARNING, "WPA: RC4 key data "
1664                                    "too long (%lu)",
1665                                    (unsigned long) keydatalen);
1666                         return -1;
1667                 }
1668                 memcpy(gd->gtk, key + 1, keydatalen);
1669                 rc4_skip(ek, 32, 256, gd->gtk, keydatalen);
1670         } else if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1671                 if (keydatalen % 8) {
1672                         wpa_printf(MSG_WARNING, "WPA: Unsupported AES-WRAP "
1673                                    "len %lu", (unsigned long) keydatalen);
1674                         return -1;
1675                 }
1676                 if (maxkeylen > sizeof(gd->gtk)) {
1677                         wpa_printf(MSG_WARNING, "WPA: AES-WRAP key data "
1678                                    "too long (keydatalen=%lu maxkeylen=%lu)",
1679                                    (unsigned long) keydatalen,
1680                                    (unsigned long) maxkeylen);
1681                         return -1;
1682                 }
1683                 if (aes_unwrap(sm->ptk.kek, maxkeylen / 8,
1684                                (const u8 *) (key + 1), gd->gtk)) {
1685                         wpa_printf(MSG_WARNING, "WPA: AES unwrap "
1686                                    "failed - could not decrypt GTK");
1687                         return -1;
1688                 }
1689         }
1690         gd->tx = wpa_supplicant_gtk_tx_bit_workaround(
1691                 sm, !!(key_info & WPA_KEY_INFO_TXRX));
1692         return 0;
1693 }
1694
1695
1696 static int wpa_supplicant_send_2_of_2(struct wpa_sm *sm,
1697                                       const unsigned char *src_addr,
1698                                       const struct wpa_eapol_key *key,
1699                                       int ver, u16 key_info)
1700 {
1701         size_t rlen;
1702         struct wpa_eapol_key *reply;
1703         u8 *rbuf;
1704
1705         rbuf = wpa_sm_alloc_eapol(sm, IEEE802_1X_TYPE_EAPOL_KEY, NULL,
1706                                   sizeof(*reply), &rlen, (void *) &reply);
1707         if (rbuf == NULL)
1708                 return -1;
1709
1710         reply->type = sm->proto == WPA_PROTO_RSN ?
1711                 EAPOL_KEY_TYPE_RSN : EAPOL_KEY_TYPE_WPA;
1712         key_info &= WPA_KEY_INFO_KEY_INDEX_MASK;
1713         key_info |= ver | WPA_KEY_INFO_MIC | WPA_KEY_INFO_SECURE;
1714         WPA_PUT_BE16(reply->key_info, key_info);
1715         if (sm->proto == WPA_PROTO_RSN)
1716                 WPA_PUT_BE16(reply->key_length, 0);
1717         else
1718                 memcpy(reply->key_length, key->key_length, 2);
1719         memcpy(reply->replay_counter, key->replay_counter,
1720                WPA_REPLAY_COUNTER_LEN);
1721
1722         WPA_PUT_BE16(reply->key_data_length, 0);
1723
1724         wpa_printf(MSG_DEBUG, "WPA: Sending EAPOL-Key 2/2");
1725         wpa_eapol_key_send(sm, sm->ptk.kck, ver, src_addr, ETH_P_EAPOL,
1726                            rbuf, rlen, reply->key_mic);
1727
1728         return 0;
1729 }
1730
1731
1732 static void wpa_supplicant_process_1_of_2(struct wpa_sm *sm,
1733                                           const unsigned char *src_addr,
1734                                           const struct wpa_eapol_key *key,
1735                                           int extra_len, u16 ver)
1736 {
1737         u16 key_info, keydatalen;
1738         int rekey;
1739         struct wpa_gtk_data gd;
1740
1741         memset(&gd, 0, sizeof(gd));
1742
1743         rekey = wpa_sm_get_state(sm) == WPA_COMPLETED;
1744         wpa_sm_set_state(sm, WPA_GROUP_HANDSHAKE);
1745         wpa_printf(MSG_DEBUG, "WPA: RX message 1 of Group Key Handshake from "
1746                    MACSTR " (ver=%d)", MAC2STR(src_addr), ver);
1747
1748         key_info = WPA_GET_BE16(key->key_info);
1749         keydatalen = WPA_GET_BE16(key->key_data_length);
1750
1751         if (sm->proto == WPA_PROTO_RSN) {
1752                 if (wpa_supplicant_process_1_of_2_rsn(sm,
1753                                                       (const u8 *) (key + 1),
1754                                                       keydatalen, key_info,
1755                                                       &gd))
1756                         return;
1757         } else {
1758                 if (wpa_supplicant_process_1_of_2_wpa(sm, key, keydatalen,
1759                                                       key_info, extra_len,
1760                                                       ver, &gd))
1761                         return;
1762         }
1763
1764         if (wpa_supplicant_install_gtk(sm, &gd, key->key_rsc) ||
1765             wpa_supplicant_send_2_of_2(sm, src_addr, key, ver, key_info))
1766                 return;
1767
1768         if (rekey) {
1769                 wpa_msg(sm->ctx->ctx, MSG_INFO, "WPA: Group rekeying "
1770                         "completed with " MACSTR " [GTK=%s]",
1771                         MAC2STR(src_addr), wpa_cipher_txt(sm->group_cipher));
1772                 wpa_sm_set_state(sm, WPA_COMPLETED);
1773         } else {
1774                 wpa_supplicant_key_neg_complete(sm, src_addr,
1775                                                 key_info &
1776                                                 WPA_KEY_INFO_SECURE);
1777         }
1778 }
1779
1780
1781 static int wpa_supplicant_verify_eapol_key_mic(struct wpa_sm *sm,
1782                                                struct wpa_eapol_key *key,
1783                                                u16 ver,
1784                                                const u8 *buf, size_t len)
1785 {
1786         u8 mic[16];
1787         int ok = 0;
1788
1789         memcpy(mic, key->key_mic, 16);
1790         if (sm->tptk_set) {
1791                 memset(key->key_mic, 0, 16);
1792                 wpa_eapol_key_mic(sm->tptk.kck, ver, buf, len,
1793                                   key->key_mic);
1794                 if (memcmp(mic, key->key_mic, 16) != 0) {
1795                         wpa_printf(MSG_WARNING, "WPA: Invalid EAPOL-Key MIC "
1796                                    "when using TPTK - ignoring TPTK");
1797                 } else {
1798                         ok = 1;
1799                         sm->tptk_set = 0;
1800                         sm->ptk_set = 1;
1801                         memcpy(&sm->ptk, &sm->tptk, sizeof(sm->ptk));
1802                 }
1803         }
1804
1805         if (!ok && sm->ptk_set) {
1806                 memset(key->key_mic, 0, 16);
1807                 wpa_eapol_key_mic(sm->ptk.kck, ver, buf, len,
1808                                   key->key_mic);
1809                 if (memcmp(mic, key->key_mic, 16) != 0) {
1810                         wpa_printf(MSG_WARNING, "WPA: Invalid EAPOL-Key MIC "
1811                                    "- dropping packet");
1812                         return -1;
1813                 }
1814                 ok = 1;
1815         }
1816
1817         if (!ok) {
1818                 wpa_printf(MSG_WARNING, "WPA: Could not verify EAPOL-Key MIC "
1819                            "- dropping packet");
1820                 return -1;
1821         }
1822
1823         memcpy(sm->rx_replay_counter, key->replay_counter,
1824                WPA_REPLAY_COUNTER_LEN);
1825         sm->rx_replay_counter_set = 1;
1826         return 0;
1827 }
1828
1829
1830 /* Decrypt RSN EAPOL-Key key data (RC4 or AES-WRAP) */
1831 static int wpa_supplicant_decrypt_key_data(struct wpa_sm *sm,
1832                                            struct wpa_eapol_key *key, u16 ver)
1833 {
1834         u16 keydatalen = WPA_GET_BE16(key->key_data_length);
1835
1836         wpa_hexdump(MSG_DEBUG, "RSN: encrypted key data",
1837                     (u8 *) (key + 1), keydatalen);
1838         if (!sm->ptk_set) {
1839                 wpa_printf(MSG_WARNING, "WPA: PTK not available, "
1840                            "cannot decrypt EAPOL-Key key data.");
1841                 return -1;
1842         }
1843
1844         /* Decrypt key data here so that this operation does not need
1845          * to be implemented separately for each message type. */
1846         if (ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4) {
1847                 u8 ek[32];
1848                 memcpy(ek, key->key_iv, 16);
1849                 memcpy(ek + 16, sm->ptk.kek, 16);
1850                 rc4_skip(ek, 32, 256, (u8 *) (key + 1), keydatalen);
1851         } else if (ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1852                 u8 *buf;
1853                 if (keydatalen % 8) {
1854                         wpa_printf(MSG_WARNING, "WPA: Unsupported "
1855                                    "AES-WRAP len %d", keydatalen);
1856                         return -1;
1857                 }
1858                 keydatalen -= 8; /* AES-WRAP adds 8 bytes */
1859                 buf = malloc(keydatalen);
1860                 if (buf == NULL) {
1861                         wpa_printf(MSG_WARNING, "WPA: No memory for "
1862                                    "AES-UNWRAP buffer");
1863                         return -1;
1864                 }
1865                 if (aes_unwrap(sm->ptk.kek, keydatalen / 8,
1866                                (u8 *) (key + 1), buf)) {
1867                         free(buf);
1868                         wpa_printf(MSG_WARNING, "WPA: AES unwrap failed - "
1869                                    "could not decrypt EAPOL-Key key data");
1870                         return -1;
1871                 }
1872                 memcpy(key + 1, buf, keydatalen);
1873                 free(buf);
1874                 WPA_PUT_BE16(key->key_data_length, keydatalen);
1875         }
1876         wpa_hexdump_key(MSG_DEBUG, "WPA: decrypted EAPOL-Key key data",
1877                         (u8 *) (key + 1), keydatalen);
1878         return 0;
1879 }
1880
1881
1882 /**
1883  * wpa_sm_rx_eapol - Process received WPA EAPOL frames
1884  * @sm: Pointer to WPA state machine data from wpa_sm_init()
1885  * @src_addr: Source MAC address of the EAPOL packet
1886  * @buf: Pointer to the beginning of the EAPOL data (EAPOL header)
1887  * @len: Length of the EAPOL frame
1888  * Returns: 1 = WPA EAPOL-Key processed, 0 = not a WPA EAPOL-Key, -1 failure
1889  *
1890  * This function is called for each received EAPOL frame. Other than EAPOL-Key
1891  * frames can be skipped if filtering is done elsewhere. wpa_sm_rx_eapol() is
1892  * only processing WPA and WPA2 EAPOL-Key frames.
1893  *
1894  * The received EAPOL-Key packets are validated and valid packets are replied
1895  * to. In addition, key material (PTK, GTK) is configured at the end of a
1896  * successful key handshake.
1897  */
1898 int wpa_sm_rx_eapol(struct wpa_sm *sm, const u8 *src_addr,
1899                     const u8 *buf, size_t len)
1900 {
1901         size_t plen, data_len, extra_len;
1902         struct ieee802_1x_hdr *hdr;
1903         struct wpa_eapol_key *key;
1904         u16 key_info, ver;
1905         u8 *tmp;
1906         int ret = -1;
1907
1908         if (len < sizeof(*hdr) + sizeof(*key)) {
1909                 wpa_printf(MSG_DEBUG, "WPA: EAPOL frame too short to be a WPA "
1910                            "EAPOL-Key (len %lu, expecting at least %lu)",
1911                            (unsigned long) len,
1912                            (unsigned long) sizeof(*hdr) + sizeof(*key));
1913                 return 0;
1914         }
1915
1916         tmp = malloc(len);
1917         if (tmp == NULL)
1918                 return -1;
1919         memcpy(tmp, buf, len);
1920
1921         hdr = (struct ieee802_1x_hdr *) tmp;
1922         key = (struct wpa_eapol_key *) (hdr + 1);
1923         plen = ntohs(hdr->length);
1924         data_len = plen + sizeof(*hdr);
1925         wpa_printf(MSG_DEBUG, "IEEE 802.1X RX: version=%d type=%d length=%lu",
1926                    hdr->version, hdr->type, (unsigned long) plen);
1927
1928         if (hdr->version < EAPOL_VERSION) {
1929                 /* TODO: backwards compatibility */
1930         }
1931         if (hdr->type != IEEE802_1X_TYPE_EAPOL_KEY) {
1932                 wpa_printf(MSG_DEBUG, "WPA: EAPOL frame (type %u) discarded, "
1933                         "not a Key frame", hdr->type);
1934                 if (sm->cur_pmksa) {
1935                         wpa_printf(MSG_DEBUG, "WPA: Cancelling PMKSA caching "
1936                                    "attempt - attempt full EAP "
1937                                    "authentication");
1938                         eapol_sm_notify_pmkid_attempt(sm->eapol, 0);
1939                 }
1940                 ret = 0;
1941                 goto out;
1942         }
1943         if (plen > len - sizeof(*hdr) || plen < sizeof(*key)) {
1944                 wpa_printf(MSG_DEBUG, "WPA: EAPOL frame payload size %lu "
1945                            "invalid (frame size %lu)",
1946                            (unsigned long) plen, (unsigned long) len);
1947                 ret = 0;
1948                 goto out;
1949         }
1950
1951         wpa_printf(MSG_DEBUG, "  EAPOL-Key type=%d", key->type);
1952         if (key->type != EAPOL_KEY_TYPE_WPA && key->type != EAPOL_KEY_TYPE_RSN)
1953         {
1954                 wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key type (%d) unknown, "
1955                            "discarded", key->type);
1956                 ret = 0;
1957                 goto out;
1958         }
1959
1960         eapol_sm_notify_lower_layer_success(sm->eapol);
1961         wpa_hexdump(MSG_MSGDUMP, "WPA: RX EAPOL-Key", tmp, len);
1962         if (data_len < len) {
1963                 wpa_printf(MSG_DEBUG, "WPA: ignoring %lu bytes after the IEEE "
1964                            "802.1X data", (unsigned long) len - data_len);
1965         }
1966         key_info = WPA_GET_BE16(key->key_info);
1967         ver = key_info & WPA_KEY_INFO_TYPE_MASK;
1968         if (ver != WPA_KEY_INFO_TYPE_HMAC_MD5_RC4 &&
1969             ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1970                 wpa_printf(MSG_INFO, "WPA: Unsupported EAPOL-Key descriptor "
1971                            "version %d.", ver);
1972                 goto out;
1973         }
1974
1975         if (sm->pairwise_cipher == WPA_CIPHER_CCMP &&
1976             ver != WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
1977                 wpa_printf(MSG_INFO, "WPA: CCMP is used, but EAPOL-Key "
1978                            "descriptor version (%d) is not 2.", ver);
1979                 if (sm->group_cipher != WPA_CIPHER_CCMP &&
1980                     !(key_info & WPA_KEY_INFO_KEY_TYPE)) {
1981                         /* Earlier versions of IEEE 802.11i did not explicitly
1982                          * require version 2 descriptor for all EAPOL-Key
1983                          * packets, so allow group keys to use version 1 if
1984                          * CCMP is not used for them. */
1985                         wpa_printf(MSG_INFO, "WPA: Backwards compatibility: "
1986                                    "allow invalid version for non-CCMP group "
1987                                    "keys");
1988                 } else
1989                         goto out;
1990         }
1991
1992         if (sm->rx_replay_counter_set &&
1993             memcmp(key->replay_counter, sm->rx_replay_counter,
1994                    WPA_REPLAY_COUNTER_LEN) <= 0) {
1995                 wpa_printf(MSG_WARNING, "WPA: EAPOL-Key Replay Counter did not"
1996                            " increase - dropping packet");
1997                 goto out;
1998         }
1999
2000         if (!(key_info & WPA_KEY_INFO_ACK)) {
2001                 wpa_printf(MSG_INFO, "WPA: No Ack bit in key_info");
2002                 goto out;
2003         }
2004
2005         if (key_info & WPA_KEY_INFO_REQUEST) {
2006                 wpa_printf(MSG_INFO, "WPA: EAPOL-Key with Request bit - "
2007                            "dropped");
2008                 goto out;
2009         }
2010
2011         if ((key_info & WPA_KEY_INFO_MIC) &&
2012             wpa_supplicant_verify_eapol_key_mic(sm, key, ver, tmp, data_len))
2013                 goto out;
2014
2015         extra_len = data_len - sizeof(*hdr) - sizeof(*key);
2016
2017         if (WPA_GET_BE16(key->key_data_length) > extra_len) {
2018                 wpa_msg(sm->ctx->ctx, MSG_INFO, "WPA: Invalid EAPOL-Key "
2019                         "frame - key_data overflow (%d > %lu)",
2020                         WPA_GET_BE16(key->key_data_length),
2021                         (unsigned long) extra_len);
2022                 goto out;
2023         }
2024
2025         if (sm->proto == WPA_PROTO_RSN &&
2026             (key_info & WPA_KEY_INFO_ENCR_KEY_DATA) &&
2027             wpa_supplicant_decrypt_key_data(sm, key, ver))
2028                 goto out;
2029
2030         if (key_info & WPA_KEY_INFO_KEY_TYPE) {
2031                 if (key_info & WPA_KEY_INFO_KEY_INDEX_MASK) {
2032                         wpa_printf(MSG_WARNING, "WPA: Ignored EAPOL-Key "
2033                                    "(Pairwise) with non-zero key index");
2034                         goto out;
2035                 }
2036                 if (key_info & WPA_KEY_INFO_MIC) {
2037                         /* 3/4 4-Way Handshake */
2038                         wpa_supplicant_process_3_of_4(sm, src_addr, key,
2039                                                       extra_len, ver);
2040                 } else {
2041                         /* 1/4 4-Way Handshake */
2042                         wpa_supplicant_process_1_of_4(sm, src_addr, key,
2043                                                       ver);
2044                 }
2045         } else {
2046                 if (key_info & WPA_KEY_INFO_MIC) {
2047                         /* 1/2 Group Key Handshake */
2048                         wpa_supplicant_process_1_of_2(sm, src_addr, key,
2049                                                       extra_len, ver);
2050                 } else {
2051                         wpa_printf(MSG_WARNING, "WPA: EAPOL-Key (Group) "
2052                                    "without Mic bit - dropped");
2053                 }
2054         }
2055
2056         ret = 1;
2057
2058 out:
2059         free(tmp);
2060         return ret;
2061 }
2062
2063
2064 static int wpa_cipher_bits(int cipher)
2065 {
2066         switch (cipher) {
2067         case WPA_CIPHER_CCMP:
2068                 return 128;
2069         case WPA_CIPHER_TKIP:
2070                 return 256;
2071         case WPA_CIPHER_WEP104:
2072                 return 104;
2073         case WPA_CIPHER_WEP40:
2074                 return 40;
2075         default:
2076                 return 0;
2077         }
2078 }
2079
2080
2081 static const u8 * wpa_key_mgmt_suite(struct wpa_sm *sm)
2082 {
2083         static const u8 *dummy = (u8 *) "\x00\x00\x00\x00";
2084         switch (sm->key_mgmt) {
2085         case WPA_KEY_MGMT_IEEE8021X:
2086                 return (sm->proto == WPA_PROTO_RSN ?
2087                         RSN_AUTH_KEY_MGMT_UNSPEC_802_1X :
2088                         WPA_AUTH_KEY_MGMT_UNSPEC_802_1X);
2089         case WPA_KEY_MGMT_PSK:
2090                 return (sm->proto == WPA_PROTO_RSN ?
2091                         RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X :
2092                         WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X);
2093         case WPA_KEY_MGMT_WPA_NONE:
2094                 return WPA_AUTH_KEY_MGMT_NONE;
2095         default:
2096                 return dummy;
2097         }
2098 }
2099
2100
2101 static const u8 * wpa_cipher_suite(struct wpa_sm *sm, int cipher)
2102 {
2103         static const u8 *dummy = (u8 *) "\x00\x00\x00\x00";
2104         switch (cipher) {
2105         case WPA_CIPHER_CCMP:
2106                 return (sm->proto == WPA_PROTO_RSN ?
2107                         RSN_CIPHER_SUITE_CCMP : WPA_CIPHER_SUITE_CCMP);
2108         case WPA_CIPHER_TKIP:
2109                 return (sm->proto == WPA_PROTO_RSN ?
2110                         RSN_CIPHER_SUITE_TKIP : WPA_CIPHER_SUITE_TKIP);
2111         case WPA_CIPHER_WEP104:
2112                 return (sm->proto == WPA_PROTO_RSN ?
2113                         RSN_CIPHER_SUITE_WEP104 : WPA_CIPHER_SUITE_WEP104);
2114         case WPA_CIPHER_WEP40:
2115                 return (sm->proto == WPA_PROTO_RSN ?
2116                         RSN_CIPHER_SUITE_WEP40 : WPA_CIPHER_SUITE_WEP40);
2117         case WPA_CIPHER_NONE:
2118                 return (sm->proto == WPA_PROTO_RSN ?
2119                         RSN_CIPHER_SUITE_NONE : WPA_CIPHER_SUITE_NONE);
2120         default:
2121                 return dummy;
2122         }
2123 }
2124
2125
2126 #define RSN_SUITE "%02x-%02x-%02x-%d"
2127 #define RSN_SUITE_ARG(s) (s)[0], (s)[1], (s)[2], (s)[3]
2128
2129 /**
2130  * wpa_sm_get_mib - Dump text list of MIB entries
2131  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2132  * @buf: Buffer for the list
2133  * @buflen: Length of the buffer
2134  * Returns: Number of bytes written to buffer
2135  *
2136  * This function is used fetch dot11 MIB variables.
2137  */
2138 int wpa_sm_get_mib(struct wpa_sm *sm, char *buf, size_t buflen)
2139 {
2140         int len, i;
2141         char pmkid_txt[PMKID_LEN * 2 + 1];
2142         int rsna;
2143
2144         if (sm->cur_pmksa) {
2145                 char *pos = pmkid_txt;
2146                 for (i = 0; i < PMKID_LEN; i++) {
2147                         pos += sprintf(pos, "%02x", sm->cur_pmksa->pmkid[i]);
2148                 }
2149         } else
2150                 pmkid_txt[0] = '\0';
2151
2152         if ((sm->key_mgmt == WPA_KEY_MGMT_PSK ||
2153              sm->key_mgmt == WPA_KEY_MGMT_IEEE8021X) &&
2154             sm->proto == WPA_PROTO_RSN)
2155                 rsna = 1;
2156         else
2157                 rsna = 0;
2158
2159         len = snprintf(buf, buflen,
2160                        "dot11RSNAOptionImplemented=TRUE\n"
2161                        "dot11RSNAPreauthenticationImplemented=TRUE\n"
2162                        "dot11RSNAEnabled=%s\n"
2163                        "dot11RSNAPreauthenticationEnabled=%s\n"
2164                        "dot11RSNAConfigVersion=%d\n"
2165                        "dot11RSNAConfigPairwiseKeysSupported=5\n"
2166                        "dot11RSNAConfigGroupCipherSize=%d\n"
2167                        "dot11RSNAConfigPMKLifetime=%d\n"
2168                        "dot11RSNAConfigPMKReauthThreshold=%d\n"
2169                        "dot11RSNAConfigNumberOfPTKSAReplayCounters=1\n"
2170                        "dot11RSNAConfigSATimeout=%d\n"
2171                        "dot11RSNAAuthenticationSuiteSelected=" RSN_SUITE "\n"
2172                        "dot11RSNAPairwiseCipherSelected=" RSN_SUITE "\n"
2173                        "dot11RSNAGroupCipherSelected=" RSN_SUITE "\n"
2174                        "dot11RSNAPMKIDUsed=%s\n"
2175                        "dot11RSNAAuthenticationSuiteRequested=" RSN_SUITE "\n"
2176                        "dot11RSNAPairwiseCipherRequested=" RSN_SUITE "\n"
2177                        "dot11RSNAGroupCipherRequested=" RSN_SUITE "\n"
2178                        "dot11RSNAConfigNumberOfGTKSAReplayCounters=0\n"
2179                        "dot11RSNA4WayHandshakeFailures=%u\n",
2180                        rsna ? "TRUE" : "FALSE",
2181                        rsna ? "TRUE" : "FALSE",
2182                        RSN_VERSION,
2183                        wpa_cipher_bits(sm->group_cipher),
2184                        sm->dot11RSNAConfigPMKLifetime,
2185                        sm->dot11RSNAConfigPMKReauthThreshold,
2186                        sm->dot11RSNAConfigSATimeout,
2187                        RSN_SUITE_ARG(wpa_key_mgmt_suite(sm)),
2188                        RSN_SUITE_ARG(wpa_cipher_suite(sm,
2189                                                       sm->pairwise_cipher)),
2190                        RSN_SUITE_ARG(wpa_cipher_suite(sm, sm->group_cipher)),
2191                        pmkid_txt,
2192                        RSN_SUITE_ARG(wpa_key_mgmt_suite(sm)),
2193                        RSN_SUITE_ARG(wpa_cipher_suite(sm,
2194                                                       sm->pairwise_cipher)),
2195                        RSN_SUITE_ARG(wpa_cipher_suite(sm, sm->group_cipher)),
2196                        sm->dot11RSNA4WayHandshakeFailures);
2197         return len;
2198 }
2199
2200
2201 /**
2202  * wpa_sm_init - Initialize WPA state machine
2203  * @ctx: Context pointer for callbacks
2204  * Returns: Pointer to the allocated WPA state machine data
2205  *
2206  * This function is used to allocate a new WPA state machine and the returned
2207  * value is passed to all WPA state machine calls.
2208  */
2209 struct wpa_sm * wpa_sm_init(struct wpa_sm_ctx *ctx)
2210 {
2211         struct wpa_sm *sm;
2212
2213         sm = malloc(sizeof(*sm));
2214         if (sm == NULL)
2215                 return NULL;
2216         memset(sm, 0, sizeof(*sm));
2217         sm->renew_snonce = 1;
2218         sm->ctx = ctx;
2219
2220         sm->dot11RSNAConfigPMKLifetime = 43200;
2221         sm->dot11RSNAConfigPMKReauthThreshold = 70;
2222         sm->dot11RSNAConfigSATimeout = 60;
2223
2224         return sm;
2225 }
2226
2227
2228 /**
2229  * wpa_sm_deinit - Deinitialize WPA state machine
2230  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2231  */
2232 void wpa_sm_deinit(struct wpa_sm *sm)
2233 {
2234         if (sm == NULL)
2235                 return;
2236         eloop_cancel_timeout(wpa_sm_start_preauth, sm, 0);
2237         free(sm->assoc_wpa_ie);
2238         free(sm->ap_wpa_ie);
2239         free(sm->ap_rsn_ie);
2240         free(sm->ctx);
2241         free(sm);
2242 }
2243
2244
2245 /**
2246  * wpa_sm_notify_assoc - Notify WPA state machine about association
2247  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2248  * @bssid: The BSSID of the new association
2249  *
2250  * This function is called to let WPA state machine know that the connection
2251  * was established.
2252  */
2253 void wpa_sm_notify_assoc(struct wpa_sm *sm, const u8 *bssid)
2254 {
2255         if (sm == NULL)
2256                 return;
2257
2258         wpa_printf(MSG_DEBUG, "WPA: Association event - clear replay counter");
2259         memcpy(sm->bssid, bssid, ETH_ALEN);
2260         memset(sm->rx_replay_counter, 0, WPA_REPLAY_COUNTER_LEN);
2261         sm->rx_replay_counter_set = 0;
2262         sm->renew_snonce = 1;
2263         if (memcmp(sm->preauth_bssid, bssid, ETH_ALEN) == 0)
2264                 rsn_preauth_deinit(sm);
2265 }
2266
2267
2268 /**
2269  * wpa_sm_notify_disassoc - Notify WPA state machine about disassociation
2270  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2271  *
2272  * This function is called to let WPA state machine know that the connection
2273  * was lost. This will abort any existing pre-authentication session.
2274  */
2275 void wpa_sm_notify_disassoc(struct wpa_sm *sm)
2276 {
2277         rsn_preauth_deinit(sm);
2278         if (wpa_sm_get_state(sm) == WPA_4WAY_HANDSHAKE)
2279                 sm->dot11RSNA4WayHandshakeFailures++;
2280 }
2281
2282
2283 /**
2284  * wpa_sm_set_pmk - Set PMK
2285  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2286  * @pmk: The new PMK
2287  * @pmk_len: The length of the new PMK in bytes
2288  *
2289  * Configure the PMK for WPA state machine.
2290  */
2291 void wpa_sm_set_pmk(struct wpa_sm *sm, const u8 *pmk, size_t pmk_len)
2292 {
2293         if (sm == NULL)
2294                 return;
2295
2296         sm->pmk_len = pmk_len;
2297         memcpy(sm->pmk, pmk, pmk_len);
2298 }
2299
2300
2301 /**
2302  * wpa_sm_set_pmk_from_pmksa - Set PMK based on the current PMKSA
2303  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2304  *
2305  * Take the PMK from the current PMKSA into use. If no PMKSA is active, the PMK
2306  * will be cleared.
2307  */
2308 void wpa_sm_set_pmk_from_pmksa(struct wpa_sm *sm)
2309 {
2310         if (sm == NULL)
2311                 return;
2312
2313         if (sm->cur_pmksa) {
2314                 sm->pmk_len = sm->cur_pmksa->pmk_len;
2315                 memcpy(sm->pmk, sm->cur_pmksa->pmk, sm->pmk_len);
2316         } else {
2317                 sm->pmk_len = PMK_LEN;
2318                 memset(sm->pmk, 0, PMK_LEN);
2319         }
2320 }
2321
2322
2323 /**
2324  * wpa_sm_set_fast_reauth - Set fast reauthentication (EAP) enabled/disabled
2325  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2326  * @fast_reauth: Whether fast reauthentication (EAP) is allowed
2327  */
2328 void wpa_sm_set_fast_reauth(struct wpa_sm *sm, int fast_reauth)
2329 {
2330         if (sm)
2331                 sm->fast_reauth = fast_reauth;
2332 }
2333
2334
2335 /**
2336  * wpa_sm_set_scard_ctx - Set context pointer for smartcard callbacks
2337  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2338  * @scard_ctx: Context pointer for smartcard related callback functions
2339  */
2340 void wpa_sm_set_scard_ctx(struct wpa_sm *sm, void *scard_ctx)
2341 {
2342         if (sm == NULL)
2343                 return;
2344         sm->scard_ctx = scard_ctx;
2345         if (sm->preauth_eapol)
2346                 eapol_sm_register_scard_ctx(sm->preauth_eapol, scard_ctx);
2347 }
2348
2349
2350 /**
2351  * wpa_sm_set_config - Notification of current configration change
2352  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2353  * @config: Pointer to current network configuration
2354  *
2355  * Notify WPA state machine that configuration has changed. config will be
2356  * stored as a backpointer to network configuration. This can be %NULL to clear
2357  * the stored pointed.
2358  */
2359 void wpa_sm_set_config(struct wpa_sm *sm, struct wpa_ssid *config)
2360 {
2361         if (sm)
2362                 sm->cur_ssid = config;
2363 }
2364
2365
2366 /**
2367  * wpa_sm_set_own_addr - Set own MAC address
2368  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2369  * @addr: Own MAC address
2370  */
2371 void wpa_sm_set_own_addr(struct wpa_sm *sm, const u8 *addr)
2372 {
2373         if (sm)
2374                 memcpy(sm->own_addr, addr, ETH_ALEN);
2375 }
2376
2377
2378 /**
2379  * wpa_sm_set_ifname - Set network interface name
2380  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2381  * @ifname: Interface name
2382  */
2383 void wpa_sm_set_ifname(struct wpa_sm *sm, const char *ifname)
2384 {
2385         if (sm)
2386                 sm->ifname = ifname;
2387 }
2388
2389
2390 /**
2391  * wpa_sm_set_eapol - Set EAPOL state machine pointer
2392  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2393  * @eapol: Pointer to EAPOL state machine allocated with eapol_sm_init()
2394  */
2395 void wpa_sm_set_eapol(struct wpa_sm *sm, struct eapol_sm *eapol)
2396 {
2397         if (sm)
2398                 sm->eapol = eapol;
2399 }
2400
2401
2402 /**
2403  * wpa_sm_set_param - Set WPA state machine parameters
2404  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2405  * @param: Parameter field
2406  * @value: Parameter value
2407  * Returns: 0 on success, -1 on failure
2408  */
2409 int wpa_sm_set_param(struct wpa_sm *sm, enum wpa_sm_conf_params param,
2410                      unsigned int value)
2411 {
2412         int ret = 0;
2413
2414         if (sm == NULL)
2415                 return -1;
2416
2417         switch (param) {
2418         case RSNA_PMK_LIFETIME:
2419                 if (value > 0)
2420                         sm->dot11RSNAConfigPMKLifetime = value;
2421                 else
2422                         ret = -1;
2423                 break;
2424         case RSNA_PMK_REAUTH_THRESHOLD:
2425                 if (value > 0 && value <= 100)
2426                         sm->dot11RSNAConfigPMKReauthThreshold = value;
2427                 else
2428                         ret = -1;
2429                 break;
2430         case RSNA_SA_TIMEOUT:
2431                 if (value > 0)
2432                         sm->dot11RSNAConfigSATimeout = value;
2433                 else
2434                         ret = -1;
2435                 break;
2436         case WPA_PARAM_PROTO:
2437                 sm->proto = value;
2438                 break;
2439         case WPA_PARAM_PAIRWISE:
2440                 sm->pairwise_cipher = value;
2441                 break;
2442         case WPA_PARAM_GROUP:
2443                 sm->group_cipher = value;
2444                 break;
2445         case WPA_PARAM_KEY_MGMT:
2446                 sm->key_mgmt = value;
2447                 break;
2448         }
2449
2450         return ret;
2451 }
2452
2453
2454 /**
2455  * wpa_sm_get_param - Get WPA state machine parameters
2456  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2457  * @param: Parameter field
2458  * Returns: Parameter value
2459  */
2460 unsigned int wpa_sm_get_param(struct wpa_sm *sm, enum wpa_sm_conf_params param)
2461 {
2462         if (sm == NULL)
2463                 return 0;
2464
2465         switch (param) {
2466         case RSNA_PMK_LIFETIME:
2467                 return sm->dot11RSNAConfigPMKLifetime;
2468         case RSNA_PMK_REAUTH_THRESHOLD:
2469                 return sm->dot11RSNAConfigPMKReauthThreshold;
2470         case RSNA_SA_TIMEOUT:
2471                 return sm->dot11RSNAConfigSATimeout;
2472         case WPA_PARAM_PROTO:
2473                 return sm->proto;
2474         case WPA_PARAM_PAIRWISE:
2475                 return sm->pairwise_cipher;
2476         case WPA_PARAM_GROUP:
2477                 return sm->group_cipher;
2478         case WPA_PARAM_KEY_MGMT:
2479                 return sm->key_mgmt;
2480         default:
2481                 return 0;
2482         }
2483 }
2484
2485
2486 /**
2487  * wpa_sm_get_status - Get WPA state machine
2488  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2489  * @buf: Buffer for status information
2490  * @buflen: Maximum buffer length
2491  * @verbose: Whether to include verbose status information
2492  * Returns: Number of bytes written to buf.
2493  *
2494  * Query WPA state machine for status information. This function fills in
2495  * a text area with current status information. If the buffer (buf) is not
2496  * large enough, status information will be truncated to fit the buffer.
2497  */
2498 int wpa_sm_get_status(struct wpa_sm *sm, char *buf, size_t buflen,
2499                       int verbose)
2500 {
2501         char *pos = buf, *end = buf + buflen;
2502
2503         pos += snprintf(pos, end - pos,
2504                         "pairwise_cipher=%s\n"
2505                         "group_cipher=%s\n"
2506                         "key_mgmt=%s\n",
2507                         wpa_cipher_txt(sm->pairwise_cipher),
2508                         wpa_cipher_txt(sm->group_cipher),
2509                         wpa_key_mgmt_txt(sm->key_mgmt, sm->proto));
2510         return pos - buf;
2511 }
2512
2513
2514 /**
2515  * wpa_sm_set_assoc_wpa_ie_default - Generate own WPA/RSN IE from configuration
2516  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2517  * @wpa_ie: Pointer to buffer for WPA/RSN IE
2518  * @wpa_ie_len: Pointer to the length of the wpa_ie buffer
2519  * Returns: 0 on success, -1 on failure
2520  *
2521  * Inform WPA state machine about the WPA/RSN IE used in (Re)Association
2522  * Request frame. The IE will be used to override the default value generated
2523  * with wpa_sm_set_assoc_wpa_ie_default().
2524  */
2525 int wpa_sm_set_assoc_wpa_ie_default(struct wpa_sm *sm, u8 *wpa_ie,
2526                                     size_t *wpa_ie_len)
2527 {
2528         if (sm == NULL)
2529                 return -1;
2530
2531         *wpa_ie_len = wpa_gen_wpa_ie(sm, wpa_ie, *wpa_ie_len);
2532         if (*wpa_ie_len < 0)
2533                 return -1;
2534
2535         wpa_hexdump(MSG_DEBUG, "WPA: Set own WPA IE default",
2536                     wpa_ie, *wpa_ie_len);
2537
2538         if (sm->assoc_wpa_ie == NULL) {
2539                 /*
2540                  * Make a copy of the WPA/RSN IE so that 4-Way Handshake gets
2541                  * the correct version of the IE even if PMKSA caching is
2542                  * aborted (which would remove PMKID from IE generation).
2543                  */
2544                 sm->assoc_wpa_ie = malloc(*wpa_ie_len);
2545                 if (sm->assoc_wpa_ie == NULL)
2546                         return -1;
2547
2548                 memcpy(sm->assoc_wpa_ie, wpa_ie, *wpa_ie_len);
2549                 sm->assoc_wpa_ie_len = *wpa_ie_len;
2550         }
2551
2552         return 0;
2553 }
2554
2555
2556 /**
2557  * wpa_sm_set_assoc_wpa_ie - Set own WPA/RSN IE from (Re)AssocReq
2558  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2559  * @ie: Pointer to IE data (starting from id)
2560  * @len: IE length
2561  * Returns: 0 on success, -1 on failure
2562  *
2563  * Inform WPA state machine about the WPA/RSN IE used in (Re)Association
2564  * Request frame. The IE will be used to override the default value generated
2565  * with wpa_sm_set_assoc_wpa_ie_default().
2566  */
2567 int wpa_sm_set_assoc_wpa_ie(struct wpa_sm *sm, const u8 *ie, size_t len)
2568 {
2569         if (sm == NULL)
2570                 return -1;
2571
2572         free(sm->assoc_wpa_ie);
2573         if (ie == NULL || len == 0) {
2574                 wpa_printf(MSG_DEBUG, "WPA: clearing own WPA/RSN IE");
2575                 sm->assoc_wpa_ie = NULL;
2576                 sm->assoc_wpa_ie_len = 0;
2577         } else {
2578                 wpa_hexdump(MSG_DEBUG, "WPA: set own WPA/RSN IE", ie, len);
2579                 sm->assoc_wpa_ie = malloc(len);
2580                 if (sm->assoc_wpa_ie == NULL)
2581                         return -1;
2582
2583                 memcpy(sm->assoc_wpa_ie, ie, len);
2584                 sm->assoc_wpa_ie_len = len;
2585         }
2586
2587         return 0;
2588 }
2589
2590
2591 /**
2592  * wpa_sm_set_ap_wpa_ie - Set AP WPA IE from Beacon/ProbeResp
2593  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2594  * @ie: Pointer to IE data (starting from id)
2595  * @len: IE length
2596  * Returns: 0 on success, -1 on failure
2597  *
2598  * Inform WPA state machine about the WPA IE used in Beacon / Probe Response
2599  * frame.
2600  */
2601 int wpa_sm_set_ap_wpa_ie(struct wpa_sm *sm, const u8 *ie, size_t len)
2602 {
2603         if (sm == NULL)
2604                 return -1;
2605
2606         free(sm->ap_wpa_ie);
2607         if (ie == NULL || len == 0) {
2608                 wpa_printf(MSG_DEBUG, "WPA: clearing AP WPA IE");
2609                 sm->ap_wpa_ie = NULL;
2610                 sm->ap_wpa_ie_len = 0;
2611         } else {
2612                 wpa_hexdump(MSG_DEBUG, "WPA: set AP WPA IE", ie, len);
2613                 sm->ap_wpa_ie = malloc(len);
2614                 if (sm->ap_wpa_ie == NULL)
2615                         return -1;
2616
2617                 memcpy(sm->ap_wpa_ie, ie, len);
2618                 sm->ap_wpa_ie_len = len;
2619         }
2620
2621         return 0;
2622 }
2623
2624
2625 /**
2626  * wpa_sm_set_ap_rsn_ie - Set AP RSN IE from Beacon/ProbeResp
2627  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2628  * @ie: Pointer to IE data (starting from id)
2629  * @len: IE length
2630  * Returns: 0 on success, -1 on failure
2631  *
2632  * Inform WPA state machine about the RSN IE used in Beacon / Probe Response
2633  * frame.
2634  */
2635 int wpa_sm_set_ap_rsn_ie(struct wpa_sm *sm, const u8 *ie, size_t len)
2636 {
2637         if (sm == NULL)
2638                 return -1;
2639
2640         free(sm->ap_rsn_ie);
2641         if (ie == NULL || len == 0) {
2642                 wpa_printf(MSG_DEBUG, "WPA: clearing AP RSN IE");
2643                 sm->ap_rsn_ie = NULL;
2644                 sm->ap_rsn_ie_len = 0;
2645         } else {
2646                 wpa_hexdump(MSG_DEBUG, "WPA: set AP RSN IE", ie, len);
2647                 sm->ap_rsn_ie = malloc(len);
2648                 if (sm->ap_rsn_ie == NULL)
2649                         return -1;
2650
2651                 memcpy(sm->ap_rsn_ie, ie, len);
2652                 sm->ap_rsn_ie_len = len;
2653         }
2654
2655         return 0;
2656 }
2657
2658
2659 /**
2660  * wpa_sm_parse_own_wpa_ie - Parse own WPA/RSN IE
2661  * @sm: Pointer to WPA state machine data from wpa_sm_init()
2662  * @data: Pointer to data area for parsing results
2663  * Returns: 0 on success, -1 if IE is not known, or -2 on parsing failure
2664  *
2665  * Parse the contents of the own WPA or RSN IE from (Re)AssocReq and write the
2666  * parsed data into data.
2667  */
2668 int wpa_sm_parse_own_wpa_ie(struct wpa_sm *sm, struct wpa_ie_data *data)
2669 {
2670         if (sm == NULL || sm->assoc_wpa_ie == NULL) {
2671                 wpa_printf(MSG_DEBUG, "WPA: No WPA/RSN IE available from "
2672                            "association info");
2673                 return -1;
2674         }
2675         if (wpa_parse_wpa_ie(sm->assoc_wpa_ie, sm->assoc_wpa_ie_len, data))
2676                 return -2;
2677         return 0;
2678 }