summaryrefslogtreecommitdiffstats
path: root/NetworkPkg/IpSecDxe/Ikev2/Utility.c
blob: 16be09e14ad61166bd31c7430ad52d488e709a89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
/** @file
  The Common operations used by IKE Exchange Process.

  (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
  Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>

  This program and the accompanying materials
  are licensed and made available under the terms and conditions of the BSD License
  which accompanies this distribution.  The full text of the license may be found at
  http://opensource.org/licenses/bsd-license.php.

  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/

#include "Utility.h"
#include "IpSecDebug.h"
#include "IkeService.h"
#include "IpSecConfigImpl.h"

UINT16 mIkev2EncryptAlgorithmList[IKEV2_SUPPORT_ENCRYPT_ALGORITHM_NUM] = {
  IKEV2_TRANSFORM_ID_ENCR_3DES,
  IKEV2_TRANSFORM_ID_ENCR_AES_CBC, 
};

UINT16 mIkev2PrfAlgorithmList[IKEV2_SUPPORT_PRF_ALGORITHM_NUM] = {
  IKEV2_TRANSFORM_ID_PRF_HMAC_SHA1,
};

UINT16 mIkev2DhGroupAlgorithmList[IKEV2_SUPPORT_DH_ALGORITHM_NUM] = {
  IKEV2_TRANSFORM_ID_DH_1024MODP,
  IKEV2_TRANSFORM_ID_DH_2048MODP,
};

UINT16 mIkev2AuthAlgorithmList[IKEV2_SUPPORT_AUTH_ALGORITHM_NUM] = {
  IKEV2_TRANSFORM_ID_AUTH_HMAC_SHA1_96,
};

/**
  Allocate buffer for IKEV2_SA_SESSION and initialize it.

  @param[in] Private        Pointer to IPSEC_PRIVATE_DATA.
  @param[in] UdpService     Pointer to IKE_UDP_SERVICE related to this IKE SA Session.

  @return Pointer to IKEV2_SA_SESSION or NULL.

**/
IKEV2_SA_SESSION *
Ikev2SaSessionAlloc (
  IN IPSEC_PRIVATE_DATA       *Private,
  IN IKE_UDP_SERVICE          *UdpService
  )
{
  EFI_STATUS            Status;
  IKEV2_SESSION_COMMON  *SessionCommon;
  IKEV2_SA_SESSION      *IkeSaSession;

  IkeSaSession = AllocateZeroPool (sizeof (IKEV2_SA_SESSION));
  ASSERT (IkeSaSession != NULL);

  //
  // Initialize the fields of IkeSaSession and its SessionCommon.
  //
  IkeSaSession->NCookie              = NULL;
  IkeSaSession->Signature            = IKEV2_SA_SESSION_SIGNATURE;
  IkeSaSession->InitiatorCookie      = IkeGenerateCookie ();
  IkeSaSession->ResponderCookie      = 0;
  //
  // BUGBUG: Message ID starts from 2 is to match the OpenSwan requirement, but it 
  // might not match the IPv6 Logo. In its test specification, it mentions that
  // the Message ID should start from zero after the IKE_SA_INIT exchange.
  //
  IkeSaSession->MessageId            = 2;
  SessionCommon                      = &IkeSaSession->SessionCommon;
  SessionCommon->UdpService          = UdpService;
  SessionCommon->Private             = Private;
  SessionCommon->IkeSessionType      = IkeSessionTypeIkeSa;
  SessionCommon->IkeVer              = 2;
  SessionCommon->AfterEncodePayload  = NULL;
  SessionCommon->BeforeDecodePayload = NULL;

  //
  // Create a resend notfiy event for retry.
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER | EVT_NOTIFY_SIGNAL,
                  TPL_CALLBACK,
                  Ikev2ResendNotify,
                  SessionCommon,
                  &SessionCommon->TimeoutEvent
                  );

  if (EFI_ERROR (Status)) {
    FreePool (IkeSaSession);
    return NULL;
  }

  //
  // Initialize the lists in IkeSaSession.
  //
  InitializeListHead (&IkeSaSession->ChildSaSessionList);
  InitializeListHead (&IkeSaSession->ChildSaEstablishSessionList);
  InitializeListHead (&IkeSaSession->InfoMIDList);
  InitializeListHead (&IkeSaSession->DeleteSaList);

  return IkeSaSession;
}

/**
  Register the established IKEv2 SA into Private->Ikev2EstablishedList. If there is
  IKEV2_SA_SESSION with same remote peer IP, remove the old one then register the
  new one.

  @param[in]  IkeSaSession  Pointer to IKEV2_SA_SESSION to be registered.
  @param[in]  Private       Pointer to IPSEC_PRAVATE_DATA.

**/
VOID
Ikev2SaSessionReg (
  IN IKEV2_SA_SESSION          *IkeSaSession,
  IN IPSEC_PRIVATE_DATA        *Private
  )
{
  IKEV2_SESSION_COMMON         *SessionCommon;
  IKEV2_SA_SESSION             *OldIkeSaSession;
  EFI_STATUS                   Status;
  UINT64                       Lifetime;

  //
  // Keep IKE SA exclusive to remote ip address.
  //
  SessionCommon   = &IkeSaSession->SessionCommon;
  OldIkeSaSession = Ikev2SaSessionRemove (&Private->Ikev2EstablishedList, &SessionCommon->RemotePeerIp);
  if (OldIkeSaSession != NULL) {
    //
    // TODO: It should delete all child SAs if rekey the IKE SA.
    //
    Ikev2SaSessionFree (OldIkeSaSession);
  }

  //
  // Cleanup the fields of SessionCommon for processing.
  // 
  Ikev2SessionCommonRefresh (SessionCommon);

  //
  // Insert the ready IKE SA session into established list.
  //
  Ikev2SaSessionInsert (&Private->Ikev2EstablishedList, IkeSaSession, &SessionCommon->RemotePeerIp);

  //
  // Create a notfiy event for the IKE SA life time counting.
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER | EVT_NOTIFY_SIGNAL,
                  TPL_CALLBACK,
                  Ikev2LifetimeNotify,
                  SessionCommon,
                  &SessionCommon->TimeoutEvent
                  );
  if (EFI_ERROR(Status)){
    //
    // If TimerEvent creation failed, the SA will be alive untill user disable it or 
    // receiving a Delete Payload from peer. 
    //
    return;
  }

  //
  // Start to count the lifetime of the IKE SA.
  //
  if (IkeSaSession->Spd->Data->ProcessingPolicy->SaLifetime.HardLifetime == 0) {
    Lifetime = IKE_SA_DEFAULT_LIFETIME;
  } else {
    Lifetime = IkeSaSession->Spd->Data->ProcessingPolicy->SaLifetime.HardLifetime;
  }
  
  Status = gBS->SetTimer (
                  SessionCommon->TimeoutEvent,
                  TimerRelative,
                  MultU64x32(Lifetime, 10000000) // ms->100ns
                  );
  if (EFI_ERROR(Status)){
    //
    // If SetTimer failed, the SA will be alive untill user disable it or 
    // receiving a Delete Payload from peer. 
    //
    return ;
  }

  DEBUG ((
    DEBUG_INFO,
    "\n------IkeSa established and start to count down %d seconds lifetime\n",
    Lifetime
    ));

  return ;
}

/**
  Find a IKEV2_SA_SESSION by the remote peer IP.

  @param[in]  SaSessionList     SaSession List to be searched.
  @param[in]  RemotePeerIp      Pointer to specified IP address.

  @return Pointer to IKEV2_SA_SESSION if find one or NULL.

**/
IKEV2_SA_SESSION *
Ikev2SaSessionLookup (
  IN LIST_ENTRY           *SaSessionList,
  IN EFI_IP_ADDRESS       *RemotePeerIp
  )
{
  LIST_ENTRY        *Entry;
  IKEV2_SA_SESSION  *IkeSaSession;

  NET_LIST_FOR_EACH (Entry, SaSessionList) {
    IkeSaSession = IKEV2_SA_SESSION_BY_SESSION (Entry);

    if (CompareMem (
          &IkeSaSession->SessionCommon.RemotePeerIp,
          RemotePeerIp,
          sizeof (EFI_IP_ADDRESS)
          ) == 0) {

      return IkeSaSession;
    }
  }

  return NULL;
}

/**
  Insert a IKE_SA_SESSION into IkeSaSession list. The IkeSaSession list is either
  Private->Ikev2SaSession list or Private->Ikev2EstablishedList list.

  @param[in]  SaSessionList   Pointer to list to be inserted into.
  @param[in]  IkeSaSession    Pointer to IKEV2_SA_SESSION to be inserted. 
  @param[in]  RemotePeerIp    Pointer to EFI_IP_ADDRESSS to indicate the 
                              unique IKEV2_SA_SESSION.

**/
VOID
Ikev2SaSessionInsert (
  IN LIST_ENTRY           *SaSessionList,
  IN IKEV2_SA_SESSION     *IkeSaSession,
  IN EFI_IP_ADDRESS       *RemotePeerIp
  )
{
  Ikev2SaSessionRemove (SaSessionList, RemotePeerIp);
  InsertTailList (SaSessionList, &IkeSaSession->BySessionTable);
}

/**
  Remove the SA Session by Remote Peer IP.

  @param[in]  SaSessionList   Pointer to list to be searched.
  @param[in]  RemotePeerIp    Pointer to EFI_IP_ADDRESS to use for SA Session search.

  @retval Pointer to IKEV2_SA_SESSION with the specified remote IP address or NULL. 

**/
IKEV2_SA_SESSION *
Ikev2SaSessionRemove (
  IN LIST_ENTRY           *SaSessionList,
  IN EFI_IP_ADDRESS       *RemotePeerIp
  )
{
  LIST_ENTRY        *Entry;
  IKEV2_SA_SESSION  *IkeSaSession;

  NET_LIST_FOR_EACH (Entry, SaSessionList) {
    IkeSaSession = IKEV2_SA_SESSION_BY_SESSION (Entry);

    if (CompareMem (
          &IkeSaSession->SessionCommon.RemotePeerIp,
          RemotePeerIp,
          sizeof (EFI_IP_ADDRESS)
          ) == 0) {

      RemoveEntryList (Entry);
      return IkeSaSession;
    }
  }

  return NULL;
}

/**
  Marking a SA session as on deleting.

  @param[in]  IkeSaSession  Pointer to IKEV2_SA_SESSION.

  @retval     EFI_SUCCESS   Find the related SA session and marked it.

**/
EFI_STATUS
Ikev2SaSessionOnDeleting (
  IN IKEV2_SA_SESSION          *IkeSaSession
  )
{
  return EFI_SUCCESS;
}

/**
  Free specified Seession Common. The session common would belong to a IKE SA or 
  a Child SA.

  @param[in]   SessionCommon   Pointer to a Session Common.

**/
VOID
Ikev2SaSessionCommonFree (
  IN IKEV2_SESSION_COMMON      *SessionCommon
  )
{

  ASSERT (SessionCommon != NULL);

  if (SessionCommon->LastSentPacket != NULL) {
    IkePacketFree (SessionCommon->LastSentPacket);
  }

  if (SessionCommon->SaParams != NULL) {
    FreePool (SessionCommon->SaParams);
  }
  if (SessionCommon->TimeoutEvent != NULL) {
    gBS->CloseEvent (SessionCommon->TimeoutEvent);
  }
}

