Staging: rt3070: remove dead CONFIG_AP_SUPPORT code
[linux-2.6] / drivers / staging / rt3070 / common / cmm_wpa.c
1 /*
2  *************************************************************************
3  * Ralink Tech Inc.
4  * 5F., No.36, Taiyuan St., Jhubei City,
5  * Hsinchu County 302,
6  * Taiwan, R.O.C.
7  *
8  * (c) Copyright 2002-2007, Ralink Technology, Inc.
9  *
10  * This program is free software; you can redistribute it and/or modify  *
11  * it under the terms of the GNU General Public License as published by  *
12  * the Free Software Foundation; either version 2 of the License, or     *
13  * (at your option) any later version.                                   *
14  *                                                                       *
15  * This program is distributed in the hope that it will be useful,       *
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
18  * GNU General Public License for more details.                          *
19  *                                                                       *
20  * You should have received a copy of the GNU General Public License     *
21  * along with this program; if not, write to the                         *
22  * Free Software Foundation, Inc.,                                       *
23  * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
24  *                                                                       *
25  *************************************************************************
26
27         Module Name:
28         wpa.c
29
30         Abstract:
31
32         Revision History:
33         Who                     When                    What
34         --------        ----------              ----------------------------------------------
35         Jan     Lee             03-07-22                Initial
36         Paul Lin        03-11-28                Modify for supplicant
37 */
38 #include "../rt_config.h"
39 // WPA OUI
40 UCHAR           OUI_WPA_NONE_AKM[4]             = {0x00, 0x50, 0xF2, 0x00};
41 UCHAR       OUI_WPA_VERSION[4]      = {0x00, 0x50, 0xF2, 0x01};
42 UCHAR       OUI_WPA_TKIP[4]     = {0x00, 0x50, 0xF2, 0x02};
43 UCHAR       OUI_WPA_CCMP[4]     = {0x00, 0x50, 0xF2, 0x04};
44 UCHAR       OUI_WPA_8021X_AKM[4]        = {0x00, 0x50, 0xF2, 0x01};
45 UCHAR       OUI_WPA_PSK_AKM[4]      = {0x00, 0x50, 0xF2, 0x02};
46 // WPA2 OUI
47 UCHAR       OUI_WPA2_WEP40[4]   = {0x00, 0x0F, 0xAC, 0x01};
48 UCHAR       OUI_WPA2_TKIP[4]        = {0x00, 0x0F, 0xAC, 0x02};
49 UCHAR       OUI_WPA2_CCMP[4]        = {0x00, 0x0F, 0xAC, 0x04};
50 UCHAR       OUI_WPA2_8021X_AKM[4]   = {0x00, 0x0F, 0xAC, 0x01};
51 UCHAR       OUI_WPA2_PSK_AKM[4]         = {0x00, 0x0F, 0xAC, 0x02};
52 // MSA OUI
53 UCHAR           OUI_MSA_8021X_AKM[4]    = {0x00, 0x0F, 0xAC, 0x05};             // Not yet final - IEEE 802.11s-D1.06
54 UCHAR           OUI_MSA_PSK_AKM[4]      = {0x00, 0x0F, 0xAC, 0x06};             // Not yet final - IEEE 802.11s-D1.06
55
56 /*
57         ========================================================================
58
59         Routine Description:
60                 The pseudo-random function(PRF) that hashes various inputs to
61                 derive a pseudo-random value. To add liveness to the pseudo-random
62                 value, a nonce should be one of the inputs.
63
64                 It is used to generate PTK, GTK or some specific random value.
65
66         Arguments:
67                 UCHAR   *key,           -       the key material for HMAC_SHA1 use
68                 INT             key_len         -       the length of key
69                 UCHAR   *prefix         -       a prefix label
70                 INT             prefix_len      -       the length of the label
71                 UCHAR   *data           -       a specific data with variable length
72                 INT             data_len        -       the length of a specific data
73                 INT             len                     -       the output lenght
74
75         Return Value:
76                 UCHAR   *output         -       the calculated result
77
78         Note:
79                 802.11i-2004    Annex H.3
80
81         ========================================================================
82 */
83 VOID    PRF(
84         IN      UCHAR   *key,
85         IN      INT             key_len,
86         IN      UCHAR   *prefix,
87         IN      INT             prefix_len,
88         IN      UCHAR   *data,
89         IN      INT             data_len,
90         OUT     UCHAR   *output,
91         IN      INT             len)
92 {
93         INT             i;
94     UCHAR   *input;
95         INT             currentindex = 0;
96         INT             total_len;
97
98         // Allocate memory for input
99         os_alloc_mem(NULL, (PUCHAR *)&input, 1024);
100
101     if (input == NULL)
102     {
103         DBGPRINT(RT_DEBUG_ERROR, ("!!!PRF: no memory!!!\n"));
104         return;
105     }
106
107         // Generate concatenation input
108         NdisMoveMemory(input, prefix, prefix_len);
109
110         // Concatenate a single octet containing 0
111         input[prefix_len] =     0;
112
113         // Concatenate specific data
114         NdisMoveMemory(&input[prefix_len + 1], data, data_len);
115         total_len =     prefix_len + 1 + data_len;
116
117         // Concatenate a single octet containing 0
118         // This octet shall be update later
119         input[total_len] = 0;
120         total_len++;
121
122         // Iterate to calculate the result by hmac-sha-1
123         // Then concatenate to last result
124         for     (i = 0; i <     (len + 19) / 20; i++)
125         {
126                 HMAC_SHA1(input, total_len,     key, key_len, &output[currentindex]);
127                 currentindex += 20;
128
129                 // update the last octet
130                 input[total_len - 1]++;
131         }
132     os_free_mem(NULL, input);
133 }
134
135 /*
136         ========================================================================
137
138         Routine Description:
139                 It utilizes PRF-384 or PRF-512 to derive session-specific keys from a PMK.
140                 It shall be called by 4-way handshake processing.
141
142         Arguments:
143                 pAd     -       pointer to our pAdapter context
144                 PMK             -       pointer to PMK
145                 ANonce  -       pointer to ANonce
146                 AA              -       pointer to Authenticator Address
147                 SNonce  -       pointer to SNonce
148                 SA              -       pointer to Supplicant Address
149                 len             -       indicate the length of PTK (octet)
150
151         Return Value:
152                 Output          pointer to the PTK
153
154         Note:
155                 Refer to IEEE 802.11i-2004 8.5.1.2
156
157         ========================================================================
158 */
159 VOID WpaCountPTK(
160         IN      PRTMP_ADAPTER   pAd,
161         IN      UCHAR   *PMK,
162         IN      UCHAR   *ANonce,
163         IN      UCHAR   *AA,
164         IN      UCHAR   *SNonce,
165         IN      UCHAR   *SA,
166         OUT     UCHAR   *output,
167         IN      UINT    len)
168 {
169         UCHAR   concatenation[76];
170         UINT    CurrPos = 0;
171         UCHAR   temp[32];
172         UCHAR   Prefix[] = {'P', 'a', 'i', 'r', 'w', 'i', 's', 'e', ' ', 'k', 'e', 'y', ' ',
173                                                 'e', 'x', 'p', 'a', 'n', 's', 'i', 'o', 'n'};
174
175         // initiate the concatenation input
176         NdisZeroMemory(temp, sizeof(temp));
177         NdisZeroMemory(concatenation, 76);
178
179         // Get smaller address
180         if (RTMPCompareMemory(SA, AA, 6) == 1)
181                 NdisMoveMemory(concatenation, AA, 6);
182         else
183                 NdisMoveMemory(concatenation, SA, 6);
184         CurrPos += 6;
185
186         // Get larger address
187         if (RTMPCompareMemory(SA, AA, 6) == 1)
188                 NdisMoveMemory(&concatenation[CurrPos], SA, 6);
189         else
190                 NdisMoveMemory(&concatenation[CurrPos], AA, 6);
191
192         // store the larger mac address for backward compatible of
193         // ralink proprietary STA-key issue
194         NdisMoveMemory(temp, &concatenation[CurrPos], MAC_ADDR_LEN);
195         CurrPos += 6;
196
197         // Get smaller Nonce
198         if (RTMPCompareMemory(ANonce, SNonce, 32) == 0)
199                 NdisMoveMemory(&concatenation[CurrPos], temp, 32);      // patch for ralink proprietary STA-key issue
200         else if (RTMPCompareMemory(ANonce, SNonce, 32) == 1)
201                 NdisMoveMemory(&concatenation[CurrPos], SNonce, 32);
202         else
203                 NdisMoveMemory(&concatenation[CurrPos], ANonce, 32);
204         CurrPos += 32;
205
206         // Get larger Nonce
207         if (RTMPCompareMemory(ANonce, SNonce, 32) == 0)
208                 NdisMoveMemory(&concatenation[CurrPos], temp, 32);      // patch for ralink proprietary STA-key issue
209         else if (RTMPCompareMemory(ANonce, SNonce, 32) == 1)
210                 NdisMoveMemory(&concatenation[CurrPos], ANonce, 32);
211         else
212                 NdisMoveMemory(&concatenation[CurrPos], SNonce, 32);
213         CurrPos += 32;
214
215         hex_dump("concatenation=", concatenation, 76);
216
217         // Use PRF to generate PTK
218         PRF(PMK, LEN_MASTER_KEY, Prefix, 22, concatenation, 76, output, len);
219
220 }
221
222 /*
223         ========================================================================
224
225         Routine Description:
226                 Generate random number by software.
227
228         Arguments:
229                 pAd             -       pointer to our pAdapter context
230                 macAddr -       pointer to local MAC address
231
232         Return Value:
233
234         Note:
235                 802.1ii-2004  Annex H.5
236
237         ========================================================================
238 */
239 VOID    GenRandom(
240         IN      PRTMP_ADAPTER   pAd,
241         IN      UCHAR                   *macAddr,
242         OUT     UCHAR                   *random)
243 {
244         INT             i, curr;
245         UCHAR   local[80], KeyCounter[32];
246         UCHAR   result[80];
247         ULONG   CurrentTime;
248         UCHAR   prefix[] = {'I', 'n', 'i', 't', ' ', 'C', 'o', 'u', 'n', 't', 'e', 'r'};
249
250         // Zero the related information
251         NdisZeroMemory(result, 80);
252         NdisZeroMemory(local, 80);
253         NdisZeroMemory(KeyCounter, 32);
254
255         for     (i = 0; i <     32;     i++)
256         {
257                 // copy the local MAC address
258                 COPY_MAC_ADDR(local, macAddr);
259                 curr =  MAC_ADDR_LEN;
260
261                 // concatenate the current time
262                 NdisGetSystemUpTime(&CurrentTime);
263                 NdisMoveMemory(&local[curr],  &CurrentTime,     sizeof(CurrentTime));
264                 curr += sizeof(CurrentTime);
265
266                 // concatenate the last result
267                 NdisMoveMemory(&local[curr],  result, 32);
268                 curr += 32;
269
270                 // concatenate a variable
271                 NdisMoveMemory(&local[curr],  &i,  2);
272                 curr += 2;
273
274                 // calculate the result
275                 PRF(KeyCounter, 32, prefix,12, local, curr, result, 32);
276         }
277
278         NdisMoveMemory(random, result,  32);
279 }
280
281 /*
282         ========================================================================
283
284         Routine Description:
285                 Build cipher suite in RSN-IE.
286                 It only shall be called by RTMPMakeRSNIE.
287
288         Arguments:
289                 pAd                     -       pointer to our pAdapter context
290         ElementID       -       indicate the WPA1 or WPA2
291         WepStatus       -       indicate the encryption type
292                 bMixCipher      -       a boolean to indicate the pairwise cipher and group
293                                                 cipher are the same or not
294
295         Return Value:
296
297         Note:
298
299         ========================================================================
300 */
301 static VOID RTMPInsertRsnIeCipher(
302         IN  PRTMP_ADAPTER   pAd,
303         IN      UCHAR                   ElementID,
304         IN      UINT                    WepStatus,
305         IN      BOOLEAN                 bMixCipher,
306         IN      UCHAR                   FlexibleCipher,
307         OUT     PUCHAR                  pRsnIe,
308         OUT     UCHAR                   *rsn_len)
309 {
310         UCHAR   PairwiseCnt;
311
312         *rsn_len = 0;
313
314         // decide WPA2 or WPA1
315         if (ElementID == Wpa2Ie)
316         {
317                 RSNIE2  *pRsnie_cipher = (RSNIE2*)pRsnIe;
318
319                 // Assign the verson as 1
320                 pRsnie_cipher->version = 1;
321
322         switch (WepStatus)
323         {
324                 // TKIP mode
325             case Ndis802_11Encryption2Enabled:
326                 NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
327                 pRsnie_cipher->ucount = 1;
328                 NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_TKIP, 4);
329                 *rsn_len = sizeof(RSNIE2);
330                 break;
331
332                         // AES mode
333             case Ndis802_11Encryption3Enabled:
334                                 if (bMixCipher)
335                                         NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
336                                 else
337                                         NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_CCMP, 4);
338                 pRsnie_cipher->ucount = 1;
339                 NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_CCMP, 4);
340                 *rsn_len = sizeof(RSNIE2);
341                 break;
342
343                         // TKIP-AES mix mode
344             case Ndis802_11Encryption4Enabled:
345                 NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
346
347                                 PairwiseCnt = 1;
348                                 // Insert WPA2 TKIP as the first pairwise cipher
349                                 if (MIX_CIPHER_WPA2_TKIP_ON(FlexibleCipher))
350                                 {
351                         NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_TKIP, 4);
352                                         // Insert WPA2 AES as the secondary pairwise cipher
353                                         if (MIX_CIPHER_WPA2_AES_ON(FlexibleCipher))
354                                         {
355                                 NdisMoveMemory(pRsnie_cipher->ucast[0].oui + 4, OUI_WPA2_CCMP, 4);
356                                                 PairwiseCnt = 2;
357                                         }
358                                 }
359                                 else
360                                 {
361                                         // Insert WPA2 AES as the first pairwise cipher
362                                         NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_CCMP, 4);
363                                 }
364
365                 pRsnie_cipher->ucount = PairwiseCnt;
366                 *rsn_len = sizeof(RSNIE2) + (4 * (PairwiseCnt - 1));
367                 break;
368         }
369
370                 // swap for big-endian platform
371                 pRsnie_cipher->version = cpu2le16(pRsnie_cipher->version);
372             pRsnie_cipher->ucount = cpu2le16(pRsnie_cipher->ucount);
373         }
374         else
375         {
376                 RSNIE   *pRsnie_cipher = (RSNIE*)pRsnIe;
377
378                 // Assign OUI and version
379                 NdisMoveMemory(pRsnie_cipher->oui, OUI_WPA_VERSION, 4);
380         pRsnie_cipher->version = 1;
381
382                 switch (WepStatus)
383                 {
384                         // TKIP mode
385             case Ndis802_11Encryption2Enabled:
386                 NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
387                 pRsnie_cipher->ucount = 1;
388                 NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_TKIP, 4);
389                 *rsn_len = sizeof(RSNIE);
390                 break;
391
392                         // AES mode
393             case Ndis802_11Encryption3Enabled:
394                                 if (bMixCipher)
395                                         NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
396                                 else
397                                         NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_CCMP, 4);
398                 pRsnie_cipher->ucount = 1;
399                 NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_CCMP, 4);
400                 *rsn_len = sizeof(RSNIE);
401                 break;
402
403                         // TKIP-AES mix mode
404             case Ndis802_11Encryption4Enabled:
405                 NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
406
407                                 PairwiseCnt = 1;
408                                 // Insert WPA TKIP as the first pairwise cipher
409                                 if (MIX_CIPHER_WPA_TKIP_ON(FlexibleCipher))
410                                 {
411                         NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_TKIP, 4);
412                                         // Insert WPA AES as the secondary pairwise cipher
413                                         if (MIX_CIPHER_WPA_AES_ON(FlexibleCipher))
414                                         {
415                                 NdisMoveMemory(pRsnie_cipher->ucast[0].oui + 4, OUI_WPA_CCMP, 4);
416                                                 PairwiseCnt = 2;
417                                         }
418                                 }
419                                 else
420                                 {
421                                         // Insert WPA AES as the first pairwise cipher
422                                         NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_CCMP, 4);
423                                 }
424
425                 pRsnie_cipher->ucount = PairwiseCnt;
426                 *rsn_len = sizeof(RSNIE) + (4 * (PairwiseCnt - 1));
427                 break;
428         }
429
430                 // swap for big-endian platform
431                 pRsnie_cipher->version = cpu2le16(pRsnie_cipher->version);
432             pRsnie_cipher->ucount = cpu2le16(pRsnie_cipher->ucount);
433         }
434
435 }
436
437 /*
438         ========================================================================
439
440         Routine Description:
441                 Build AKM suite in RSN-IE.
442                 It only shall be called by RTMPMakeRSNIE.
443
444         Arguments:
445                 pAd                     -       pointer to our pAdapter context
446         ElementID       -       indicate the WPA1 or WPA2
447         AuthMode        -       indicate the authentication mode
448                 apidx           -       indicate the interface index
449
450         Return Value:
451
452         Note:
453
454         ========================================================================
455 */
456 static VOID RTMPInsertRsnIeAKM(
457         IN  PRTMP_ADAPTER   pAd,
458         IN      UCHAR                   ElementID,
459         IN      UINT                    AuthMode,
460         IN      UCHAR                   apidx,
461         OUT     PUCHAR                  pRsnIe,
462         OUT     UCHAR                   *rsn_len)
463 {
464         RSNIE_AUTH              *pRsnie_auth;
465
466         pRsnie_auth = (RSNIE_AUTH*)(pRsnIe + (*rsn_len));
467
468         // decide WPA2 or WPA1
469         if (ElementID == Wpa2Ie)
470         {
471                 switch (AuthMode)
472         {
473             case Ndis802_11AuthModeWPA2:
474             case Ndis802_11AuthModeWPA1WPA2:
475                 pRsnie_auth->acount = 1;
476                         NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA2_8021X_AKM, 4);
477                 break;
478
479             case Ndis802_11AuthModeWPA2PSK:
480             case Ndis802_11AuthModeWPA1PSKWPA2PSK:
481                 pRsnie_auth->acount = 1;
482                         NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA2_PSK_AKM, 4);
483                 break;
484         }
485         }
486         else
487         {
488                 switch (AuthMode)
489         {
490             case Ndis802_11AuthModeWPA:
491             case Ndis802_11AuthModeWPA1WPA2:
492                 pRsnie_auth->acount = 1;
493                 NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_8021X_AKM, 4);
494                 break;
495
496             case Ndis802_11AuthModeWPAPSK:
497             case Ndis802_11AuthModeWPA1PSKWPA2PSK:
498                 pRsnie_auth->acount = 1;
499                 NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_PSK_AKM, 4);
500                 break;
501
502                         case Ndis802_11AuthModeWPANone:
503                 pRsnie_auth->acount = 1;
504                 NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_NONE_AKM, 4);
505                 break;
506         }
507         }
508
509         pRsnie_auth->acount = cpu2le16(pRsnie_auth->acount);
510
511         (*rsn_len) += sizeof(RSNIE_AUTH);       // update current RSNIE length
512
513 }
514
515 /*
516         ========================================================================
517
518         Routine Description:
519                 Build capability in RSN-IE.
520                 It only shall be called by RTMPMakeRSNIE.
521
522         Arguments:
523                 pAd                     -       pointer to our pAdapter context
524         ElementID       -       indicate the WPA1 or WPA2
525                 apidx           -       indicate the interface index
526
527         Return Value:
528
529         Note:
530
531         ========================================================================
532 */
533 static VOID RTMPInsertRsnIeCap(
534         IN  PRTMP_ADAPTER   pAd,
535         IN      UCHAR                   ElementID,
536         IN      UCHAR                   apidx,
537         OUT     PUCHAR                  pRsnIe,
538         OUT     UCHAR                   *rsn_len)
539 {
540         RSN_CAPABILITIES    *pRSN_Cap;
541
542         // it could be ignored in WPA1 mode
543         if (ElementID == WpaIe)
544                 return;
545
546         pRSN_Cap = (RSN_CAPABILITIES*)(pRsnIe + (*rsn_len));
547
548
549         pRSN_Cap->word = cpu2le16(pRSN_Cap->word);
550
551         (*rsn_len) += sizeof(RSN_CAPABILITIES); // update current RSNIE length
552
553 }
554
555
556 /*
557         ========================================================================
558
559         Routine Description:
560                 Build RSN IE context. It is not included element-ID and length.
561
562         Arguments:
563                 pAd                     -       pointer to our pAdapter context
564         AuthMode        -       indicate the authentication mode
565         WepStatus       -       indicate the encryption type
566                 apidx           -       indicate the interface index
567
568         Return Value:
569
570         Note:
571
572         ========================================================================
573 */
574 VOID RTMPMakeRSNIE(
575     IN  PRTMP_ADAPTER   pAd,
576     IN  UINT            AuthMode,
577     IN  UINT            WepStatus,
578         IN      UCHAR                   apidx)
579 {
580         PUCHAR          pRsnIe = NULL;                  // primary RSNIE
581         UCHAR           *rsnielen_cur_p = 0;    // the length of the primary RSNIE
582         UCHAR           *rsnielen_ex_cur_p = 0; // the length of the secondary RSNIE
583         UCHAR           PrimaryRsnie;
584         BOOLEAN         bMixCipher = FALSE;     // indicate the pairwise and group cipher are different
585         UCHAR           p_offset;
586         WPA_MIX_PAIR_CIPHER             FlexibleCipher = MIX_CIPHER_NOTUSE;     // it provide the more flexible cipher combination in WPA-WPA2 and TKIPAES mode
587
588         rsnielen_cur_p = NULL;
589         rsnielen_ex_cur_p = NULL;
590
591         {
592                 {
593                         if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
594                         {
595                                 if (AuthMode < Ndis802_11AuthModeWPA)
596                                         return;
597                         }
598                         else
599                         {
600                                 // Support WPAPSK or WPA2PSK in STA-Infra mode
601                                 // Support WPANone in STA-Adhoc mode
602                                 if ((AuthMode != Ndis802_11AuthModeWPAPSK) &&
603                                         (AuthMode != Ndis802_11AuthModeWPA2PSK) &&
604                                         (AuthMode != Ndis802_11AuthModeWPANone)
605                                         )
606                                         return;
607                         }
608
609                         DBGPRINT(RT_DEBUG_TRACE,("==> RTMPMakeRSNIE(STA)\n"));
610
611                         // Zero RSNIE context
612                         pAd->StaCfg.RSNIE_Len = 0;
613                         NdisZeroMemory(pAd->StaCfg.RSN_IE, MAX_LEN_OF_RSNIE);
614
615                         // Pointer to RSNIE
616                         rsnielen_cur_p = &pAd->StaCfg.RSNIE_Len;
617                         pRsnIe = pAd->StaCfg.RSN_IE;
618
619                         bMixCipher = pAd->StaCfg.bMixCipher;
620                 }
621         }
622
623         // indicate primary RSNIE as WPA or WPA2
624         if ((AuthMode == Ndis802_11AuthModeWPA) ||
625                 (AuthMode == Ndis802_11AuthModeWPAPSK) ||
626                 (AuthMode == Ndis802_11AuthModeWPANone) ||
627                 (AuthMode == Ndis802_11AuthModeWPA1WPA2) ||
628                 (AuthMode == Ndis802_11AuthModeWPA1PSKWPA2PSK))
629                 PrimaryRsnie = WpaIe;
630         else
631                 PrimaryRsnie = Wpa2Ie;
632
633         {
634                 // Build the primary RSNIE
635                 // 1. insert cipher suite
636                 RTMPInsertRsnIeCipher(pAd, PrimaryRsnie, WepStatus, bMixCipher, FlexibleCipher, pRsnIe, &p_offset);
637
638                 // 2. insert AKM
639                 RTMPInsertRsnIeAKM(pAd, PrimaryRsnie, AuthMode, apidx, pRsnIe, &p_offset);
640
641                 // 3. insert capability
642                 RTMPInsertRsnIeCap(pAd, PrimaryRsnie, apidx, pRsnIe, &p_offset);
643         }
644
645         // 4. update the RSNIE length
646         *rsnielen_cur_p = p_offset;
647
648         hex_dump("The primary RSNIE", pRsnIe, (*rsnielen_cur_p));
649
650
651 }
652
653 /*
654     ==========================================================================
655     Description:
656                 Check whether the received frame is EAP frame.
657
658         Arguments:
659                 pAd                             -       pointer to our pAdapter context
660                 pEntry                  -       pointer to active entry
661                 pData                   -       the received frame
662                 DataByteCount   -       the received frame's length
663                 FromWhichBSSID  -       indicate the interface index
664
665     Return:
666          TRUE                   -       This frame is EAP frame
667          FALSE                  -       otherwise
668     ==========================================================================
669 */
670 BOOLEAN RTMPCheckWPAframe(
671     IN PRTMP_ADAPTER    pAd,
672     IN PMAC_TABLE_ENTRY pEntry,
673     IN PUCHAR           pData,
674     IN ULONG            DataByteCount,
675         IN UCHAR                        FromWhichBSSID)
676 {
677         ULONG   Body_len;
678         BOOLEAN Cancelled;
679
680
681     if(DataByteCount < (LENGTH_802_1_H + LENGTH_EAPOL_H))
682         return FALSE;
683
684
685         // Skip LLC header
686     if (NdisEqualMemory(SNAP_802_1H, pData, 6) ||
687         // Cisco 1200 AP may send packet with SNAP_BRIDGE_TUNNEL
688         NdisEqualMemory(SNAP_BRIDGE_TUNNEL, pData, 6))
689     {
690         pData += 6;
691     }
692         // Skip 2-bytes EAPoL type
693     if (NdisEqualMemory(EAPOL, pData, 2))
694     {
695         pData += 2;
696     }
697     else
698         return FALSE;
699
700     switch (*(pData+1))
701     {
702         case EAPPacket:
703                         Body_len = (*(pData+2)<<8) | (*(pData+3));
704             DBGPRINT(RT_DEBUG_TRACE, ("Receive EAP-Packet frame, TYPE = 0, Length = %ld\n", Body_len));
705             break;
706         case EAPOLStart:
707             DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL-Start frame, TYPE = 1 \n"));
708                         if (pEntry->EnqueueEapolStartTimerRunning != EAPOL_START_DISABLE)
709             {
710                 DBGPRINT(RT_DEBUG_TRACE, ("Cancel the EnqueueEapolStartTimerRunning \n"));
711                 RTMPCancelTimer(&pEntry->EnqueueStartForPSKTimer, &Cancelled);
712                 pEntry->EnqueueEapolStartTimerRunning = EAPOL_START_DISABLE;
713             }
714             break;
715         case EAPOLLogoff:
716             DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOLLogoff frame, TYPE = 2 \n"));
717             break;
718         case EAPOLKey:
719                         Body_len = (*(pData+2)<<8) | (*(pData+3));
720             DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL-Key frame, TYPE = 3, Length = %ld\n", Body_len));
721             break;
722         case EAPOLASFAlert:
723             DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOLASFAlert frame, TYPE = 4 \n"));
724             break;
725         default:
726             return FALSE;
727
728     }
729     return TRUE;
730 }
731
732
733 /*
734     ==========================================================================
735     Description:
736         ENCRYPT AES GTK before sending in EAPOL frame.
737         AES GTK length = 128 bit,  so fix blocks for aes-key-wrap as 2 in this function.
738         This function references to RFC 3394 for aes key wrap algorithm.
739     Return:
740     ==========================================================================
741 */
742 VOID AES_GTK_KEY_WRAP(
743     IN UCHAR    *key,
744     IN UCHAR    *plaintext,
745     IN UCHAR    p_len,
746     OUT UCHAR   *ciphertext)
747 {
748     UCHAR       A[8], BIN[16], BOUT[16];
749     UCHAR       R[512];
750     INT         num_blocks = p_len/8;   // unit:64bits
751     INT         i, j;
752     aes_context aesctx;
753     UCHAR       xor;
754
755     rtmp_aes_set_key(&aesctx, key, 128);
756
757     // Init IA
758     for (i = 0; i < 8; i++)
759         A[i] = 0xa6;
760
761     //Input plaintext
762     for (i = 0; i < num_blocks; i++)
763     {
764         for (j = 0 ; j < 8; j++)
765             R[8 * (i + 1) + j] = plaintext[8 * i + j];
766     }
767
768     // Key Mix
769     for (j = 0; j < 6; j++)
770     {
771         for(i = 1; i <= num_blocks; i++)
772         {
773             //phase 1
774             NdisMoveMemory(BIN, A, 8);
775             NdisMoveMemory(&BIN[8], &R[8 * i], 8);
776             rtmp_aes_encrypt(&aesctx, BIN, BOUT);
777
778             NdisMoveMemory(A, &BOUT[0], 8);
779             xor = num_blocks * j + i;
780             A[7] = BOUT[7] ^ xor;
781             NdisMoveMemory(&R[8 * i], &BOUT[8], 8);
782         }
783     }
784
785     // Output ciphertext
786     NdisMoveMemory(ciphertext, A, 8);
787
788     for (i = 1; i <= num_blocks; i++)
789     {
790         for (j = 0 ; j < 8; j++)
791             ciphertext[8 * i + j] = R[8 * i + j];
792     }
793 }
794
795
796 /*
797         ========================================================================
798
799         Routine Description:
800                 Misc function to decrypt AES body
801
802         Arguments:
803
804         Return Value:
805
806         Note:
807                 This function references to     RFC     3394 for aes key unwrap algorithm.
808
809         ========================================================================
810 */
811 VOID    AES_GTK_KEY_UNWRAP(
812         IN      UCHAR   *key,
813         OUT     UCHAR   *plaintext,
814         IN      UCHAR    c_len,
815         IN      UCHAR   *ciphertext)
816
817 {
818         UCHAR       A[8], BIN[16], BOUT[16];
819         UCHAR       xor;
820         INT         i, j;
821         aes_context aesctx;
822         UCHAR       *R;
823         INT         num_blocks = c_len/8;       // unit:64bits
824
825
826         os_alloc_mem(NULL, (PUCHAR *)&R, 512);
827
828         if (R == NULL)
829     {
830         DBGPRINT(RT_DEBUG_ERROR, ("!!!AES_GTK_KEY_UNWRAP: no memory!!!\n"));
831         return;
832     } /* End of if */
833
834         // Initialize
835         NdisMoveMemory(A, ciphertext, 8);
836         //Input plaintext
837         for(i = 0; i < (c_len-8); i++)
838         {
839                 R[ i] = ciphertext[i + 8];
840         }
841
842         rtmp_aes_set_key(&aesctx, key, 128);
843
844         for(j = 5; j >= 0; j--)
845         {
846                 for(i = (num_blocks-1); i > 0; i--)
847                 {
848                         xor = (num_blocks -1 )* j + i;
849                         NdisMoveMemory(BIN, A, 8);
850                         BIN[7] = A[7] ^ xor;
851                         NdisMoveMemory(&BIN[8], &R[(i-1)*8], 8);
852                         rtmp_aes_decrypt(&aesctx, BIN, BOUT);
853                         NdisMoveMemory(A, &BOUT[0], 8);
854                         NdisMoveMemory(&R[(i-1)*8], &BOUT[8], 8);
855                 }
856         }
857
858         // OUTPUT
859         for(i = 0; i < c_len; i++)
860         {
861                 plaintext[i] = R[i];
862         }
863
864
865         os_free_mem(NULL, R);
866 }
867
868 /*
869     ==========================================================================
870     Description:
871                 Report the EAP message type
872
873         Arguments:
874                 msg             -       EAPOL_PAIR_MSG_1
875                                         EAPOL_PAIR_MSG_2
876                                         EAPOL_PAIR_MSG_3
877                                         EAPOL_PAIR_MSG_4
878                                         EAPOL_GROUP_MSG_1
879                                         EAPOL_GROUP_MSG_2
880
881     Return:
882          message type string
883
884     ==========================================================================
885 */
886 CHAR *GetEapolMsgType(CHAR msg)
887 {
888     if(msg == EAPOL_PAIR_MSG_1)
889         return "Pairwise Message 1";
890     else if(msg == EAPOL_PAIR_MSG_2)
891         return "Pairwise Message 2";
892         else if(msg == EAPOL_PAIR_MSG_3)
893         return "Pairwise Message 3";
894         else if(msg == EAPOL_PAIR_MSG_4)
895         return "Pairwise Message 4";
896         else if(msg == EAPOL_GROUP_MSG_1)
897         return "Group Message 1";
898         else if(msg == EAPOL_GROUP_MSG_2)
899         return "Group Message 2";
900     else
901         return "Invalid Message";
902 }
903
904
905 /*
906     ========================================================================
907
908     Routine Description:
909     Check Sanity RSN IE of EAPoL message
910
911     Arguments:
912
913     Return Value:
914
915
916     ========================================================================
917 */
918 BOOLEAN RTMPCheckRSNIE(
919         IN  PRTMP_ADAPTER   pAd,
920         IN  PUCHAR          pData,
921         IN  UCHAR           DataLen,
922         IN  MAC_TABLE_ENTRY *pEntry,
923         OUT     UCHAR                   *Offset)
924 {
925         PUCHAR              pVIE;
926         UCHAR               len;
927         PEID_STRUCT         pEid;
928         BOOLEAN                         result = FALSE;
929
930         pVIE = pData;
931         len      = DataLen;
932         *Offset = 0;
933
934         while (len > sizeof(RSNIE2))
935         {
936                 pEid = (PEID_STRUCT) pVIE;
937                 // WPA RSN IE
938                 if ((pEid->Eid == IE_WPA) && (NdisEqualMemory(pEid->Octet, WPA_OUI, 4)))
939                 {
940                         if ((pEntry->AuthMode == Ndis802_11AuthModeWPA || pEntry->AuthMode == Ndis802_11AuthModeWPAPSK) &&
941                                 (NdisEqualMemory(pVIE, pEntry->RSN_IE, pEntry->RSNIE_Len)) &&
942                                 (pEntry->RSNIE_Len == (pEid->Len + 2)))
943                         {
944                                         result = TRUE;
945                         }
946
947                         *Offset += (pEid->Len + 2);
948                 }
949                 // WPA2 RSN IE
950                 else if ((pEid->Eid == IE_RSN) && (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3)))
951                 {
952                         if ((pEntry->AuthMode == Ndis802_11AuthModeWPA2 || pEntry->AuthMode == Ndis802_11AuthModeWPA2PSK) &&
953                                 (NdisEqualMemory(pVIE, pEntry->RSN_IE, pEntry->RSNIE_Len)) &&
954                                 (pEntry->RSNIE_Len == (pEid->Len + 2))/* ToDo-AlbertY for mesh*/)
955                         {
956                                         result = TRUE;
957                         }
958
959                         *Offset += (pEid->Len + 2);
960                 }
961                 else
962                 {
963                         break;
964                 }
965
966                 pVIE += (pEid->Len + 2);
967                 len  -= (pEid->Len + 2);
968         }
969
970
971         return result;
972
973 }
974
975
976 /*
977     ========================================================================
978
979     Routine Description:
980     Parse KEYDATA field.  KEYDATA[] May contain 2 RSN IE and optionally GTK.
981     GTK  is encaptulated in KDE format at  p.83 802.11i D10
982
983     Arguments:
984
985     Return Value:
986
987     Note:
988         802.11i D10
989
990     ========================================================================
991 */
992 BOOLEAN RTMPParseEapolKeyData(
993         IN  PRTMP_ADAPTER   pAd,
994         IN  PUCHAR          pKeyData,
995         IN  UCHAR           KeyDataLen,
996         IN      UCHAR                   GroupKeyIndex,
997         IN      UCHAR                   MsgType,
998         IN      BOOLEAN                 bWPA2,
999         IN  MAC_TABLE_ENTRY *pEntry)
1000 {
1001     PKDE_ENCAP          pKDE = NULL;
1002     PUCHAR              pMyKeyData = pKeyData;
1003     UCHAR               KeyDataLength = KeyDataLen;
1004     UCHAR               GTKLEN = 0;
1005         UCHAR                           DefaultIdx = 0;
1006         UCHAR                           skip_offset;
1007
1008         // Verify The RSN IE contained in pairewise_msg_2 && pairewise_msg_3 and skip it
1009         if (MsgType == EAPOL_PAIR_MSG_2 || MsgType == EAPOL_PAIR_MSG_3)
1010     {
1011                 // Check RSN IE whether it is WPA2/WPA2PSK
1012                 if (!RTMPCheckRSNIE(pAd, pKeyData, KeyDataLen, pEntry, &skip_offset))
1013                 {
1014                         // send wireless event - for RSN IE different
1015                         if (pAd->CommonCfg.bWirelessEvent)
1016                                 RTMPSendWirelessEvent(pAd, IW_RSNIE_DIFF_EVENT_FLAG, pEntry->Addr, pEntry->apidx, 0);
1017
1018                 DBGPRINT(RT_DEBUG_ERROR, ("RSN_IE Different in msg %d of 4-way handshake!\n", MsgType));
1019                         hex_dump("Receive RSN_IE ", pKeyData, KeyDataLen);
1020                         hex_dump("Desired RSN_IE ", pEntry->RSN_IE, pEntry->RSNIE_Len);
1021
1022                         return FALSE;
1023         }
1024         else
1025                 {
1026                         if (bWPA2 && MsgType == EAPOL_PAIR_MSG_3)
1027                         {
1028                                 // skip RSN IE
1029                                 pMyKeyData += skip_offset;
1030                                 KeyDataLength -= skip_offset;
1031                                 DBGPRINT(RT_DEBUG_TRACE, ("RTMPParseEapolKeyData ==> WPA2/WPA2PSK RSN IE matched in Msg 3, Length(%d) \n", skip_offset));
1032                         }
1033                         else
1034                                 return TRUE;
1035                 }
1036         }
1037
1038         DBGPRINT(RT_DEBUG_TRACE,("RTMPParseEapolKeyData ==> KeyDataLength %d without RSN_IE \n", KeyDataLength));
1039
1040         // Parse EKD format in pairwise_msg_3_WPA2 && group_msg_1_WPA2
1041         if (bWPA2 && (MsgType == EAPOL_PAIR_MSG_3 || MsgType == EAPOL_GROUP_MSG_1))
1042         {
1043                 if (KeyDataLength >= 8) // KDE format exclude GTK length
1044         {
1045                 pKDE = (PKDE_ENCAP) pMyKeyData;
1046
1047
1048                         DefaultIdx = pKDE->GTKEncap.Kid;
1049
1050                         // Sanity check - KED length
1051                         if (KeyDataLength < (pKDE->Len + 2))
1052                 {
1053                         DBGPRINT(RT_DEBUG_ERROR, ("ERROR: The len from KDE is too short \n"));
1054                         return FALSE;
1055                 }
1056
1057                         // Get GTK length - refer to IEEE 802.11i-2004 p.82
1058                         GTKLEN = pKDE->Len -6;
1059                         if (GTKLEN < LEN_AES_KEY)
1060                         {
1061                                 DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key length is too short (%d) \n", GTKLEN));
1062                         return FALSE;
1063                         }
1064
1065         }
1066                 else
1067         {
1068                         DBGPRINT(RT_DEBUG_ERROR, ("ERROR: KDE format length is too short \n"));
1069                 return FALSE;
1070         }
1071
1072                 DBGPRINT(RT_DEBUG_TRACE, ("GTK in KDE format ,DefaultKeyID=%d, KeyLen=%d \n", DefaultIdx, GTKLEN));
1073                 // skip it
1074                 pMyKeyData += 8;
1075                 KeyDataLength -= 8;
1076
1077         }
1078         else if (!bWPA2 && MsgType == EAPOL_GROUP_MSG_1)
1079         {
1080                 DefaultIdx = GroupKeyIndex;
1081                 DBGPRINT(RT_DEBUG_TRACE, ("GTK DefaultKeyID=%d \n", DefaultIdx));
1082         }
1083
1084         // Sanity check - shared key index must be 1 ~ 3
1085         if (DefaultIdx < 1 || DefaultIdx > 3)
1086     {
1087         DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key index(%d) is invalid in %s %s \n", DefaultIdx, ((bWPA2) ? "WPA2" : "WPA"), GetEapolMsgType(MsgType)));
1088         return FALSE;
1089     }
1090
1091         return TRUE;
1092
1093 }
1094
1095
1096 /*
1097         ========================================================================
1098
1099         Routine Description:
1100                 Construct EAPoL message for WPA handshaking
1101                 Its format is below,
1102
1103                 +--------------------+
1104                 | Protocol Version       |  1 octet
1105                 +--------------------+
1106                 | Protocol Type          |      1 octet
1107                 +--------------------+
1108                 | Body Length            |  2 octets
1109                 +--------------------+
1110                 | Descriptor Type        |      1 octet
1111                 +--------------------+
1112                 | Key Information    |  2 octets
1113                 +--------------------+
1114                 | Key Length         |  1 octet
1115                 +--------------------+
1116                 | Key Repaly Counter |  8 octets
1117                 +--------------------+
1118                 | Key Nonce                  |  32 octets
1119                 +--------------------+
1120                 | Key IV                         |  16 octets
1121                 +--------------------+
1122                 | Key RSC                        |  8 octets
1123                 +--------------------+
1124                 | Key ID or Reserved |  8 octets
1125                 +--------------------+
1126                 | Key MIC                        |      16 octets
1127                 +--------------------+
1128                 | Key Data Length        |      2 octets
1129                 +--------------------+
1130                 | Key Data                       |      n octets
1131                 +--------------------+
1132
1133
1134         Arguments:
1135                 pAd                     Pointer to our adapter
1136
1137         Return Value:
1138                 None
1139
1140         Note:
1141
1142         ========================================================================
1143 */
1144 VOID    ConstructEapolMsg(
1145         IN      PRTMP_ADAPTER           pAd,
1146     IN  UCHAR                           AuthMode,
1147     IN  UCHAR                           WepStatus,
1148     IN  UCHAR                           GroupKeyWepStatus,
1149     IN  UCHAR                           MsgType,
1150     IN  UCHAR                           DefaultKeyIdx,
1151     IN  UCHAR                           *ReplayCounter,
1152         IN      UCHAR                           *KeyNonce,
1153         IN      UCHAR                           *TxRSC,
1154         IN      UCHAR                           *PTK,
1155         IN      UCHAR                           *GTK,
1156         IN      UCHAR                           *RSNIE,
1157         IN      UCHAR                           RSNIE_Len,
1158     OUT PEAPOL_PACKET       pMsg)
1159 {
1160         BOOLEAN bWPA2 = FALSE;
1161
1162         // Choose WPA2 or not
1163         if ((AuthMode == Ndis802_11AuthModeWPA2) || (AuthMode == Ndis802_11AuthModeWPA2PSK))
1164                 bWPA2 = TRUE;
1165
1166     // Init Packet and Fill header
1167     pMsg->ProVer = EAPOL_VER;
1168     pMsg->ProType = EAPOLKey;
1169
1170         // Default 95 bytes, the EAPoL-Key descriptor exclude Key-data field
1171         pMsg->Body_Len[1] = LEN_EAPOL_KEY_MSG;
1172
1173         // Fill in EAPoL descriptor
1174         if (bWPA2)
1175                 pMsg->KeyDesc.Type = WPA2_KEY_DESC;
1176         else
1177                 pMsg->KeyDesc.Type = WPA1_KEY_DESC;
1178
1179         // Fill in Key information, refer to IEEE Std 802.11i-2004 page 78
1180         // When either the pairwise or the group cipher is AES, the DESC_TYPE_AES(2) shall be used.
1181         pMsg->KeyDesc.KeyInfo.KeyDescVer =
1182                 (((WepStatus == Ndis802_11Encryption3Enabled) || (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
1183
1184         // Specify Key Type as Group(0) or Pairwise(1)
1185         if (MsgType >= EAPOL_GROUP_MSG_1)
1186                 pMsg->KeyDesc.KeyInfo.KeyType = GROUPKEY;
1187         else
1188                 pMsg->KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
1189
1190         // Specify Key Index, only group_msg1_WPA1
1191         if (!bWPA2 && (MsgType >= EAPOL_GROUP_MSG_1))
1192                 pMsg->KeyDesc.KeyInfo.KeyIndex = DefaultKeyIdx;
1193
1194         if (MsgType == EAPOL_PAIR_MSG_3)
1195                 pMsg->KeyDesc.KeyInfo.Install = 1;
1196
1197         if ((MsgType == EAPOL_PAIR_MSG_1) || (MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1))
1198                 pMsg->KeyDesc.KeyInfo.KeyAck = 1;
1199
1200         if (MsgType != EAPOL_PAIR_MSG_1)
1201                 pMsg->KeyDesc.KeyInfo.KeyMic = 1;
1202
1203         if ((bWPA2 && (MsgType >= EAPOL_PAIR_MSG_3)) || (!bWPA2 && (MsgType >= EAPOL_GROUP_MSG_1)))
1204     {
1205         pMsg->KeyDesc.KeyInfo.Secure = 1;
1206     }
1207
1208         if (bWPA2 && ((MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1)))
1209     {
1210         pMsg->KeyDesc.KeyInfo.EKD_DL = 1;
1211     }
1212
1213         // key Information element has done.
1214         *(USHORT *)(&pMsg->KeyDesc.KeyInfo) = cpu2le16(*(USHORT *)(&pMsg->KeyDesc.KeyInfo));
1215
1216         // Fill in Key Length
1217         {
1218                 if (MsgType >= EAPOL_GROUP_MSG_1)
1219                 {
1220                         // the length of group key cipher
1221                         pMsg->KeyDesc.KeyLength[1] = ((GroupKeyWepStatus == Ndis802_11Encryption2Enabled) ? TKIP_GTK_LENGTH : LEN_AES_KEY);
1222                 }
1223                 else
1224                 {
1225                         // the length of pairwise key cipher
1226                         pMsg->KeyDesc.KeyLength[1] = ((WepStatus == Ndis802_11Encryption2Enabled) ? LEN_TKIP_KEY : LEN_AES_KEY);
1227                 }
1228         }
1229
1230         // Fill in replay counter
1231     NdisMoveMemory(pMsg->KeyDesc.ReplayCounter, ReplayCounter, LEN_KEY_DESC_REPLAY);
1232
1233         // Fill Key Nonce field
1234         // ANonce : pairwise_msg1 & pairwise_msg3
1235         // SNonce : pairwise_msg2
1236         // GNonce : group_msg1_wpa1
1237         if ((MsgType <= EAPOL_PAIR_MSG_3) || ((!bWPA2 && (MsgType == EAPOL_GROUP_MSG_1))))
1238         NdisMoveMemory(pMsg->KeyDesc.KeyNonce, KeyNonce, LEN_KEY_DESC_NONCE);
1239
1240         // Fill key IV - WPA2 as 0, WPA1 as random
1241         if (!bWPA2 && (MsgType == EAPOL_GROUP_MSG_1))
1242         {
1243                 // Suggest IV be random number plus some number,
1244                 NdisMoveMemory(pMsg->KeyDesc.KeyIv, &KeyNonce[16], LEN_KEY_DESC_IV);
1245         pMsg->KeyDesc.KeyIv[15] += 2;
1246         }
1247
1248     // Fill Key RSC field
1249     // It contains the RSC for the GTK being installed.
1250         if ((MsgType == EAPOL_PAIR_MSG_3 && bWPA2) || (MsgType == EAPOL_GROUP_MSG_1))
1251         {
1252         NdisMoveMemory(pMsg->KeyDesc.KeyRsc, TxRSC, 6);
1253         }
1254
1255         // Clear Key MIC field for MIC calculation later
1256     NdisZeroMemory(pMsg->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
1257
1258         ConstructEapolKeyData(pAd,
1259                                                   AuthMode,
1260                                                   WepStatus,
1261                                                   GroupKeyWepStatus,
1262                                                   MsgType,
1263                                                   DefaultKeyIdx,
1264                                                   bWPA2,
1265                                                   PTK,
1266                                                   GTK,
1267                                                   RSNIE,
1268                                                   RSNIE_Len,
1269                                                   pMsg);
1270
1271         // Calculate MIC and fill in KeyMic Field except Pairwise Msg 1.
1272         if (MsgType != EAPOL_PAIR_MSG_1)
1273         {
1274                 CalculateMIC(pAd, WepStatus, PTK, pMsg);
1275         }
1276
1277         DBGPRINT(RT_DEBUG_TRACE, ("===> ConstructEapolMsg for %s %s\n", ((bWPA2) ? "WPA2" : "WPA"), GetEapolMsgType(MsgType)));
1278         DBGPRINT(RT_DEBUG_TRACE, ("          Body length = %d \n", pMsg->Body_Len[1]));
1279         DBGPRINT(RT_DEBUG_TRACE, ("          Key length  = %d \n", pMsg->KeyDesc.KeyLength[1]));
1280
1281
1282 }
1283
1284 /*
1285         ========================================================================
1286
1287         Routine Description:
1288                 Construct the Key Data field of EAPoL message
1289
1290         Arguments:
1291                 pAd                     Pointer to our adapter
1292                 Elem            Message body
1293
1294         Return Value:
1295                 None
1296
1297         Note:
1298
1299         ========================================================================
1300 */
1301 VOID    ConstructEapolKeyData(
1302         IN      PRTMP_ADAPTER   pAd,
1303         IN      UCHAR                   AuthMode,
1304         IN      UCHAR                   WepStatus,
1305         IN      UCHAR                   GroupKeyWepStatus,
1306         IN      UCHAR                   MsgType,
1307         IN      UCHAR                   DefaultKeyIdx,
1308         IN      BOOLEAN                 bWPA2Capable,
1309         IN      UCHAR                   *PTK,
1310         IN      UCHAR                   *GTK,
1311         IN      UCHAR                   *RSNIE,
1312         IN      UCHAR                   RSNIE_LEN,
1313         OUT PEAPOL_PACKET   pMsg)
1314 {
1315         UCHAR           *mpool, *Key_Data, *Rc4GTK;
1316         UCHAR       ekey[(LEN_KEY_DESC_IV+LEN_EAP_EK)];
1317         UCHAR           data_offset;
1318
1319
1320         if (MsgType == EAPOL_PAIR_MSG_1 || MsgType == EAPOL_PAIR_MSG_4 || MsgType == EAPOL_GROUP_MSG_2)
1321                 return;
1322
1323         // allocate memory pool
1324         os_alloc_mem(pAd, (PUCHAR *)&mpool, 1500);
1325
1326     if (mpool == NULL)
1327                 return;
1328
1329         /* Rc4GTK Len = 512 */
1330         Rc4GTK = (UCHAR *) ROUND_UP(mpool, 4);
1331         /* Key_Data Len = 512 */
1332         Key_Data = (UCHAR *) ROUND_UP(Rc4GTK + 512, 4);
1333
1334         NdisZeroMemory(Key_Data, 512);
1335         pMsg->KeyDesc.KeyDataLen[1] = 0;
1336         data_offset = 0;
1337
1338         // Encapsulate RSNIE in pairwise_msg2 & pairwise_msg3
1339         if (RSNIE_LEN && ((MsgType == EAPOL_PAIR_MSG_2) || (MsgType == EAPOL_PAIR_MSG_3)))
1340         {
1341                 if (bWPA2Capable)
1342                         Key_Data[data_offset + 0] = IE_WPA2;
1343                 else
1344                         Key_Data[data_offset + 0] = IE_WPA;
1345
1346         Key_Data[data_offset + 1] = RSNIE_LEN;
1347                 NdisMoveMemory(&Key_Data[data_offset + 2], RSNIE, RSNIE_LEN);
1348                 data_offset += (2 + RSNIE_LEN);
1349         }
1350
1351         // Encapsulate KDE format in pairwise_msg3_WPA2 & group_msg1_WPA2
1352         if (bWPA2Capable && ((MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1)))
1353         {
1354                 // Key Data Encapsulation (KDE) format - 802.11i-2004  Figure-43w and Table-20h
1355         Key_Data[data_offset + 0] = 0xDD;
1356
1357                 if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
1358                 {
1359                         Key_Data[data_offset + 1] = 0x16;// 4+2+16(OUI+DataType+DataField)
1360                 }
1361                 else
1362                 {
1363                         Key_Data[data_offset + 1] = 0x26;// 4+2+32(OUI+DataType+DataField)
1364                 }
1365
1366         Key_Data[data_offset + 2] = 0x00;
1367         Key_Data[data_offset + 3] = 0x0F;
1368         Key_Data[data_offset + 4] = 0xAC;
1369         Key_Data[data_offset + 5] = 0x01;
1370
1371                 // GTK KDE format - 802.11i-2004  Figure-43x
1372         Key_Data[data_offset + 6] = (DefaultKeyIdx & 0x03);
1373         Key_Data[data_offset + 7] = 0x00;       // Reserved Byte
1374
1375                 data_offset += 8;
1376         }
1377
1378
1379         // Encapsulate GTK and encrypt the key-data field with KEK.
1380         // Only for pairwise_msg3_WPA2 and group_msg1
1381         if ((MsgType == EAPOL_PAIR_MSG_3 && bWPA2Capable) || (MsgType == EAPOL_GROUP_MSG_1))
1382         {
1383                 // Fill in GTK
1384                 if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
1385                 {
1386                         NdisMoveMemory(&Key_Data[data_offset], GTK, LEN_AES_KEY);
1387                         data_offset += LEN_AES_KEY;
1388                 }
1389                 else
1390                 {
1391                         NdisMoveMemory(&Key_Data[data_offset], GTK, TKIP_GTK_LENGTH);
1392                         data_offset += TKIP_GTK_LENGTH;
1393                 }
1394
1395                 // Still dont know why, but if not append will occur "GTK not include in MSG3"
1396                 // Patch for compatibility between zero config and funk
1397                 if (MsgType == EAPOL_PAIR_MSG_3 && bWPA2Capable)
1398                 {
1399                         if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
1400                         {
1401                                 Key_Data[data_offset + 0] = 0xDD;
1402                                 Key_Data[data_offset + 1] = 0;
1403                                 data_offset += 2;
1404                         }
1405                         else
1406                         {
1407                                 Key_Data[data_offset + 0] = 0xDD;
1408                                 Key_Data[data_offset + 1] = 0;
1409                                 Key_Data[data_offset + 2] = 0;
1410                                 Key_Data[data_offset + 3] = 0;
1411                                 Key_Data[data_offset + 4] = 0;
1412                                 Key_Data[data_offset + 5] = 0;
1413                                 data_offset += 6;
1414                         }
1415                 }
1416
1417                 // Encrypt the data material in key data field
1418                 if (WepStatus == Ndis802_11Encryption3Enabled)
1419                 {
1420                         AES_GTK_KEY_WRAP(&PTK[16], Key_Data, data_offset, Rc4GTK);
1421             // AES wrap function will grow 8 bytes in length
1422             data_offset += 8;
1423                 }
1424                 else
1425                 {
1426                         // PREPARE Encrypted  "Key DATA" field.  (Encrypt GTK with RC4, usinf PTK[16]->[31] as Key, IV-field as IV)
1427                         // put TxTsc in Key RSC field
1428                         pAd->PrivateInfo.FCSCRC32 = PPPINITFCS32;   //Init crc32.
1429
1430                         // ekey is the contanetion of IV-field, and PTK[16]->PTK[31]
1431                         NdisMoveMemory(ekey, pMsg->KeyDesc.KeyIv, LEN_KEY_DESC_IV);
1432                         NdisMoveMemory(&ekey[LEN_KEY_DESC_IV], &PTK[16], LEN_EAP_EK);
1433                         ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, ekey, sizeof(ekey));  //INIT SBOX, KEYLEN+3(IV)
1434                         pAd->PrivateInfo.FCSCRC32 = RTMP_CALC_FCS32(pAd->PrivateInfo.FCSCRC32, Key_Data, data_offset);
1435                         WPAARCFOUR_ENCRYPT(&pAd->PrivateInfo.WEPCONTEXT, Rc4GTK, Key_Data, data_offset);
1436                 }
1437
1438                 NdisMoveMemory(pMsg->KeyDesc.KeyData, Rc4GTK, data_offset);
1439         }
1440         else
1441         {
1442                 NdisMoveMemory(pMsg->KeyDesc.KeyData, Key_Data, data_offset);
1443         }
1444
1445         // set key data length field and total length
1446         pMsg->KeyDesc.KeyDataLen[1] = data_offset;
1447     pMsg->Body_Len[1] += data_offset;
1448
1449         os_free_mem(pAd, mpool);
1450
1451 }
1452
1453 /*
1454         ========================================================================
1455
1456         Routine Description:
1457                 Calcaulate MIC. It is used during 4-ways handsharking.
1458
1459         Arguments:
1460                 pAd                             -       pointer to our pAdapter context
1461         PeerWepStatus   -       indicate the encryption type
1462
1463         Return Value:
1464
1465         Note:
1466
1467         ========================================================================
1468 */
1469 VOID    CalculateMIC(
1470         IN      PRTMP_ADAPTER   pAd,
1471         IN      UCHAR                   PeerWepStatus,
1472         IN      UCHAR                   *PTK,
1473         OUT PEAPOL_PACKET   pMsg)
1474 {
1475     UCHAR   *OutBuffer;
1476         ULONG   FrameLen = 0;
1477         UCHAR   mic[LEN_KEY_DESC_MIC];
1478         UCHAR   digest[80];
1479
1480         // allocate memory for MIC calculation
1481         os_alloc_mem(pAd, (PUCHAR *)&OutBuffer, 512);
1482
1483     if (OutBuffer == NULL)
1484     {
1485                 DBGPRINT(RT_DEBUG_ERROR, ("!!!CalculateMIC: no memory!!!\n"));
1486                 return;
1487     }
1488
1489         // make a frame for calculating MIC.
1490     MakeOutgoingFrame(OutBuffer,                &FrameLen,
1491                       pMsg->Body_Len[1] + 4,    pMsg,
1492                       END_OF_ARGS);
1493
1494         NdisZeroMemory(mic, sizeof(mic));
1495
1496         // Calculate MIC
1497     if (PeerWepStatus == Ndis802_11Encryption3Enabled)
1498         {
1499                 HMAC_SHA1(OutBuffer,  FrameLen, PTK, LEN_EAP_MICK, digest);
1500                 NdisMoveMemory(mic, digest, LEN_KEY_DESC_MIC);
1501         }
1502         else
1503         {
1504                 hmac_md5(PTK,  LEN_EAP_MICK, OutBuffer, FrameLen, mic);
1505         }
1506
1507         // store the calculated MIC
1508         NdisMoveMemory(pMsg->KeyDesc.KeyMic, mic, LEN_KEY_DESC_MIC);
1509
1510         os_free_mem(pAd, OutBuffer);
1511 }
1512
1513 /*
1514         ========================================================================
1515
1516         Routine Description:
1517                 Some received frames can't decrypt by Asic, so decrypt them by software.
1518
1519         Arguments:
1520                 pAd                             -       pointer to our pAdapter context
1521         PeerWepStatus   -       indicate the encryption type
1522
1523         Return Value:
1524                 NDIS_STATUS_SUCCESS             -       decryption successful
1525                 NDIS_STATUS_FAILURE             -       decryption failure
1526
1527         ========================================================================
1528 */
1529 NDIS_STATUS     RTMPSoftDecryptBroadCastData(
1530         IN      PRTMP_ADAPTER                                   pAd,
1531         IN      RX_BLK                                                  *pRxBlk,
1532         IN  NDIS_802_11_ENCRYPTION_STATUS       GroupCipher,
1533         IN  PCIPHER_KEY                                         pShard_key)
1534 {
1535         PRXWI_STRUC                     pRxWI = pRxBlk->pRxWI;
1536
1537
1538
1539         // handle WEP decryption
1540         if (GroupCipher == Ndis802_11Encryption1Enabled)
1541     {
1542                 if (RTMPSoftDecryptWEP(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount, pShard_key))
1543                 {
1544
1545                         //Minus IV[4] & ICV[4]
1546                         pRxWI->MPDUtotalByteCount -= 8;
1547                 }
1548                 else
1549                 {
1550                         DBGPRINT(RT_DEBUG_ERROR, ("ERROR : Software decrypt WEP data fails.\n"));
1551                         // give up this frame
1552                         return NDIS_STATUS_FAILURE;
1553                 }
1554         }
1555         // handle TKIP decryption
1556         else if (GroupCipher == Ndis802_11Encryption2Enabled)
1557         {
1558                 if (RTMPSoftDecryptTKIP(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount, 0, pShard_key))
1559                 {
1560
1561                         //Minus 8 bytes MIC, 8 bytes IV/EIV, 4 bytes ICV
1562                         pRxWI->MPDUtotalByteCount -= 20;
1563                 }
1564         else
1565                 {
1566                         DBGPRINT(RT_DEBUG_ERROR, ("ERROR : RTMPSoftDecryptTKIP Failed\n"));
1567                         // give up this frame
1568                         return NDIS_STATUS_FAILURE;
1569         }
1570         }
1571         // handle AES decryption
1572         else if (GroupCipher == Ndis802_11Encryption3Enabled)
1573         {
1574                 if (RTMPSoftDecryptAES(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount , pShard_key))
1575                 {
1576
1577                         //8 bytes MIC, 8 bytes IV/EIV (CCMP Header)
1578                         pRxWI->MPDUtotalByteCount -= 16;
1579                 }
1580                 else
1581                 {
1582                         DBGPRINT(RT_DEBUG_ERROR, ("ERROR : RTMPSoftDecryptAES Failed\n"));
1583                         // give up this frame
1584                         return NDIS_STATUS_FAILURE;
1585                 }
1586         }
1587         else
1588         {
1589                 // give up this frame
1590                 return NDIS_STATUS_FAILURE;
1591         }
1592
1593         return NDIS_STATUS_SUCCESS;
1594
1595 }
1596