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