/**
  After IKE/Child SA is estiblished, close the time event and free sent packet.

  @param[in]   SessionCommon   Pointer to a Session Common.

**/
VOID
Ikev2SessionCommonRefresh (
  IN IKEV2_SESSION_COMMON      *SessionCommon
  )
{
  ASSERT (SessionCommon != NULL);

  gBS->CloseEvent (SessionCommon->TimeoutEvent);
  SessionCommon->TimeoutEvent     = NULL;
  SessionCommon->TimeoutInterval  = 0;
  SessionCommon->RetryCount       = 0;
  if (SessionCommon->LastSentPacket != NULL) {
    IkePacketFree (SessionCommon->LastSentPacket);
    SessionCommon->LastSentPacket = NULL;
  }

  return ;
}
/**
  Free specified IKEV2 SA Session. 

  @param[in]    IkeSaSession   Pointer to IKEV2_SA_SESSION to be freed.

**/
VOID
Ikev2SaSessionFree (
  IN IKEV2_SA_SESSION         *IkeSaSession
  )
{
  IKEV2_SESSION_KEYS      *IkeKeys;
  LIST_ENTRY              *Entry;
  IKEV2_CHILD_SA_SESSION  *ChildSa;
  IKEV2_DH_BUFFER         *DhBuffer;

  ASSERT (IkeSaSession != NULL);
  
  //
  // Delete Common Session
  //
  Ikev2SaSessionCommonFree (&IkeSaSession->SessionCommon);

  //
  // Delete ChildSaEstablish List and SAD
  //
  for (Entry = IkeSaSession->ChildSaEstablishSessionList.ForwardLink;
       Entry != &IkeSaSession->ChildSaEstablishSessionList;
      ) {

    ChildSa = IKEV2_CHILD_SA_SESSION_BY_IKE_SA (Entry);
    Entry   = Entry->ForwardLink;
    Ikev2ChildSaSilentDelete (ChildSa->IkeSaSession, ChildSa->LocalPeerSpi);

  }

  //
  // Delete ChildSaSessionList
  //
  for ( Entry  = IkeSaSession->ChildSaSessionList.ForwardLink;
        Entry != &IkeSaSession->ChildSaSessionList;
        ){
    ChildSa = IKEV2_CHILD_SA_SESSION_BY_IKE_SA (Entry);
    Entry   = Entry->ForwardLink;
    RemoveEntryList (Entry->BackLink);
    Ikev2ChildSaSessionFree (ChildSa);
  }

  //
  // Delete DhBuffer and Keys
  //
  if (IkeSaSession->IkeKeys != NULL) {
    IkeKeys  = IkeSaSession->IkeKeys;
    DhBuffer = IkeKeys->DhBuffer;

    //
    // Delete DhBuffer
    //
    Ikev2DhBufferFree (DhBuffer);

    //
    // Delete Keys
    //    
    if (IkeKeys->SkAiKey != NULL) {
      FreePool (IkeKeys->SkAiKey);
    }
    if (IkeKeys->SkArKey != NULL) {
      FreePool (IkeKeys->SkArKey);
    }
    if (IkeKeys->SkdKey != NULL) {
      FreePool (IkeKeys->SkdKey);
    }
    if (IkeKeys->SkEiKey != NULL) {
      FreePool (IkeKeys->SkEiKey);
    }
    if (IkeKeys->SkErKey != NULL) {
      FreePool (IkeKeys->SkErKey);
    }
    if (IkeKeys->SkPiKey != NULL) {
      FreePool (IkeKeys->SkPiKey);
    }
    if (IkeKeys->SkPrKey != NULL) {
      FreePool (IkeKeys->SkPrKey);
    }
    FreePool (IkeKeys);
  }

  if (IkeSaSession->SaData != NULL) {
    FreePool (IkeSaSession->SaData);
  }

  if (IkeSaSession->NiBlock != NULL) {
    FreePool (IkeSaSession->NiBlock);
  }

  if (IkeSaSession->NrBlock != NULL) {
    FreePool (IkeSaSession->NrBlock);
  }

  if (IkeSaSession->NCookie != NULL) {
    FreePool (IkeSaSession->NCookie);
  }

  if (IkeSaSession->InitPacket != NULL) {
    FreePool (IkeSaSession->InitPacket);
  }

  if (IkeSaSession->RespPacket != NULL) {
    FreePool (IkeSaSession->RespPacket);
  }

  FreePool (IkeSaSession);

  return ;
}

/**
  Increase the MessageID in IkeSaSession.

  @param[in] IkeSaSession Pointer to a specified IKEV2_SA_SESSION.

**/
VOID
Ikev2SaSessionIncreaseMessageId (
  IN IKEV2_SA_SESSION         *IkeSaSession
  )
{
  if (IkeSaSession->MessageId < 0xffffffff) {
    IkeSaSession->MessageId ++;
  } else {
    //
    // TODO: Trigger Rekey process.
    //
  }
}

/**
  Allocate memory for IKEV2 Child SA Session.
  
  @param[in]   UdpService     Pointer to IKE_UDP_SERVICE.
  @param[in]   IkeSaSession   Pointer to IKEV2_SA_SESSION related to this Child SA 
                              Session.

  @retval  Pointer of a new created IKEV2 Child SA Session or NULL.

**/
IKEV2_CHILD_SA_SESSION *
Ikev2ChildSaSessionAlloc (
  IN IKE_UDP_SERVICE          *UdpService,
  IN IKEV2_SA_SESSION         *IkeSaSession
  )
{
  EFI_STATUS                  Status;
  IKEV2_CHILD_SA_SESSION      *ChildSaSession;
  IKEV2_SESSION_COMMON        *ChildSaCommon;
  IKEV2_SESSION_COMMON        *SaCommon;

  ChildSaSession = AllocateZeroPool (sizeof (IKEV2_CHILD_SA_SESSION));
  if (ChildSaSession == NULL) {
    return NULL;
  }

  //
  // Initialize the fields of ChildSaSession and its SessionCommon.
  //
  ChildSaSession->Signature          = IKEV2_CHILD_SA_SESSION_SIGNATURE;
  ChildSaSession->IkeSaSession       = IkeSaSession;
  ChildSaSession->MessageId          = IkeSaSession->MessageId;
  ChildSaSession->LocalPeerSpi       = IkeGenerateSpi ();
  ChildSaCommon                      = &ChildSaSession->SessionCommon;
  ChildSaCommon->UdpService          = UdpService;
  ChildSaCommon->Private             = IkeSaSession->SessionCommon.Private;
  ChildSaCommon->IkeSessionType      = IkeSessionTypeChildSa;
  ChildSaCommon->IkeVer              = 2;
  ChildSaCommon->AfterEncodePayload  = Ikev2ChildSaAfterEncodePayload;
  ChildSaCommon->BeforeDecodePayload = Ikev2ChildSaBeforeDecodePayload;
  SaCommon = &ChildSaSession->IkeSaSession->SessionCommon;

  //
  // Create a resend notfiy event for retry.
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER | EVT_NOTIFY_SIGNAL,
                  TPL_CALLBACK,
                  Ikev2ResendNotify,
                  ChildSaCommon,
                  &ChildSaCommon->TimeoutEvent
                  );
  if (EFI_ERROR (Status)) {
    FreePool (ChildSaSession);
    return NULL;
  }

  CopyMem (&ChildSaCommon->LocalPeerIp, &SaCommon->LocalPeerIp, sizeof (EFI_IP_ADDRESS));
  CopyMem (&ChildSaCommon->RemotePeerIp, &SaCommon->RemotePeerIp, sizeof (EFI_IP_ADDRESS));

  return ChildSaSession;
}

/**
  Register a established IKEv2 Child SA into IkeSaSession->ChildSaEstablishSessionList. 
  If the there is IKEV2_CHILD_SA_SESSION with same remote peer IP, remove the old one 
  then register the new one.

  @param[in]  ChildSaSession  Pointer to IKEV2_CHILD_SA_SESSION to be registered.
  @param[in]  Private         Pointer to IPSEC_PRAVATE_DATA.

**/
VOID
Ikev2ChildSaSessionReg (
  IN IKEV2_CHILD_SA_SESSION    *ChildSaSession,
  IN IPSEC_PRIVATE_DATA        *Private
  )
{
  IKEV2_SESSION_COMMON         *SessionCommon;
  IKEV2_CHILD_SA_SESSION       *OldChildSaSession;
  IKEV2_SA_SESSION             *IkeSaSession;
  EFI_STATUS                   Status;
  UINT64                       Lifetime;

  //
  // Keep the IKE SA exclusive.
  //
  SessionCommon     = &ChildSaSession->SessionCommon;
  IkeSaSession      = ChildSaSession->IkeSaSession;
  OldChildSaSession = Ikev2ChildSaSessionRemove (
                        &IkeSaSession->ChildSaEstablishSessionList,
                        ChildSaSession->LocalPeerSpi,
                        IKEV2_ESTABLISHED_CHILDSA_LIST
                        );
  if (OldChildSaSession != NULL) {
    //
    // Free the old one.
    //
    Ikev2ChildSaSessionFree (OldChildSaSession);
  }

  //
  // Store the ready child SA into SAD.
  //
  Ikev2StoreSaData (ChildSaSession);

  //
  // Cleanup the fields of SessionCommon for processing.
  // 
  Ikev2SessionCommonRefresh (SessionCommon);
 
  //
  // Insert the ready child SA session into established list.
  //
  Ikev2ChildSaSessionInsert (&IkeSaSession->ChildSaEstablishSessionList, ChildSaSession);

  //
  // Create a Notify event for the IKE SA life time counting.
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER | EVT_NOTIFY_SIGNAL,
                  TPL_CALLBACK,
                  Ikev2LifetimeNotify,
                  SessionCommon,
                  &SessionCommon->TimeoutEvent
                  );
  if (EFI_ERROR(Status)){
    return ;
  }

  //
  // Start to count the lifetime of the IKE SA.
  //
  if (ChildSaSession->Spd->Data->ProcessingPolicy->SaLifetime.HardLifetime != 0){
    Lifetime = ChildSaSession->Spd->Data->ProcessingPolicy->SaLifetime.HardLifetime;
  } else {
    Lifetime = CHILD_SA_DEFAULT_LIFETIME;
  }

  Status = gBS->SetTimer (
                  SessionCommon->TimeoutEvent,
                  TimerRelative,
                  MultU64x32(Lifetime, 10000000) // ms->100ns
                  );
  if (EFI_ERROR(Status)){
    return ;
  }

  DEBUG ((
    DEBUG_INFO,
    "\n------ChildSa established and start to count down %d seconds lifetime\n",
    Lifetime
    ));

  return ;
}

/**
  Find the ChildSaSession by it's MessagId.

  @param[in] SaSessionList  Pointer to a ChildSaSession List.
  @param[in] Mid            The messageId used to search ChildSaSession.

  @return Pointer to IKEV2_CHILD_SA_SESSION or NULL.

**/
IKEV2_CHILD_SA_SESSION *
Ikev2ChildSaSessionLookupByMid (
  IN LIST_ENTRY           *SaSessionList,
  IN UINT32               Mid
  )
{
  LIST_ENTRY              *Entry;
  IKEV2_CHILD_SA_SESSION  *ChildSaSession;

  NET_LIST_FOR_EACH (Entry, SaSessionList) {
    ChildSaSession  = IKEV2_CHILD_SA_SESSION_BY_IKE_SA (Entry);

    if (ChildSaSession->MessageId == Mid) {
      return ChildSaSession;
    }
  }
  return NULL;
}

/**
  This function find the Child SA by the specified SPI.

  This functin find a ChildSA session by searching the ChildSaSessionlist of
  the input IKEV2_SA_SESSION by specified MessageID.
  
  @param[in]  SaSessionList      Pointer to List to be searched.
  @param[in]  Spi                Specified SPI.

  @return Pointer to IKEV2_CHILD_SA_SESSION or NULL.

**/
IKEV2_CHILD_SA_SESSION *
Ikev2ChildSaSessionLookupBySpi (
  IN LIST_ENTRY           *SaSessionList,
  IN UINT32               Spi
  )
{
  LIST_ENTRY              *Entry;
  IKEV2_CHILD_SA_SESSION  *ChildSaSession;

  NET_LIST_FOR_EACH (Entry, SaSessionList) {
    ChildSaSession  = IKEV2_CHILD_SA_SESSION_BY_IKE_SA (Entry);

    if (ChildSaSession->RemotePeerSpi == Spi || ChildSaSession->LocalPeerSpi == Spi) {
      return ChildSaSession;
    }
  }

  return NULL;
}

/**
  Insert a Child SA Session into the specified ChildSa list.

  @param[in]  SaSessionList   Pointer to list to be inserted in.
  @param[in]  ChildSaSession  Pointer to IKEV2_CHILD_SA_SESSION to be inserted.

**/
VOID
Ikev2ChildSaSessionInsert (
  IN LIST_ENTRY               *SaSessionList,
  IN IKEV2_CHILD_SA_SESSION   *ChildSaSession
  )
{
 InsertTailList (SaSessionList, &ChildSaSession->ByIkeSa);
}

/**
  Remove the IKEV2_CHILD_SA_SESSION from IkeSaSessionList.
  
  @param[in]  SaSessionList      The SA Session List to be iterated.
  @param[in]  Spi                Spi used to identified the IKEV2_CHILD_SA_SESSION.
  @param[in]  ListType           The type of the List to indicate whether it is a 
                                 Established. 

  @return The point to IKEV2_CHILD_SA_SESSION or NULL.
  
**/
IKEV2_CHILD_SA_SESSION *
Ikev2ChildSaSessionRemove (
  IN LIST_ENTRY           *SaSessionList,
  IN UINT32               Spi, 
  IN UINT8                ListType
  )
{
  LIST_ENTRY              *Entry;
  LIST_ENTRY              *NextEntry;
  IKEV2_CHILD_SA_SESSION  *ChildSaSession;

  NET_LIST_FOR_EACH_SAFE (Entry, NextEntry, SaSessionList) {
    
    if (ListType == IKEV2_ESTABLISHED_CHILDSA_LIST || ListType == IKEV2_ESTABLISHING_CHILDSA_LIST) {
      ChildSaSession = IKEV2_CHILD_SA_SESSION_BY_IKE_SA (Entry);
    } else if (ListType == IKEV2_DELET_CHILDSA_LIST) {
      ChildSaSession = IKEV2_CHILD_SA_SESSION_BY_DEL_SA (Entry);
    } else {
      return NULL;
    }

    if (ChildSaSession->RemotePeerSpi == Spi || ChildSaSession->LocalPeerSpi == Spi) {
      RemoveEntryList (Entry);
      return ChildSaSession;
    }
  }

  return NULL;
}

/**
  Mark a specified Child SA Session as on deleting.

  @param[in]  ChildSaSession   Pointer to IKEV2_CHILD_SA_SESSION.

  @retval     EFI_SUCCESS      Operation is successful.

**/
EFI_STATUS
Ikev2ChildSaSessionOnDeleting (
  IN IKEV2_CHILD_SA_SESSION   *ChildSaSession
  )
{
  return EFI_SUCCESS;
}

/**
  Free the memory located for the specified IKEV2_CHILD_SA_SESSION. 

  @param[in]  ChildSaSession  Pointer to IKEV2_CHILD_SA_SESSION.

**/
VOID
Ikev2ChildSaSessionFree (
  IN IKEV2_CHILD_SA_SESSION   *ChildSaSession
  )
{
  IKEV2_SESSION_COMMON  *SessionCommon;

  SessionCommon = &ChildSaSession->SessionCommon;
  if (ChildSaSession->SaData != NULL) {
    FreePool (ChildSaSession->SaData);
  }

  if (ChildSaSession->NiBlock != NULL) {
    FreePool (ChildSaSession->NiBlock);
  }

  if (ChildSaSession->NrBlock != NULL) {
    FreePool (ChildSaSession->NrBlock);
  }

  if (ChildSaSession->ChildKeymats.LocalPeerInfo.EspAlgoInfo.AuthKey != NULL) {
    FreePool (ChildSaSession->ChildKeymats.LocalPeerInfo.EspAlgoInfo.AuthKey);
  }

  if (ChildSaSession->ChildKeymats.LocalPeerInfo.EspAlgoInfo.EncKey != NULL) {
    FreePool (ChildSaSession->ChildKeymats.LocalPeerInfo.EspAlgoInfo.EncKey);
  }

  if (ChildSaSession->ChildKeymats.RemotePeerInfo.EspAlgoInfo.AuthKey != NULL) {
    FreePool (ChildSaSession->ChildKeymats.RemotePeerInfo.EspAlgoInfo.AuthKey);
  }

  if (ChildSaSession->ChildKeymats.RemotePeerInfo.EspAlgoInfo.EncKey != NULL) {
    FreePool (ChildSaSession->ChildKeymats.RemotePeerInfo.EspAlgoInfo.EncKey);
  }

  //
  // Delete DhBuffer
  //
  Ikev2DhBufferFree (ChildSaSession->DhBuffer);

  //
  // Delete SpdSelector
  //
  if (ChildSaSession->SpdSelector != NULL) {
    if (ChildSaSession->SpdSelector->LocalAddress != NULL) {
      FreePool (ChildSaSession->SpdSelector->LocalAddress);
    }
    if (ChildSaSession->SpdSelector->RemoteAddress != NULL) {
      FreePool (ChildSaSession->SpdSelector->RemoteAddress);
    }
    FreePool (ChildSaSession->SpdSelector);
  }
  Ikev2SaSessionCommonFree (SessionCommon);
  FreePool (ChildSaSession);

  return ;
}

/**
  Delete the specified established Child SA.

  This function delete the Child SA directly and don't send the Information Packet to
  remote peer.

  @param[in]  IkeSaSession   Pointer to a IKE SA Session used to be searched for.
  @param[in]  Spi            SPI used to find the Child SA.

  @retval     EFI_NOT_FOUND  Pointer of IKE SA Session is NULL.
  @retval     EFI_NOT_FOUND  There is no specified Child SA related with the input
                             SPI under this IKE SA Session.
  @retval     EFI_SUCCESS    Delete the Child SA successfully.

**/
EFI_STATUS
Ikev2ChildSaSilentDelete (
  IN IKEV2_SA_SESSION       *IkeSaSession,
  IN UINT32                 Spi
  )
{
  EFI_STATUS                Status;
  EFI_IPSEC_CONFIG_SELECTOR *Selector;
  UINTN                     SelectorSize;
  BOOLEAN                   IsLocalFound;
  BOOLEAN                   IsRemoteFound;
  UINT32                    LocalSpi;
  UINT32                    RemoteSpi;
  IKEV2_CHILD_SA_SESSION    *ChildSession;
  EFI_IPSEC_CONFIG_SELECTOR *LocalSelector;
  EFI_IPSEC_CONFIG_SELECTOR *RemoteSelector;
  IKE_UDP_SERVICE           *UdpService;
  IPSEC_PRIVATE_DATA        *Private;

  if (IkeSaSession == NULL) {
    return EFI_NOT_FOUND;
  }

  IsLocalFound    = FALSE;
  IsRemoteFound   = FALSE;
  ChildSession    = NULL;
  LocalSelector   = NULL;
  RemoteSelector  = NULL;
  UdpService      = IkeSaSession->SessionCommon.UdpService;

  Private = IkeSaSession->SessionCommon.Private;

  //
  // Remove the Established SA from ChildSaEstablishlist.
  //
  ChildSession = Ikev2ChildSaSessionRemove(
                   &(IkeSaSession->ChildSaEstablishSessionList),
                   Spi, 
                   IKEV2_ESTABLISHED_CHILDSA_LIST
                   );
  if (ChildSession == NULL) {
    return EFI_NOT_FOUND;
  }

  LocalSpi  = ChildSession->LocalPeerSpi;
  RemoteSpi = ChildSession->RemotePeerSpi;
  
  SelectorSize  = sizeof (EFI_IPSEC_CONFIG_SELECTOR);
  Selector      = AllocateZeroPool (SelectorSize);
  ASSERT (Selector != NULL);

  

  while (1) {
    Status = EfiIpSecConfigGetNextSelector (
               &Private->IpSecConfig,
               IPsecConfigDataTypeSad,
               &SelectorSize,
               Selector
               );
    if (Status == EFI_BUFFER_TOO_SMALL) {
      FreePool (Selector);

      Selector = AllocateZeroPool (SelectorSize);
      ASSERT (Selector != NULL);
      Status   = EfiIpSecConfigGetNextSelector (
                   &Private->IpSecConfig,
                   IPsecConfigDataTypeSad,
                   &SelectorSize,
                   Selector
                   );
    }

    if (EFI_ERROR (Status)) {
      break;
    }

    if (Selector->SaId.Spi == RemoteSpi) {
      //
      // SPI is unique. There is only one SAD whose SPI is
      // same with RemoteSpi.
      //
      IsRemoteFound   = TRUE;
      RemoteSelector  = AllocateZeroPool (SelectorSize);
      ASSERT (RemoteSelector != NULL);
      CopyMem (RemoteSelector, Selector, SelectorSize);
    }

    if (Selector->SaId.Spi == LocalSpi) {
      //
      // SPI is unique. There is only one SAD whose SPI is
      // same with LocalSpi.
      //
      IsLocalFound  = TRUE;
      LocalSelector = AllocateZeroPool (SelectorSize);
      ASSERT (LocalSelector != NULL);
      CopyMem (LocalSelector, Selector, SelectorSize);
    }
  }
  //
  // Delete SA from the Variable.
  //
  if (IsLocalFound) {
    Status = EfiIpSecConfigSetData (
               &Private->IpSecConfig,
               IPsecConfigDataTypeSad,
               LocalSelector,
               NULL,
               NULL
               );
  }

  if (IsRemoteFound) {
    Status = EfiIpSecConfigSetData (
               &Private->IpSecConfig,
               IPsecConfigDataTypeSad,
               RemoteSelector,
               NULL,
               NULL
               );

  }

  DEBUG (
    (DEBUG_INFO,
    "\n------IKEV2 deleted ChildSa(local spi, remote spi):(0x%x, 0x%x)------\n",
    LocalSpi,
    RemoteSpi)
    );
  Ikev2ChildSaSessionFree (ChildSession);

  if (RemoteSelector != NULL) {
    FreePool (RemoteSelector);
  }

  if (LocalSelector != NULL) {
    FreePool (LocalSelector);
  }

  if (Selector != NULL) {
    FreePool (Selector);
  }

  return Status;
}

/**
  Free the specified DhBuffer.

  @param[in] DhBuffer   Pointer to IKEV2_DH_BUFFER to be freed.
  
**/
VOID
Ikev2DhBufferFree (
  IKEV2_DH_BUFFER *DhBuffer
) 
{
  if (DhBuffer != NULL) {
    if (DhBuffer->GxBuffer != NULL) {
      FreePool (DhBuffer->GxBuffer);
    }
    if (DhBuffer->GyBuffer != NULL) {
      FreePool (DhBuffer->GyBuffer);
    }
    if (DhBuffer->GxyBuffer != NULL) {
      FreePool (DhBuffer->GxyBuffer);
    }
    if (DhBuffer->DhContext != NULL) {
      IpSecCryptoIoFreeDh (&DhBuffer->DhContext);
    }
    FreePool (DhBuffer);
  }
}

/**
  This function is to parse a request IKE packet and return its request type.
  The request type is one of IKE CHILD SA creation, IKE SA rekeying and 
  IKE CHILD SA rekeying.

  @param[in] IkePacket  IKE packet to be prased.

  return the type of the IKE packet.

**/
IKEV2_CREATE_CHILD_REQUEST_TYPE
Ikev2ChildExchangeRequestType(
  IN IKE_PACKET               *IkePacket
  )
{
  BOOLEAN       Flag;
  LIST_ENTRY    *Entry;
  IKE_PAYLOAD   *IkePayload;

  Flag            = FALSE;

  NET_LIST_FOR_EACH (Entry, &(IkePacket)->PayloadList) {
    IkePayload  = IKE_PAYLOAD_BY_PACKET (Entry);
    if (IkePayload->PayloadType == IKEV2_PAYLOAD_TYPE_TS_INIT) {
      //
      // Packet with Ts Payload means it is for either CHILD_SA_CREATE or CHILD_SA_REKEY.
      //
      Flag = TRUE;
    }
    if (IkePayload->PayloadType == IKEV2_PAYLOAD_TYPE_NOTIFY) { 
      if (((IKEV2_NOTIFY*)IkePayload)->MessageType == IKEV2_NOTIFICATION_REKEY_SA) {
        //
        // If notify payload with REKEY_SA message type, the IkePacket is for 
        // rekeying Child SA.
        //
        return IkeRequestTypeRekeyChildSa;
      }
    }
  };

  if (!Flag){
    //
    // The Create Child Exchange is for IKE SA rekeying.
    //
    return IkeRequestTypeRekeyIkeSa;
  } else {
    //
    // If the Notify payloaad with transport mode message type, the IkePacket is 
    // for create Child SA.
    //
    return IkeRequestTypeCreateChildSa;
  }
}

/**
  Associate a SPD selector to the Child SA Session.

  This function is called when the Child SA is not the first child SA of its 
  IKE SA. It associate a SPD to this Child SA.

  @param[in, out]  ChildSaSession     Pointer to the Child SA Session to be associated to 
                                      a SPD selector.

  @retval EFI_SUCCESS        Associate one SPD selector to this Child SA Session successfully.
  @retval EFI_NOT_FOUND      Can't find the related SPD selector.

**/
EFI_STATUS
Ikev2ChildSaAssociateSpdEntry (
  IN OUT IKEV2_CHILD_SA_SESSION *ChildSaSession
  )
{
  IpSecVisitConfigData (IPsecConfigDataTypeSpd, Ikev2MatchSpdEntry, ChildSaSession);
  if (ChildSaSession->Spd != NULL) {
    return EFI_SUCCESS;
  } else {
    return EFI_NOT_FOUND;
  }
}


/**
  This function finds the SPI from Create Child SA Exchange Packet.
 
  @param[in] IkePacket       Pointer to IKE_PACKET to be searched.

  @retval SPI number or 0 if it is not supported.

**/
UINT32
Ikev2ChildExchangeRekeySpi (
  IN IKE_PACKET               *IkePacket
  )
{
  //
  // Not support yet.
  // 
  return 0;
}

/**
  Validate the IKE header of received IKE packet.

  @param[in]   IkeSaSession  Pointer to IKEV2_SA_SESSION related to this IKE packet.
  @param[in]   IkeHdr        Pointer to IKE header of received IKE packet.

  @retval TRUE   If the IKE header is valid.
  @retval FALSE  If the IKE header is invalid.

**/
BOOLEAN
Ikev2ValidateHeader (
  IN IKEV2_SA_SESSION         *IkeSaSession,
  IN IKE_HEADER               *IkeHdr
  )
{

  IKEV2_SESSION_STATE State;

  State = IkeSaSession->SessionCommon.State;
  if (State == IkeStateInit) {
    //
    // For the IKE Initial Exchange, the MessagId should be zero.
    //
    if (IkeHdr->MessageId != 0) {
      return FALSE;
    }
  } else {
    if (State == IkeStateAuth) {
      if (IkeHdr->MessageId != 1) {
        return FALSE;
      }
    }
    if (IkeHdr->InitiatorCookie != IkeSaSession->InitiatorCookie ||
        IkeHdr->ResponderCookie != IkeSaSession->ResponderCookie
        ) {
      //
      // TODO: send notification INVALID-COOKIE
      //
      return FALSE;
    }
  }

  //
  // Information Exchagne and Create Child Exchange can be started from each part.
  //
  if (IkeHdr->ExchangeType != IKEV2_EXCHANGE_TYPE_INFO && 
      IkeHdr->ExchangeType != IKEV2_EXCHANGE_TYPE_CREATE_CHILD
      ) {
    if (IkeSaSession->SessionCommon.IsInitiator) {
      if (IkeHdr->InitiatorCookie != IkeSaSession->InitiatorCookie) {
        //
        // TODO: send notification INVALID-COOKIE
        //
        return FALSE;
      }
      if (IkeHdr->Flags != IKE_HEADER_FLAGS_RESPOND) {
        return FALSE;
      }
    } else {
      if (IkeHdr->Flags != IKE_HEADER_FLAGS_INIT) {
        return FALSE;
      }
    }
  }

  return TRUE;
}

/**
  Create and intialize IKEV2_SA_DATA for speicifed IKEV2_SESSION_COMMON.

  This function will be only called by the initiator. The responder's IKEV2_SA_DATA
  will be generated during parsed the initiator packet.

  @param[in]  SessionCommon  Pointer to IKEV2_SESSION_COMMON related to.

  @retval a Pointer to a new IKEV2_SA_DATA or NULL.

**/
IKEV2_SA_DATA *
Ikev2InitializeSaData (
  IN IKEV2_SESSION_COMMON     *SessionCommon
  )
{
  IKEV2_CHILD_SA_SESSION      *ChildSaSession;
  IKEV2_SA_DATA               *SaData;
  IKEV2_PROPOSAL_DATA         *ProposalData;
  IKEV2_TRANSFORM_DATA        *TransformData;
  IKE_SA_ATTRIBUTE            *Attribute;

  ASSERT (SessionCommon != NULL);
  //
  // TODO: Remove the hard code of the support Alogrithm. Those data should be
  // get from the SPD/PAD data.
  //
  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    SaData = AllocateZeroPool (
               sizeof (IKEV2_SA_DATA) +
               sizeof (IKEV2_PROPOSAL_DATA) * 2 +
               sizeof (IKEV2_TRANSFORM_DATA) * 4 * 2
               );
  } else {
    SaData = AllocateZeroPool (
               sizeof (IKEV2_SA_DATA) +
               sizeof (IKEV2_PROPOSAL_DATA) * 2 +
               sizeof (IKEV2_TRANSFORM_DATA) * 3 * 2
               );
  }
  if (SaData == NULL) {
    return NULL;
  }

  //
  // First proposal payload: 3DES + SHA1 + DH
  //
  SaData->NumProposals          = 2;
  ProposalData                  = (IKEV2_PROPOSAL_DATA *) (SaData + 1);
  ProposalData->ProposalIndex   = 1;

  //
  // If SA data for IKE_SA_INIT exchage, contains 4 transforms. If SA data for 
  // IKE_AUTH exchange contains 3 transforms.
  //
  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    ProposalData->NumTransforms   = 4;
  } else {
    ProposalData->NumTransforms   = 3;
  }


  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    ProposalData->ProtocolId    = IPSEC_PROTO_ISAKMP;
  } else {
    ChildSaSession              = IKEV2_CHILD_SA_SESSION_FROM_COMMON (SessionCommon);
    ProposalData->ProtocolId    = IPSEC_PROTO_IPSEC_ESP;
    ProposalData->Spi           = AllocateZeroPool (sizeof (ChildSaSession->LocalPeerSpi));
    ASSERT (ProposalData->Spi != NULL);
    CopyMem (
      ProposalData->Spi,
      &ChildSaSession->LocalPeerSpi,
      sizeof(ChildSaSession->LocalPeerSpi)
    );
  }

  //
  // Set transform attribute for Encryption Algorithm - 3DES
  //
  TransformData                 = (IKEV2_TRANSFORM_DATA *) (ProposalData + 1);
  TransformData->TransformIndex = 0;
  TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_ENCR;
  TransformData->TransformId    = IKEV2_TRANSFORM_ID_ENCR_3DES;

  //
  // Set transform attribute for Integrity Algorithm - SHA1_96
  //
  TransformData                 = (IKEV2_TRANSFORM_DATA *) (TransformData + 1);
  TransformData->TransformIndex = 1;
  TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_INTEG;
  TransformData->TransformId    = IKEV2_TRANSFORM_ID_AUTH_HMAC_SHA1_96;

  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    //
    // Set transform attribute for Pseduo-Random Function - HAMC_SHA1
    //
    TransformData                 = (IKEV2_TRANSFORM_DATA *) (TransformData + 1);
    TransformData->TransformIndex = 2;
    TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_PRF;
    TransformData->TransformId    = IKEV2_TRANSFORM_ID_PRF_HMAC_SHA1;
  }

  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    //
    // Set transform attribute for DH Group - DH 1024
    //
    TransformData                 = (IKEV2_TRANSFORM_DATA *) (TransformData + 1);
    TransformData->TransformIndex = 3;
    TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_DH;
    TransformData->TransformId    = IKEV2_TRANSFORM_ID_DH_1024MODP;
  } else {
    //
    // Transform type for Extended Sequence Numbers. Currently not support Extended
    // Sequence Number.
    //
    TransformData                 = (IKEV2_TRANSFORM_DATA *) (TransformData + 1);
    TransformData->TransformIndex = 2;
    TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_ESN;
    TransformData->TransformId    = 0;
  }

  //
  // Second proposal payload: 3DES + SHA1 + DH
  //
  ProposalData                  = (IKEV2_PROPOSAL_DATA *) (TransformData + 1);
  ProposalData->ProposalIndex   = 2;

  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    ProposalData->ProtocolId      = IPSEC_PROTO_ISAKMP;
    ProposalData->NumTransforms   = 4;
  } else {

    ChildSaSession              = IKEV2_CHILD_SA_SESSION_FROM_COMMON (SessionCommon);
    ProposalData->ProtocolId    = IPSEC_PROTO_IPSEC_ESP;
    ProposalData->NumTransforms = 3;
    ProposalData->Spi           = AllocateZeroPool (sizeof (ChildSaSession->LocalPeerSpi));
    ASSERT (ProposalData->Spi != NULL);
    CopyMem (
      ProposalData->Spi,
      &ChildSaSession->LocalPeerSpi,
      sizeof(ChildSaSession->LocalPeerSpi)
    );
  }

  //
  // Set transform attribute for Encryption Algorithm - AES-CBC
  //
  TransformData                 = (IKEV2_TRANSFORM_DATA *) (ProposalData + 1);
  TransformData->TransformIndex = 0;
  TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_ENCR;
  TransformData->TransformId    = IKEV2_TRANSFORM_ID_ENCR_AES_CBC;
  Attribute                     = &TransformData->Attribute;
  Attribute->AttrType           = IKEV2_ATTRIBUTE_TYPE_KEYLEN;
  Attribute->Attr.AttrLength    = (UINT16) (8 * IpSecGetEncryptKeyLength (IKEV2_TRANSFORM_ID_ENCR_AES_CBC));

  //
  // Set transform attribute for Integrity Algorithm - SHA1_96
  //
  TransformData                 = (IKEV2_TRANSFORM_DATA *) (TransformData + 1);
  TransformData->TransformIndex = 1;
  TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_INTEG;
  TransformData->TransformId    = IKEV2_TRANSFORM_ID_AUTH_HMAC_SHA1_96;

  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    //
    // Set transform attribute for Pseduo-Random Function - HAMC_SHA1
    //
    TransformData                 = (IKEV2_TRANSFORM_DATA *) (TransformData + 1);
    TransformData->TransformIndex = 2;
    TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_PRF;
    TransformData->TransformId    = IKEV2_TRANSFORM_ID_PRF_HMAC_SHA1;
  }

  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    //
    // Set transform attrbiute for DH Group - DH-1024
    //
    TransformData                 = (IKEV2_TRANSFORM_DATA *) (TransformData + 1);
    TransformData->TransformIndex = 3;
    TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_DH;
    TransformData->TransformId    = IKEV2_TRANSFORM_ID_DH_1024MODP;
  } else {
    //
    // Transform type for Extended Sequence Numbers. Currently not support Extended
    // Sequence Number.
    //
    TransformData                 = (IKEV2_TRANSFORM_DATA *) (TransformData + 1);
    TransformData->TransformIndex = 2;
    TransformData->TransformType  = IKEV2_TRANSFORM_TYPE_ESN;
    TransformData->TransformId    = 0;
  }

  return SaData;
}

/**
  Store the SA into SAD.

  @param[in]  ChildSaSession  Pointer to IKEV2_CHILD_SA_SESSION.

**/
VOID
Ikev2StoreSaData (
  IN IKEV2_CHILD_SA_SESSION   *ChildSaSession
  )
{
  EFI_STATUS                  Status;
  EFI_IPSEC_SA_ID             SaId;
  EFI_IPSEC_SA_DATA2           SaData;
  IKEV2_SESSION_COMMON        *SessionCommon;
  IPSEC_PRIVATE_DATA          *Private;
  UINT32                      TempAddressCount;
  EFI_IP_ADDRESS_INFO         *TempAddressInfo;

  SessionCommon             = &ChildSaSession->SessionCommon;
  Private                   = SessionCommon->Private;

  ZeroMem (&SaId, sizeof (EFI_IPSEC_SA_ID));
  ZeroMem (&SaData, sizeof (EFI_IPSEC_SA_DATA2));

  //
  // Create a SpdSelector. In this implementation, one SPD represents
  // 2 direction traffic, so in here, there needs to reverse the local address 
  // and remote address for Remote Peer's SA, then reverse again for the locate
  // SA. 
  //
  TempAddressCount = ChildSaSession->SpdSelector->LocalAddressCount;
  TempAddressInfo  = ChildSaSession->SpdSelector->LocalAddress;

  ChildSaSession->SpdSelector->LocalAddressCount = ChildSaSession->SpdSelector->RemoteAddressCount;
  ChildSaSession->SpdSelector->LocalAddress      = ChildSaSession->SpdSelector->RemoteAddress;

  ChildSaSession->SpdSelector->RemoteAddress     = TempAddressInfo;
  ChildSaSession->SpdSelector->RemoteAddressCount= TempAddressCount;

  //
  // Set the SaId and SaData.
  //
  SaId.Spi                 = ChildSaSession->LocalPeerSpi;
  SaId.Proto               = EfiIPsecESP;
  SaData.AntiReplayWindows = 16;
  SaData.SNCount           = 0;
  SaData.Mode              = ChildSaSession->Spd->Data->ProcessingPolicy->Mode;

  //
  // If it is tunnel mode, should add the TunnelDest and TunnelSource for SaData.
  //
  if (SaData.Mode == EfiIPsecTunnel) {
    CopyMem (
      &SaData.TunnelSourceAddress, 
      &ChildSaSession->Spd->Data->ProcessingPolicy->TunnelOption->RemoteTunnelAddress,
      sizeof (EFI_IP_ADDRESS)
      );
    CopyMem (
      &SaData.TunnelDestinationAddress,
      &ChildSaSession->Spd->Data->ProcessingPolicy->TunnelOption->LocalTunnelAddress,
      sizeof (EFI_IP_ADDRESS)
      );
  }

  CopyMem (&SaId.DestAddress, &ChildSaSession->SessionCommon.LocalPeerIp, sizeof (EFI_IP_ADDRESS));
  CopyMem (&SaData.AlgoInfo, &ChildSaSession->ChildKeymats.LocalPeerInfo, sizeof (EFI_IPSEC_ALGO_INFO));
  SaData.SpdSelector = ChildSaSession->SpdSelector;

  //
  // Store the remote SA into SAD.
  //
  Status = EfiIpSecConfigSetData (
             &Private->IpSecConfig,
             IPsecConfigDataTypeSad,
             (EFI_IPSEC_CONFIG_SELECTOR *) &SaId,
             &SaData,
             NULL
             );
  ASSERT_EFI_ERROR (Status);

  //
  // Store the local SA into SAD.
  //  
  ChildSaSession->SpdSelector->RemoteAddressCount = ChildSaSession->SpdSelector->LocalAddressCount;
  ChildSaSession->SpdSelector->RemoteAddress      = ChildSaSession->SpdSelector->LocalAddress;

  ChildSaSession->SpdSelector->LocalAddress       = TempAddressInfo;
  ChildSaSession->SpdSelector->LocalAddressCount  = TempAddressCount;
  
  SaId.Spi = ChildSaSession->RemotePeerSpi;

  CopyMem (&SaId.DestAddress, &ChildSaSession->SessionCommon.RemotePeerIp, sizeof (EFI_IP_ADDRESS));
  CopyMem (&SaData.AlgoInfo, &ChildSaSession->ChildKeymats.RemotePeerInfo, sizeof (EFI_IPSEC_ALGO_INFO));
  SaData.SpdSelector = ChildSaSession->SpdSelector;

  //
  // If it is tunnel mode, should add the TunnelDest and TunnelSource for SaData.
  //
  if (SaData.Mode == EfiIPsecTunnel) {
    CopyMem (
      &SaData.TunnelSourceAddress,
      &ChildSaSession->Spd->Data->ProcessingPolicy->TunnelOption->LocalTunnelAddress,
      sizeof (EFI_IP_ADDRESS)
      );
    CopyMem (
      &SaData.TunnelDestinationAddress,
      &ChildSaSession->Spd->Data->ProcessingPolicy->TunnelOption->RemoteTunnelAddress,
      sizeof (EFI_IP_ADDRESS)
      );
  }

  Status = EfiIpSecConfigSetData (
             &Private->IpSecConfig,
             IPsecConfigDataTypeSad,
             (EFI_IPSEC_CONFIG_SELECTOR *) &SaId,
             &SaData,
             NULL
             );

  ASSERT_EFI_ERROR (Status);
}

/**
  Call back function of the IKE life time is over.

  This function will mark the related IKE SA Session as deleting and trigger a 
  Information negotiation.

  @param[in]    Event     The signaled Event.
  @param[in]    Context   Pointer to data passed by caller.
  
**/
VOID
EFIAPI
Ikev2LifetimeNotify (
  IN EFI_EVENT                Event,
  IN VOID                     *Context
  )
{
  IKEV2_SA_SESSION            *IkeSaSession;
  IKEV2_CHILD_SA_SESSION      *ChildSaSession;
  IKEV2_SESSION_COMMON        *SessionCommon;

  ASSERT (Context != NULL);
  SessionCommon = (IKEV2_SESSION_COMMON *) Context;

  if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
    IkeSaSession = IKEV2_SA_SESSION_FROM_COMMON (SessionCommon);
    DEBUG ((
      DEBUG_INFO,
      "\n---IkeSa Lifetime is out(cookie_i, cookie_r):(0x%lx, 0x%lx)---\n",
      IkeSaSession->InitiatorCookie,
      IkeSaSession->ResponderCookie
      ));

    //
    // Change the  IKE SA Session's State to IKE_STATE_SA_DELETING.
    //
    IKEV2_DUMP_STATE (IkeSaSession->SessionCommon.State, IkeStateSaDeleting);
    IkeSaSession->SessionCommon.State = IkeStateSaDeleting;

  } else {
    ChildSaSession = IKEV2_CHILD_SA_SESSION_FROM_COMMON (SessionCommon);
    IkeSaSession   = ChildSaSession->IkeSaSession;

    //
    // Link the timeout child SA to the DeleteSaList.
    //
    InsertTailList (&IkeSaSession->DeleteSaList, &ChildSaSession->ByDelete);

    //
    // Change the Child SA Session's State to IKE_STATE_SA_DELETING.
    //    
    DEBUG ((
      DEBUG_INFO,
      "\n------ChildSa Lifetime is out(SPI):(0x%x)------\n",
      ChildSaSession->LocalPeerSpi
      ));
  }

  //
  // TODO: Send the delete info packet or delete silently
  //
  mIkev2Exchange.NegotiateInfo ((UINT8 *) IkeSaSession, NULL);
}

/**
  This function will be called if the TimeOut Event is signaled.

  @param[in]  Event      The signaled Event.
  @param[in]  Context    The data passed by caller.

**/
VOID
EFIAPI
Ikev2ResendNotify (
  IN EFI_EVENT                 Event,
  IN VOID                      *Context
  )
{
  IPSEC_PRIVATE_DATA           *Private;
  IKEV2_SA_SESSION             *IkeSaSession;
  IKEV2_CHILD_SA_SESSION       *ChildSaSession;
  IKEV2_SESSION_COMMON         *SessionCommon;
  LIST_ENTRY                   *ChildSaEntry;
  UINT8                        Value;
  EFI_STATUS                   Status;

  ASSERT (Context != NULL); 
  IkeSaSession   = NULL;
  ChildSaSession = NULL;
  SessionCommon  = (IKEV2_SESSION_COMMON *) Context;
  Private        = SessionCommon->Private;

  //
  // Remove the SA session from the processing list if exceed the max retry.
  //
  if (SessionCommon->RetryCount > IKE_MAX_RETRY) {
    if (SessionCommon->IkeSessionType == IkeSessionTypeIkeSa) {
      IkeSaSession = IKEV2_SA_SESSION_FROM_COMMON (SessionCommon);
      if (IkeSaSession->SessionCommon.State == IkeStateSaDeleting) {

        //
        // If the IkeSaSession is initiator, delete all its Child SAs before removing IKE SA.
        // If the IkesaSession is responder, all ChildSa has been remove in Ikev2HandleInfo();
        //
        for (ChildSaEntry = IkeSaSession->ChildSaEstablishSessionList.ForwardLink;
             ChildSaEntry != &IkeSaSession->ChildSaEstablishSessionList;
        ) {
          ChildSaSession = IKEV2_CHILD_SA_SESSION_BY_IKE_SA (ChildSaEntry);
          //
          // Move to next ChildSa Entry.
          //
          ChildSaEntry = ChildSaEntry->ForwardLink;
          //
          // Delete LocalSpi & RemoteSpi and remove the ChildSaSession from the
          // EstablishedChildSaList.
          //
          Ikev2ChildSaSilentDelete (IkeSaSession, ChildSaSession->LocalPeerSpi);
        }

        //
        // If the IKE SA Delete Payload wasn't sent out successfully, Delete it from the EstablishedList.
        //
        Ikev2SaSessionRemove (&Private->Ikev2EstablishedList, &SessionCommon->RemotePeerIp);

        if (Private != NULL && Private->IsIPsecDisabling) {
            //
            // After all IKE SAs were deleted, set the IPSEC_STATUS_DISABLED value in
            // IPsec status variable.
            //
            if (IsListEmpty (&Private->Ikev1EstablishedList) && IsListEmpty (&Private->Ikev2EstablishedList)) {
              Value = IPSEC_STATUS_DISABLED;
              Status = gRT->SetVariable (
                              IPSECCONFIG_STATUS_NAME,
                              &gEfiIpSecConfigProtocolGuid,
                              EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
                              sizeof (Value),
                              &Value
                              );
              if (!EFI_ERROR (Status)) {
                //
                // Set the Disabled Flag in Private data.
                //
                Private->IpSec.DisabledFlag = TRUE;
                Private->IsIPsecDisabling   = FALSE;
              }
            }
          }
      } else {
        Ikev2SaSessionRemove (&Private->Ikev2SessionList, &SessionCommon->RemotePeerIp);
      }
      Ikev2SaSessionFree (IkeSaSession);

    } else {

      //
      // If the packet sent by Child SA.
      //
      ChildSaSession = IKEV2_CHILD_SA_SESSION_FROM_COMMON (SessionCommon);
      IkeSaSession   = ChildSaSession->IkeSaSession;
      if (ChildSaSession->SessionCommon.State == IkeStateSaDeleting) {

        //
        // Established Child SA should be remove from the SAD entry and 
        // DeleteList. The function of Ikev2DeleteChildSaSilent() will remove 
        // the childSA from the IkeSaSession->ChildSaEstablishedList. So there 
        // is no need to remove it here.
        //
        Ikev2ChildSaSilentDelete (IkeSaSession, ChildSaSession->LocalPeerSpi);
        Ikev2ChildSaSessionRemove (
          &IkeSaSession->DeleteSaList,
          ChildSaSession->LocalPeerSpi,
          IKEV2_DELET_CHILDSA_LIST
          );
      } else {
        Ikev2ChildSaSessionRemove (
          &IkeSaSession->ChildSaSessionList,
          ChildSaSession->LocalPeerSpi,
          IKEV2_ESTABLISHING_CHILDSA_LIST
          );
      }

      Ikev2ChildSaSessionFree (ChildSaSession);
    }
    return ;
  }

  //
  // Increase the retry count.
  //
  SessionCommon->RetryCount++;
  DEBUG ((DEBUG_INFO, ">>>Resending the last packet ...\n"));

  //
  // Resend the last packet.
  //
  Ikev2SendIkePacket (
    SessionCommon->UdpService,
    (UINT8*)SessionCommon,
    SessionCommon->LastSentPacket,
    0
    );
}

/**
  Copy ChildSaSession->Spd->Selector to ChildSaSession->SpdSelector.

  ChildSaSession->SpdSelector stores the real Spdselector for its SA. Sometime,
  the SpdSelector in ChildSaSession is more accurated or the scope is smaller 
  than the one in ChildSaSession->Spd, especially for the tunnel mode.
    
  @param[in, out]  ChildSaSession  Pointer to IKEV2_CHILD_SA_SESSION related to.
  
**/
VOID
Ikev2ChildSaSessionSpdSelectorCreate (
  IN OUT IKEV2_CHILD_SA_SESSION *ChildSaSession
  ) 
{
  if (ChildSaSession->Spd != NULL && ChildSaSession->Spd->Selector != NULL) {
    if (ChildSaSession->SpdSelector == NULL) {
      ChildSaSession->SpdSelector = AllocateZeroPool (sizeof (EFI_IPSEC_SPD_SELECTOR));
      ASSERT (ChildSaSession->SpdSelector != NULL);
    }
    CopyMem (
      ChildSaSession->SpdSelector, 
      ChildSaSession->Spd->Selector, 
      sizeof (EFI_IPSEC_SPD_SELECTOR)
      );
    ChildSaSession->SpdSelector->RemoteAddress = AllocateCopyPool (
                                                   ChildSaSession->Spd->Selector->RemoteAddressCount * 
                                                   sizeof (EFI_IP_ADDRESS_INFO), 
                                                   ChildSaSession->Spd->Selector->RemoteAddress
                                                   );
    ChildSaSession->SpdSelector->LocalAddress = AllocateCopyPool (
                                                  ChildSaSession->Spd->Selector->LocalAddressCount * 
                                                  sizeof (EFI_IP_ADDRESS_INFO), 
                                                  ChildSaSession->Spd->Selector->LocalAddress
                                                  );

    ASSERT (ChildSaSession->SpdSelector->LocalAddress != NULL);
    ASSERT (ChildSaSession->SpdSelector->RemoteAddress != NULL);

    ChildSaSession->SpdSelector->RemoteAddressCount = ChildSaSession->Spd->Selector->RemoteAddressCount;
    ChildSaSession->SpdSelector->LocalAddressCount = ChildSaSession->Spd->Selector->LocalAddressCount; 
  }
}

/**
  Generate a ChildSa Session and insert it into related IkeSaSession.

  @param[in]  IkeSaSession    Pointer to related IKEV2_SA_SESSION.
  @param[in]  UdpService      Pointer to related IKE_UDP_SERVICE.

  @return pointer of IKEV2_CHILD_SA_SESSION.

**/
IKEV2_CHILD_SA_SESSION *
Ikev2ChildSaSessionCreate (
  IN IKEV2_SA_SESSION   *IkeSaSession,
  IN IKE_UDP_SERVICE     *UdpService
  )
{
  IKEV2_CHILD_SA_SESSION    *ChildSaSession;
  IKEV2_SESSION_COMMON      *ChildSaCommon;

  //
  // Create a new ChildSaSession.Insert it into processing list and initiate the common parameters.
  //
  ChildSaSession = Ikev2ChildSaSessionAlloc (UdpService, IkeSaSession);
  ASSERT (ChildSaSession != NULL);

  //
  // Set the specific parameters.
  // 
  ChildSaSession->Spd        = IkeSaSession->Spd;
  ChildSaCommon              = &ChildSaSession->SessionCommon;
  ChildSaCommon->IsInitiator = IkeSaSession->SessionCommon.IsInitiator;
  if (IkeSaSession->SessionCommon.State == IkeStateAuth) {
    ChildSaCommon->State     = IkeStateAuth;
    IKEV2_DUMP_STATE (ChildSaCommon->State, IkeStateAuth);
  } else {
    ChildSaCommon->State     = IkeStateCreateChild;
    IKEV2_DUMP_STATE (ChildSaCommon->State, IkeStateCreateChild);
  }

  //
  // If SPD->Selector is not NULL, copy it to the ChildSaSession->SpdSelector.
  // The ChildSaSession->SpdSelector might be changed after the traffic selector
  // negoniation and it will be copied into the SAData after ChildSA established.
  //
  Ikev2ChildSaSessionSpdSelectorCreate (ChildSaSession);

  //
  // Copy first NiBlock and NrBlock to ChildSa Session
  //
  ChildSaSession->NiBlock   = AllocateZeroPool (IkeSaSession->NiBlkSize);
  ASSERT (ChildSaSession->NiBlock != NULL);
  ChildSaSession->NiBlkSize = IkeSaSession->NiBlkSize;
  CopyMem (ChildSaSession->NiBlock, IkeSaSession->NiBlock, IkeSaSession->NiBlkSize);

  ChildSaSession->NrBlock   = AllocateZeroPool (IkeSaSession->NrBlkSize);
  ASSERT (ChildSaSession->NrBlock != NULL);
  ChildSaSession->NrBlkSize = IkeSaSession->NrBlkSize;
  CopyMem (ChildSaSession->NrBlock, IkeSaSession->NrBlock, IkeSaSession->NrBlkSize);

  //
  //  Only if the Create Child SA is called for the IKE_INIT Exchange and 
  //  IkeSaSession is initiator (Only Initiator's SPD is not NULL), Set the 
  //  Traffic Selectors related information here.
  //
  if (IkeSaSession->SessionCommon.State == IkeStateAuth && IkeSaSession->Spd != NULL) {
    ChildSaSession->ProtoId = IkeSaSession->Spd->Selector->NextLayerProtocol;
    ChildSaSession->LocalPort = IkeSaSession->Spd->Selector->LocalPort;
    ChildSaSession->RemotePort = IkeSaSession->Spd->Selector->RemotePort;
  }

  //
  // Insert the new ChildSaSession into processing child SA list.
  //
  Ikev2ChildSaSessionInsert (&IkeSaSession->ChildSaSessionList, ChildSaSession);
  return ChildSaSession;
}

/**
  Check if the SPD is related to the input Child SA Session.

  This function is the subfunction of Ikev1AssociateSpdEntry(). It is the call
  back function of IpSecVisitConfigData(). 
  

  @param[in]  Type               Type of the input Config Selector.
  @param[in]  Selector           Pointer to the Configure Selector to be checked. 
  @param[in]  Data               Pointer to the Configure Selector's Data passed 
                                 from the caller.
  @param[in]  SelectorSize       The buffer size of Selector.
  @param[in]  DataSize           The buffer size of the Data.
  @param[in]  Context            The data passed from the caller. It is a Child
                                 SA Session in this context.

  @retval EFI_SUCCESS        The SPD Selector is not related to the Child SA Session. 
  @retval EFI_ABORTED        The SPD Selector is related to the Child SA session and 
                             set the ChildSaSession->Spd to point to this SPD Selector.

**/
EFI_STATUS
Ikev2MatchSpdEntry (
  IN EFI_IPSEC_CONFIG_DATA_TYPE     Type,
  IN EFI_IPSEC_CONFIG_SELECTOR      *Selector,
  IN VOID                           *Data,
  IN UINTN                          SelectorSize,
  IN UINTN                          DataSize,
  IN VOID                           *Context
  )
{
  IKEV2_CHILD_SA_SESSION  *ChildSaSession;
  EFI_IPSEC_SPD_SELECTOR  *SpdSelector;
  EFI_IPSEC_SPD_DATA      *SpdData;
  BOOLEAN                 IsMatch;
  UINT8                   IpVersion;

  ASSERT (Type == IPsecConfigDataTypeSpd);
  SpdData = (EFI_IPSEC_SPD_DATA *) Data;
  //
  // Bypass all non-protect SPD entry first
  //
  if (SpdData->Action != EfiIPsecActionProtect) {
    return EFI_SUCCESS;
  }

  ChildSaSession  = (IKEV2_CHILD_SA_SESSION *) Context;
  IpVersion       = ChildSaSession->SessionCommon.UdpService->IpVersion;
  SpdSelector     = (EFI_IPSEC_SPD_SELECTOR *) Selector;  
  IsMatch         = TRUE;

  if (SpdSelector->NextLayerProtocol == EFI_IP_PROTO_UDP &&
      SpdSelector->LocalPort == IKE_DEFAULT_PORT &&
      SpdSelector->LocalPortRange == 0 &&
      SpdSelector->RemotePort == IKE_DEFAULT_PORT &&
      SpdSelector->RemotePortRange == 0
      ) {
    //
    // TODO: Skip IKE Policy here or set a SPD entry?
    //
    return EFI_SUCCESS;
  }

  if (SpdSelector->NextLayerProtocol != EFI_IPSEC_ANY_PROTOCOL &&
      SpdSelector->NextLayerProtocol != ChildSaSession->ProtoId
      ) {
    IsMatch = FALSE;
  }

  if (SpdSelector->LocalPort != EFI_IPSEC_ANY_PORT && SpdSelector->LocalPort != ChildSaSession->LocalPort) {
    IsMatch = FALSE;
  }

  if (SpdSelector->RemotePort != EFI_IPSEC_ANY_PORT && SpdSelector->RemotePort != ChildSaSession->RemotePort) {
    IsMatch = FALSE;
  }

  IsMatch = (BOOLEAN) (IsMatch && 
                       IpSecMatchIpAddress (
                         IpVersion,
                         &ChildSaSession->SessionCommon.LocalPeerIp,
                         SpdSelector->LocalAddress,
                         SpdSelector->LocalAddressCount
                         ));

  IsMatch = (BOOLEAN) (IsMatch && 
                       IpSecMatchIpAddress (
                         IpVersion,
                         &ChildSaSession->SessionCommon.RemotePeerIp,
                         SpdSelector->RemoteAddress,
                         SpdSelector->RemoteAddressCount
                         ));

  if (IsMatch) {
    ChildSaSession->Spd = IkeSearchSpdEntry (SpdSelector);
    return EFI_ABORTED;
  } else {
    return EFI_SUCCESS;
  }
}

/**
  Check if the Algorithm ID is supported.

  @param[in]  AlgorithmId The specified Algorithm ID.
  @param[in]  Type        The type used to indicate the Algorithm is for Encrypt or
                          Authentication.

  @retval     TRUE        If the Algorithm ID is supported.
  @retval     FALSE       If the Algorithm ID is not supported.

**/
BOOLEAN
Ikev2IsSupportAlg (
  IN UINT16 AlgorithmId,
  IN UINT8  Type
  )
{
  UINT8 Index;
  switch (Type) {
  case IKE_ENCRYPT_TYPE :
    for (Index = 0; Index < IKEV2_SUPPORT_ENCRYPT_ALGORITHM_NUM; Index++) {
      if (mIkev2EncryptAlgorithmList[Index] == AlgorithmId) {
        return TRUE;
      }
    }
    break;

  case IKE_AUTH_TYPE :
    for (Index = 0; Index < IKEV2_SUPPORT_AUTH_ALGORITHM_NUM; Index++) {
      if (mIkev2AuthAlgorithmList[Index] == AlgorithmId) {
        return TRUE;
      }
    }
    break;

  case IKE_DH_TYPE :
    for (Index = 0; Index < IKEV2_SUPPORT_DH_ALGORITHM_NUM; Index++) {
      if (mIkev2DhGroupAlgorithmList[Index] == AlgorithmId) {
        return TRUE;
      }
    }
    break;

  case IKE_PRF_TYPE :
    for (Index = 0; Index < IKEV2_SUPPORT_PRF_ALGORITHM_NUM; Index++) {
      if (mIkev2PrfAlgorithmList[Index] == AlgorithmId) {
        return TRUE;
      }
    }
  }
  return FALSE;
}

/**
  Get the preferred algorithm types from ProposalData.

  @param[in]  ProposalData              Pointer to related IKEV2_PROPOSAL_DATA.
  @param[out] PreferEncryptAlgorithm    Output of preferred encrypt algorithm.
  @param[out] PreferIntegrityAlgorithm  Output of preferred integrity algorithm. 
  @param[out] PreferPrfAlgorithm        Output of preferred PRF algorithm. Only 
                                        for IKE SA.
  @param[out] PreferDhGroup             Output of preferred DH group. Only for 
                                        IKE SA.
  @param[out] PreferEncryptKeylength    Output of preferred encrypt key length 
                                        in bytes.
  @param[out] IsSupportEsn              Output of value about the Extented Sequence
                                        Number is support or not. Only for Child SA.
  @param[in]  IsChildSa                 If it is ture, the ProposalData is for IKE
                                        SA. Otherwise the proposalData is for Child SA.

**/
VOID
Ikev2ParseProposalData (
  IN     IKEV2_PROPOSAL_DATA  *ProposalData, 
     OUT UINT16               *PreferEncryptAlgorithm,
     OUT UINT16               *PreferIntegrityAlgorithm,
     OUT UINT16               *PreferPrfAlgorithm,
     OUT UINT16               *PreferDhGroup,
     OUT UINTN                *PreferEncryptKeylength,
     OUT BOOLEAN              *IsSupportEsn,
  IN     BOOLEAN              IsChildSa
) 
{
  IKEV2_TRANSFORM_DATA *TransformData;
  UINT8                TransformIndex;

  //
  // Check input parameters.
  //
  if (ProposalData == NULL ||
      PreferEncryptAlgorithm == NULL || 
      PreferIntegrityAlgorithm == NULL ||
      PreferEncryptKeylength == NULL
      ) {
    return;
  }

  if (IsChildSa) {
    if (IsSupportEsn == NULL) {
      return;
    }
  } else {
    if (PreferPrfAlgorithm == NULL || PreferDhGroup == NULL) {
      return;
    }
  }  

  TransformData = (IKEV2_TRANSFORM_DATA *)(ProposalData + 1);
  for (TransformIndex = 0; TransformIndex < ProposalData->NumTransforms; TransformIndex++) {
    switch (TransformData->TransformType) {          
    //
    // For IKE SA there are four algorithm types. Encryption Algorithm, Pseudo-random Function, 
    // Integrity Algorithm, Diffie-Hellman Group. For Child SA, there are three algorithm types. 
    // Encryption Algorithm, Integrity Algorithm, Extended Sequence Number.
    //
    case IKEV2_TRANSFORM_TYPE_ENCR:
      if (*PreferEncryptAlgorithm == 0 && Ikev2IsSupportAlg (TransformData->TransformId, IKE_ENCRYPT_TYPE)) {
        //
        // Check the attribute value. According to RFC, only Keylength is support.
        //
        if (TransformData->Attribute.AttrType == IKEV2_ATTRIBUTE_TYPE_KEYLEN) {
          //
          // If the Keylength is not support, continue to check the next one.
          //
          if (IpSecGetEncryptKeyLength ((UINT8)TransformData->TransformId) != (UINTN)(TransformData->Attribute.Attr.AttrValue >> 3)){
            break;
          } else {
            *PreferEncryptKeylength = TransformData->Attribute.Attr.AttrValue;
          }
        }
        *PreferEncryptAlgorithm = TransformData->TransformId;
      }
      break;

    case IKEV2_TRANSFORM_TYPE_PRF :
      if (!IsChildSa) {
        if (*PreferPrfAlgorithm == 0 && Ikev2IsSupportAlg (TransformData->TransformId, IKE_PRF_TYPE)) {
          *PreferPrfAlgorithm = TransformData->TransformId;
        }
      }       
      break;

    case IKEV2_TRANSFORM_TYPE_INTEG :
      if (*PreferIntegrityAlgorithm == 0 && Ikev2IsSupportAlg (TransformData->TransformId, IKE_AUTH_TYPE)) {
        *PreferIntegrityAlgorithm = TransformData->TransformId;
      }
      break;
      
    case IKEV2_TRANSFORM_TYPE_DH :
      if (!IsChildSa) {
        if (*PreferDhGroup == 0 && Ikev2IsSupportAlg (TransformData->TransformId, IKE_DH_TYPE)) {
          *PreferDhGroup = TransformData->TransformId;
        }
      }        
      break;
    
    case IKEV2_TRANSFORM_TYPE_ESN :
      if (IsChildSa) {
        if (TransformData->TransformId != 0) {
          *IsSupportEsn = TRUE;
        }
      }        
      break;

    default:
      break;
    }
    TransformData = (IKEV2_TRANSFORM_DATA *)(TransformData + 1);
  }
}

/**
  Parse the received Initial Exchange Packet.
  
  This function parse the SA Payload and Key Payload to find out the cryptographic 
  suite for the further IKE negotiation and fill it into the IKE SA Session's 
  CommonSession->SaParams.

  @param[in, out]  IkeSaSession  Pointer to related IKEV2_SA_SESSION.
  @param[in]       SaPayload     The received packet.
  @param[in]       Type          The received packet IKE header flag. 

  @retval          TRUE          If the SA proposal in Packet is acceptable.
  @retval          FALSE         If the SA proposal in Packet is not acceptable.

**/
BOOLEAN
Ikev2SaParseSaPayload (
  IN OUT IKEV2_SA_SESSION *IkeSaSession,
  IN     IKE_PAYLOAD      *SaPayload,
  IN     UINT8            Type
  )
{
  IKEV2_PROPOSAL_DATA  *ProposalData;
  UINT8                ProposalIndex;
  UINT16               PreferEncryptAlgorithm;
  UINT16               PreferIntegrityAlgorithm;
  UINT16               PreferPrfAlgorithm;
  UINT16               PreferDhGroup;
  UINTN                PreferEncryptKeylength;
  UINT16               EncryptAlgorithm;
  UINT16               IntegrityAlgorithm;
  UINT16               PrfAlgorithm;
  UINT16               DhGroup;
  UINTN                EncryptKeylength;
  BOOLEAN              IsMatch;
  UINTN                SaDataSize;

  PreferPrfAlgorithm       = 0;
  PreferIntegrityAlgorithm = 0;
  PreferDhGroup            = 0;
  PreferEncryptAlgorithm   = 0;
  PreferEncryptKeylength   = 0;
  PrfAlgorithm             = 0;
  IntegrityAlgorithm       = 0;
  DhGroup                  = 0;
  EncryptAlgorithm         = 0;
  EncryptKeylength         = 0;
  IsMatch                  = FALSE;

  if (Type == IKE_HEADER_FLAGS_INIT) {
    ProposalData   = (IKEV2_PROPOSAL_DATA *)((IKEV2_SA_DATA *)SaPayload->PayloadBuf + 1);
    for (ProposalIndex = 0; ProposalIndex < ((IKEV2_SA_DATA *)SaPayload->PayloadBuf)->NumProposals; ProposalIndex++) {
      //
      // Iterate each proposal to find the perfered one.
      //
      if (ProposalData->ProtocolId == IPSEC_PROTO_ISAKMP && ProposalData->NumTransforms >= 4) {
        //
        // Get the preferred algorithms.
        //
        Ikev2ParseProposalData (
          ProposalData, 
          &PreferEncryptAlgorithm,
          &PreferIntegrityAlgorithm,
          &PreferPrfAlgorithm,
          &PreferDhGroup,
          &PreferEncryptKeylength,
          NULL,
          FALSE
          );

        if (PreferEncryptAlgorithm != 0 &&
              PreferIntegrityAlgorithm != 0 &&
              PreferPrfAlgorithm != 0 && 
              PreferDhGroup != 0
              ) {
            //
            // Find the matched one. 
            //
            IkeSaSession->SessionCommon.SaParams = AllocateZeroPool (sizeof (IKEV2_SA_PARAMS));
            ASSERT (IkeSaSession->SessionCommon.SaParams != NULL);
            IkeSaSession->SessionCommon.SaParams->EncAlgId   = PreferEncryptAlgorithm;
            IkeSaSession->SessionCommon.SaParams->EnckeyLen  = PreferEncryptKeylength;
            IkeSaSession->SessionCommon.SaParams->DhGroup    = PreferDhGroup;
            IkeSaSession->SessionCommon.SaParams->Prf        = PreferPrfAlgorithm;
            IkeSaSession->SessionCommon.SaParams->IntegAlgId = PreferIntegrityAlgorithm;
            IkeSaSession->SessionCommon.PreferDhGroup        = PreferDhGroup;

            //
            // Save the matched one in IKEV2_SA_DATA for furthure calculation.
            //
            SaDataSize           = sizeof (IKEV2_SA_DATA) +
                                   sizeof (IKEV2_PROPOSAL_DATA) +
                                   sizeof (IKEV2_TRANSFORM_DATA) * 4;
            IkeSaSession->SaData = AllocateZeroPool (SaDataSize);
            ASSERT (IkeSaSession->SaData != NULL);

            IkeSaSession->SaData->NumProposals  = 1;

            //
            // BUGBUG: Suppose the matched proposal only has 4 transforms. If
            // The matched Proposal has more than 4 transforms means it contains
            // one than one transform with same type.
            //
            CopyMem (
              (IKEV2_PROPOSAL_DATA *) (IkeSaSession->SaData + 1), 
               ProposalData, 
               SaDataSize - sizeof (IKEV2_SA_DATA)
              );

            ((IKEV2_PROPOSAL_DATA *) (IkeSaSession->SaData + 1))->ProposalIndex = 1;
            return TRUE;
          } else {
            PreferEncryptAlgorithm   = 0;
            PreferIntegrityAlgorithm = 0;
            PreferPrfAlgorithm       = 0;
            PreferDhGroup            = 0;
            PreferEncryptKeylength   = 0;
          }
      }
      //
      // Point to next Proposal.
      //
      ProposalData = (IKEV2_PROPOSAL_DATA*)((UINT8*)(ProposalData + 1) + 
                     ProposalData->NumTransforms * sizeof (IKEV2_TRANSFORM_DATA));
    }
  } else if (Type == IKE_HEADER_FLAGS_RESPOND) {
    //
    // First check the SA proposal's ProtoctolID and Transform Numbers. Since it is 
    // the responded SA proposal, suppose it only has one proposal and the transform Numbers 
    // is 4. 
    //
    ProposalData  = (IKEV2_PROPOSAL_DATA *)((IKEV2_SA_DATA *) SaPayload->PayloadBuf + 1);
    if (ProposalData->ProtocolId != IPSEC_PROTO_ISAKMP || ProposalData->NumTransforms != 4) {
      return FALSE;
    }
    //
    // Get the preferred algorithms. 
    //
    Ikev2ParseProposalData (
      ProposalData,
      &PreferEncryptAlgorithm,
      &PreferIntegrityAlgorithm,
      &PreferPrfAlgorithm,
      &PreferDhGroup,
      &PreferEncryptKeylength,
      NULL, 
      FALSE
      );
    // 
    // Check if the Sa proposal data from received packet is in the IkeSaSession->SaData.
    //
    ProposalData = (IKEV2_PROPOSAL_DATA *) (IkeSaSession->SaData + 1);

    for (ProposalIndex = 0; ProposalIndex < IkeSaSession->SaData->NumProposals && (!IsMatch); ProposalIndex++) {
      Ikev2ParseProposalData (
          ProposalData, 
          &EncryptAlgorithm,
          &IntegrityAlgorithm,
          &PrfAlgorithm,
          &DhGroup,
          &EncryptKeylength,
          NULL,
          FALSE
          );
      if (EncryptAlgorithm == PreferEncryptAlgorithm &&
          EncryptKeylength == PreferEncryptKeylength &&
          IntegrityAlgorithm == PreferIntegrityAlgorithm &&
          PrfAlgorithm == PreferPrfAlgorithm &&
          DhGroup      == PreferDhGroup
          ) {
        IsMatch = TRUE;
      } else {
        EncryptAlgorithm   = 0;
        IntegrityAlgorithm = 0;
        PrfAlgorithm       = 0;
        DhGroup            = 0;
        EncryptKeylength   = 0; 
      }

      ProposalData = (IKEV2_PROPOSAL_DATA*)((UINT8*)(ProposalData + 1) + 
                     ProposalData->NumTransforms * sizeof (IKEV2_TRANSFORM_DATA));    
    }

    if (IsMatch) {
        IkeSaSession->SessionCommon.SaParams = AllocateZeroPool (sizeof (IKEV2_SA_PARAMS));
        ASSERT (IkeSaSession->SessionCommon.SaParams != NULL);
        IkeSaSession->SessionCommon.SaParams->EncAlgId   = PreferEncryptAlgorithm;
        IkeSaSession->SessionCommon.SaParams->EnckeyLen  = PreferEncryptKeylength;
        IkeSaSession->SessionCommon.SaParams->DhGroup    = PreferDhGroup;
        IkeSaSession->SessionCommon.SaParams->Prf        = PreferPrfAlgorithm;
        IkeSaSession->SessionCommon.SaParams->IntegAlgId = PreferIntegrityAlgorithm;
        IkeSaSession->SessionCommon.PreferDhGroup        = PreferDhGroup;
      
        return TRUE;
    }
  }
  return FALSE;
}

/**
  Parse the received Authentication Exchange Packet.
  
  This function parse the SA Payload and Key Payload to find out the cryptographic
  suite for the ESP and fill it into the Child SA Session's CommonSession->SaParams.
  
  @param[in, out]  ChildSaSession  Pointer to IKEV2_CHILD_SA_SESSION related to 
                                   this Authentication Exchange.
  @param[in]       SaPayload       The received packet.
  @param[in]       Type            The IKE header's flag of received packet . 
  
  @retval          TRUE            If the SA proposal in Packet is acceptable.
  @retval          FALSE           If the SA proposal in Packet is not acceptable.

**/
BOOLEAN
Ikev2ChildSaParseSaPayload (
  IN OUT IKEV2_CHILD_SA_SESSION *ChildSaSession,
  IN     IKE_PAYLOAD            *SaPayload,
  IN     UINT8                  Type
  )
{
  IKEV2_PROPOSAL_DATA  *ProposalData;
  UINT8                ProposalIndex;
  UINT16               PreferEncryptAlgorithm;
  UINT16               PreferIntegrityAlgorithm;
  UINTN                PreferEncryptKeylength;
  BOOLEAN              PreferIsSupportEsn;
  UINT16               EncryptAlgorithm;
  UINT16               IntegrityAlgorithm;
  UINTN                EncryptKeylength;
  BOOLEAN              IsSupportEsn;
  BOOLEAN              IsMatch;
  UINTN                SaDataSize;


  PreferIntegrityAlgorithm = 0;
  PreferEncryptAlgorithm   = 0;
  PreferEncryptKeylength   = 0;
  IntegrityAlgorithm       = 0;
  EncryptAlgorithm         = 0;
  EncryptKeylength         = 0;
  IsMatch                  = TRUE;
  IsSupportEsn             = FALSE;
  PreferIsSupportEsn       = FALSE;

  if (Type == IKE_HEADER_FLAGS_INIT) {
    ProposalData   = (IKEV2_PROPOSAL_DATA *)((IKEV2_SA_DATA *) SaPayload->PayloadBuf + 1);
    for (ProposalIndex = 0; ProposalIndex < ((IKEV2_SA_DATA *) SaPayload->PayloadBuf)->NumProposals; ProposalIndex++) {
      //
      // Iterate each proposal to find the preferred one.
      //
      if (ProposalData->ProtocolId == IPSEC_PROTO_IPSEC_ESP && ProposalData->NumTransforms >= 3) {
        //
        // Get the preferred algorithm.
        //
        Ikev2ParseProposalData (
          ProposalData,
          &PreferEncryptAlgorithm,
          &PreferIntegrityAlgorithm,
          NULL,
          NULL,
          &PreferEncryptKeylength,
          &IsSupportEsn,
          TRUE
          );
        //
        // Don't support the ESN now.
        //
        if (PreferEncryptAlgorithm != 0 && 
            PreferIntegrityAlgorithm != 0 &&
            !IsSupportEsn
            ) {
          //
          // Find the matched one. 
          //
          ChildSaSession->SessionCommon.SaParams = AllocateZeroPool (sizeof (IKEV2_SA_PARAMS));
          ASSERT (ChildSaSession->SessionCommon.SaParams != NULL);
          ChildSaSession->SessionCommon.SaParams->EncAlgId   = PreferEncryptAlgorithm;
          ChildSaSession->SessionCommon.SaParams->EnckeyLen  = PreferEncryptKeylength;
          ChildSaSession->SessionCommon.SaParams->IntegAlgId = PreferIntegrityAlgorithm;
          CopyMem (&ChildSaSession->RemotePeerSpi, ProposalData->Spi, sizeof (ChildSaSession->RemotePeerSpi));

          //
          // Save the matched one in IKEV2_SA_DATA for furthure calculation.
          //
          SaDataSize           = sizeof (IKEV2_SA_DATA) +
                                 sizeof (IKEV2_PROPOSAL_DATA) +
                                 sizeof (IKEV2_TRANSFORM_DATA) * 4;

          ChildSaSession->SaData = AllocateZeroPool (SaDataSize);
          ASSERT (ChildSaSession->SaData != NULL);

          ChildSaSession->SaData->NumProposals  = 1;

          //
          // BUGBUG: Suppose there are 4 transforms in the matched proposal. If
          // the matched Proposal has more than 4 transforms that means there 
          // are more than one transform with same type.
          //
          CopyMem (
            (IKEV2_PROPOSAL_DATA *) (ChildSaSession->SaData + 1),
             ProposalData,
             SaDataSize - sizeof (IKEV2_SA_DATA)
            );

          ((IKEV2_PROPOSAL_DATA *) (ChildSaSession->SaData + 1))->ProposalIndex = 1;

          ((IKEV2_PROPOSAL_DATA *) (ChildSaSession->SaData + 1))->Spi = AllocateCopyPool (
                                                                          sizeof (ChildSaSession->LocalPeerSpi), 
                                                                          &ChildSaSession->LocalPeerSpi
                                                                          );
          ASSERT (((IKEV2_PROPOSAL_DATA *) (ChildSaSession->SaData + 1))->Spi != NULL);
          return TRUE;

        } else {
          PreferEncryptAlgorithm   = 0;
          PreferIntegrityAlgorithm = 0;
          IsSupportEsn             = TRUE;
        }
      }
      //
      // Point to next Proposal
      //
      ProposalData = (IKEV2_PROPOSAL_DATA *)((UINT8 *)(ProposalData + 1) + 
                     ProposalData->NumTransforms * sizeof (IKEV2_TRANSFORM_DATA));
    }
  } else if (Type == IKE_HEADER_FLAGS_RESPOND) {
    //
    // First check the SA proposal's ProtoctolID and Transform Numbers. Since it is 
    // the responded SA proposal, suppose it only has one proposal and the transform Numbers 
    // is 3. 
    //
    ProposalData  = (IKEV2_PROPOSAL_DATA *)((IKEV2_SA_DATA *)SaPayload->PayloadBuf + 1);
    if (ProposalData->ProtocolId != IPSEC_PROTO_IPSEC_ESP || ProposalData->NumTransforms != 3) {
      return FALSE;
    }
    //
    // Get the preferred algorithms.
    //
    Ikev2ParseProposalData (
      ProposalData,
      &PreferEncryptAlgorithm,
      &PreferIntegrityAlgorithm,
      NULL,
      NULL,
      &PreferEncryptKeylength,
      &PreferIsSupportEsn,
      TRUE
      );

    ProposalData = (IKEV2_PROPOSAL_DATA *) (ChildSaSession->SaData + 1);

    for (ProposalIndex = 0; ProposalIndex < ChildSaSession->SaData->NumProposals && (!IsMatch); ProposalIndex++) {
      Ikev2ParseProposalData (
          ProposalData, 
          &EncryptAlgorithm,
          &IntegrityAlgorithm,
          NULL,
          NULL,
          &EncryptKeylength,
          &IsSupportEsn,
          TRUE
          );
      if (EncryptAlgorithm == PreferEncryptAlgorithm &&
          EncryptKeylength == PreferEncryptKeylength &&
          IntegrityAlgorithm == PreferIntegrityAlgorithm &&
          IsSupportEsn == PreferIsSupportEsn          
          ) {
        IsMatch = TRUE;
      } else {
        PreferEncryptAlgorithm   = 0;
        PreferIntegrityAlgorithm = 0;
        IsSupportEsn             = TRUE;
      }
       ProposalData = (IKEV2_PROPOSAL_DATA*)((UINT8*)(ProposalData + 1) + 
                     ProposalData->NumTransforms * sizeof (IKEV2_TRANSFORM_DATA));  
    }
  
    ProposalData  = (IKEV2_PROPOSAL_DATA *)((IKEV2_SA_DATA *)SaPayload->PayloadBuf + 1);
    if (IsMatch) {
        ChildSaSession->SessionCommon.SaParams = AllocateZeroPool (sizeof (IKEV2_SA_PARAMS));
        ASSERT (ChildSaSession->SessionCommon.SaParams != NULL);
        ChildSaSession->SessionCommon.SaParams->EncAlgId   = PreferEncryptAlgorithm;
        ChildSaSession->SessionCommon.SaParams->EnckeyLen  = PreferEncryptKeylength;
        ChildSaSession->SessionCommon.SaParams->IntegAlgId = PreferIntegrityAlgorithm;
        CopyMem (&ChildSaSession->RemotePeerSpi, ProposalData->Spi, sizeof (ChildSaSession->RemotePeerSpi));

        return TRUE;
    }
  }
  return FALSE;
}

/**
  Generate Key buffer from fragments.

  If the digest length of specified HashAlgId is larger than or equal with the 
  required output key length, derive the key directly. Otherwise, Key Material 
  needs to be PRF-based concatenation according to 2.13 of RFC 4306: 
  prf+ (K,S) = T1 | T2 | T3 | T4 | ..., T1 = prf (K, S | 0x01),
  T2 = prf (K, T1 | S | 0x02), T3 = prf (K, T2 | S | 0x03),T4 = prf (K, T3 | S | 0x04)
  then derive the key from this key material.
  
  @param[in]       HashAlgId        The Hash Algorithm ID used to generate key.
  @param[in]       HashKey          Pointer to a key buffer which contains hash key.
  @param[in]       HashKeyLength    The length of HashKey in bytes.
  @param[in, out]  OutputKey        Pointer to buffer which is used to receive the 
                                    output key.
  @param[in]       OutputKeyLength  The length of OutPutKey buffer.
  @param[in]       Fragments        Pointer to the data to be used to generate key.
  @param[in]       NumFragments     The numbers of the Fragement.

  @retval EFI_SUCCESS            The operation complete successfully.
  @retval EFI_INVALID_PARAMETER  If NumFragments is zero.
  @retval EFI_OUT_OF_RESOURCES   If the required resource can't be allocated.
  @retval Others                 The operation is failed.

**/
EFI_STATUS
Ikev2SaGenerateKey (
  IN     UINT8                 HashAlgId,
  IN     UINT8                 *HashKey,
  IN     UINTN                 HashKeyLength,
  IN OUT UINT8                 *OutputKey,
  IN     UINTN                 OutputKeyLength,
  IN     PRF_DATA_FRAGMENT    *Fragments,
  IN     UINTN                 NumFragments
  )
{
  EFI_STATUS          Status;
  PRF_DATA_FRAGMENT   LocalFragments[3];
  UINT8               *Digest;
  UINTN               DigestSize;
  UINTN               Round;
  UINTN               Index;
  UINTN               AuthKeyLength;
  UINTN               FragmentsSize;
  UINT8               TailData;

  Status = EFI_SUCCESS;

  if (NumFragments == 0) {
    return EFI_INVALID_PARAMETER;
  }

  LocalFragments[0].Data = NULL;
  LocalFragments[1].Data = NULL;
  LocalFragments[2].Data = NULL;

  AuthKeyLength = IpSecGetHmacDigestLength (HashAlgId);
  DigestSize    = AuthKeyLength;
  Digest        = AllocateZeroPool (AuthKeyLength);

  if (Digest == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }
  //
  // If the required output key length is less than the digest size,
  // copy the digest into OutputKey.
  //
  if (OutputKeyLength <=  DigestSize) {
    Status = IpSecCryptoIoHmac (
               HashAlgId,
               HashKey, 
               HashKeyLength, 
               (HASH_DATA_FRAGMENT *) Fragments, 
               NumFragments, 
               Digest, 
               DigestSize
               );
    if (EFI_ERROR (Status)) {
      goto Exit;
    }

    CopyMem (OutputKey, Digest, OutputKeyLength);
    goto Exit;
  }

  //
  //Otherwise, Key Material need to be PRF-based concatenation according to 2.13
  //of RFC 4306: prf+ (K,S) = T1 | T2 | T3 | T4 | ..., T1 = prf (K, S | 0x01),
  //T2 = prf (K, T1 | S | 0x02), T3 = prf (K, T2 | S | 0x03),T4 = prf (K, T3 | S | 0x04)
  //then derive the key from this key material.
  //
  FragmentsSize = 0;
  for (Index = 0; Index < NumFragments; Index++) {
    FragmentsSize = FragmentsSize + Fragments[Index].DataSize;
  }

  LocalFragments[1].Data     = AllocateZeroPool (FragmentsSize);
  ASSERT (LocalFragments[1].Data != NULL);
  LocalFragments[1].DataSize = FragmentsSize;

  //
  // Copy all input fragments into LocalFragments[1];
  //
  FragmentsSize = 0;
  for (Index = 0; Index < NumFragments; Index++) {
    CopyMem (
      LocalFragments[1].Data + FragmentsSize, 
      Fragments[Index].Data,
      Fragments[Index].DataSize
      );
    FragmentsSize = FragmentsSize + Fragments[Index].DataSize;
  }

  //
  // Prepare 0x01 as the first tail data.
  //
  TailData                   = 0x01;
  LocalFragments[2].Data     = &TailData;
  LocalFragments[2].DataSize = sizeof (TailData);
  //
  // Allocate buffer for the first fragment
  //
  LocalFragments[0].Data     = AllocateZeroPool (AuthKeyLength);
  ASSERT (LocalFragments[0].Data != NULL);
  LocalFragments[0].DataSize = AuthKeyLength;

  Round = (OutputKeyLength - 1) / AuthKeyLength + 1;
  for (Index = 0; Index < Round; Index++) {
    Status = IpSecCryptoIoHmac (
               HashAlgId, 
               HashKey, 
               HashKeyLength, 
               (HASH_DATA_FRAGMENT *)(Index == 0 ? &LocalFragments[1] : LocalFragments),
               Index == 0 ? 2 : 3, 
               Digest,
               DigestSize
               );
    if (EFI_ERROR(Status)) {
      goto Exit;
    }
    CopyMem (
      LocalFragments[0].Data, 
      Digest, 
      DigestSize
      );
    if (OutputKeyLength > DigestSize * (Index + 1)) {
      CopyMem (
        OutputKey + Index * DigestSize, 
        Digest, 
        DigestSize
        );
      LocalFragments[0].DataSize = DigestSize;
      TailData ++;
    } else {
      // 
      // The last round
      //
      CopyMem (
        OutputKey + Index * DigestSize, 
        Digest, 
        OutputKeyLength - Index * DigestSize
      );
    }
  }

Exit:
  //
  // Only First and second Framgement Data need to be freed.
  //
  for (Index = 0 ; Index < 2; Index++) {
    if (LocalFragments[Index].Data != NULL) {
      FreePool (LocalFragments[Index].Data);
    }
  }
  if (Digest != NULL) {
    FreePool (Digest);
  }
  return Status;
}