aboutsummaryrefslogtreecommitdiffstats
path: root/tests/hwsim/test_ap_ft.py
blob: 6ab4f8ca23ef01693ffc825446dcf56659027bdf (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
# Fast BSS Transition tests
# Copyright (c) 2013-2019, Jouni Malinen <j@w1.fi>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.

from remotehost import remote_compatible
import binascii
import os
import time
import logging
logger = logging.getLogger()
import signal
import struct
import subprocess

import hwsim_utils
from hwsim import HWSimRadio
import hostapd
from tshark import run_tshark
from utils import HwsimSkip, alloc_fail, fail_test, wait_fail_trigger, skip_with_fips, parse_ie
from wlantest import Wlantest
from test_ap_psk import check_mib, find_wpas_process, read_process_memory, verify_not_present, get_key_locations
from test_rrm import check_beacon_req

def ft_base_rsn():
    params = { "wpa": "2",
               "wpa_key_mgmt": "FT-PSK",
               "rsn_pairwise": "CCMP" }
    return params

def ft_base_mixed():
    params = { "wpa": "3",
               "wpa_key_mgmt": "WPA-PSK FT-PSK",
               "wpa_pairwise": "TKIP",
               "rsn_pairwise": "CCMP" }
    return params

def ft_params(rsn=True, ssid=None, passphrase=None):
    if rsn:
        params = ft_base_rsn()
    else:
        params = ft_base_mixed()
    if ssid:
        params["ssid"] = ssid
    if passphrase:
        params["wpa_passphrase"] = passphrase

    params["mobility_domain"] = "a1b2"
    params["r0_key_lifetime"] = "10000"
    params["pmk_r1_push"] = "1"
    params["reassociation_deadline"] = "1000"
    return params

def ft_params1a(rsn=True, ssid=None, passphrase=None):
    params = ft_params(rsn, ssid, passphrase)
    params['nas_identifier'] = "nas1.w1.fi"
    params['r1_key_holder'] = "000102030405"
    return params

def ft_params1(rsn=True, ssid=None, passphrase=None, discovery=False):
    params = ft_params1a(rsn, ssid, passphrase)
    if discovery:
        params['r0kh'] = "ff:ff:ff:ff:ff:ff * 100102030405060708090a0b0c0d0e0f100102030405060708090a0b0c0d0e0f"
        params['r1kh'] = "00:00:00:00:00:00 00:00:00:00:00:00 100102030405060708090a0b0c0d0e0f100102030405060708090a0b0c0d0e0f"
    else:
        params['r0kh'] = [ "02:00:00:00:03:00 nas1.w1.fi 100102030405060708090a0b0c0d0e0f100102030405060708090a0b0c0d0e0f",
                           "02:00:00:00:04:00 nas2.w1.fi 300102030405060708090a0b0c0d0e0f300102030405060708090a0b0c0d0e0f" ]
        params['r1kh'] = "02:00:00:00:04:00 00:01:02:03:04:06 200102030405060708090a0b0c0d0e0f200102030405060708090a0b0c0d0e0f"
    return params

def ft_params1_old_key(rsn=True, ssid=None, passphrase=None):
    params = ft_params1a(rsn, ssid, passphrase)
    params['r0kh'] = [ "02:00:00:00:03:00 nas1.w1.fi 100102030405060708090a0b0c0d0e0f",
                       "02:00:00:00:04:00 nas2.w1.fi 300102030405060708090a0b0c0d0e0f" ]
    params['r1kh'] = "02:00:00:00:04:00 00:01:02:03:04:06 200102030405060708090a0b0c0d0e0f"
    return params

def ft_params2a(rsn=True, ssid=None, passphrase=None):
    params = ft_params(rsn, ssid, passphrase)
    params['nas_identifier'] = "nas2.w1.fi"
    params['r1_key_holder'] = "000102030406"
    return params

def ft_params2(rsn=True, ssid=None, passphrase=None, discovery=False):
    params = ft_params2a(rsn, ssid, passphrase)
    if discovery:
        params['r0kh'] = "ff:ff:ff:ff:ff:ff * 100102030405060708090a0b0c0d0e0f100102030405060708090a0b0c0d0e0f"
        params['r1kh'] = "00:00:00:00:00:00 00:00:00:00:00:00 100102030405060708090a0b0c0d0e0f100102030405060708090a0b0c0d0e0f"
    else:
        params['r0kh'] = [ "02:00:00:00:03:00 nas1.w1.fi 200102030405060708090a0b0c0d0e0f200102030405060708090a0b0c0d0e0f",
                           "02:00:00:00:04:00 nas2.w1.fi 000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f" ]
        params['r1kh'] = "02:00:00:00:03:00 00:01:02:03:04:05 300102030405060708090a0b0c0d0e0f300102030405060708090a0b0c0d0e0f"
    return params

def ft_params2_old_key(rsn=True, ssid=None, passphrase=None):
    params = ft_params2a(rsn, ssid, passphrase)
    params['r0kh'] = [ "02:00:00:00:03:00 nas1.w1.fi 200102030405060708090a0b0c0d0e0f",
                       "02:00:00:00:04:00 nas2.w1.fi 000102030405060708090a0b0c0d0e0f" ]
    params['r1kh'] = "02:00:00:00:03:00 00:01:02:03:04:05 300102030405060708090a0b0c0d0e0f"
    return params

def ft_params1_r0kh_mismatch(rsn=True, ssid=None, passphrase=None):
    params = ft_params(rsn, ssid, passphrase)
    params['nas_identifier'] = "nas1.w1.fi"
    params['r1_key_holder'] = "000102030405"
    params['r0kh'] = [ "02:00:00:00:03:00 nas1.w1.fi 100102030405060708090a0b0c0d0e0f100102030405060708090a0b0c0d0e0f",
                       "12:00:00:00:04:00 nas2.w1.fi 300102030405060708090a0b0c0d0e0f300102030405060708090a0b0c0d0e0f" ]
    params['r1kh'] = "12:00:00:00:04:00 10:01:02:03:04:06 200102030405060708090a0b0c0d0e0f200102030405060708090a0b0c0d0e0f"
    return params

def ft_params2_incorrect_rrb_key(rsn=True, ssid=None, passphrase=None):
    params = ft_params(rsn, ssid, passphrase)
    params['nas_identifier'] = "nas2.w1.fi"
    params['r1_key_holder'] = "000102030406"
    params['r0kh'] = [ "02:00:00:00:03:00 nas1.w1.fi 200102030405060708090a0b0c0d0ef1200102030405060708090a0b0c0d0ef1",
                       "02:00:00:00:04:00 nas2.w1.fi 000102030405060708090a0b0c0d0ef2000102030405060708090a0b0c0d0ef2" ]
    params['r1kh'] = "02:00:00:00:03:00 00:01:02:03:04:05 300102030405060708090a0b0c0d0ef3300102030405060708090a0b0c0d0ef3"
    return params

def ft_params2_r0kh_mismatch(rsn=True, ssid=None, passphrase=None):
    params = ft_params(rsn, ssid, passphrase)
    params['nas_identifier'] = "nas2.w1.fi"
    params['r1_key_holder'] = "000102030406"
    params['r0kh'] = [ "12:00:00:00:03:00 nas1.w1.fi 200102030405060708090a0b0c0d0e0f200102030405060708090a0b0c0d0e0f",
                       "02:00:00:00:04:00 nas2.w1.fi 000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f" ]
    params['r1kh'] = "12:00:00:00:03:00 10:01:02:03:04:05 300102030405060708090a0b0c0d0e0f300102030405060708090a0b0c0d0e0f"
    return params

def run_roams(dev, apdev, hapd0, hapd1, ssid, passphrase, over_ds=False,
              sae=False, eap=False, fail_test=False, roams=1,
              pairwise_cipher="CCMP", group_cipher="TKIP CCMP", ptk_rekey="0",
              test_connectivity=True, eap_identity="gpsk user", conndev=False,
              force_initial_conn_to_first_ap=False, sha384=False,
              group_mgmt=None, ocv=None):
    logger.info("Connect to first AP")

    copts = {}
    copts["proto"] = "WPA2"
    copts["ieee80211w"] = "1"
    copts["scan_freq"] = "2412"
    copts["pairwise"] = pairwise_cipher
    copts["group"]  = group_cipher
    copts["wpa_ptk_rekey"] = ptk_rekey
    if group_mgmt:
        copts["group_mgmt"] = group_mgmt
    if ocv:
        copts["ocv"] = ocv
    if eap:
        copts["key_mgmt"] = "FT-EAP-SHA384" if sha384 else "FT-EAP"
        copts["eap"] = "GPSK"
        copts["identity"] = eap_identity
        copts["password"] = "abcdefghijklmnop0123456789abcdef"
    else:
        if sae:
            copts["key_mgmt"] = "FT-SAE"
        else:
            copts["key_mgmt"] = "FT-PSK"
        copts["psk"] = passphrase
    if force_initial_conn_to_first_ap:
        copts["bssid"] = apdev[0]['bssid']
    dev.connect(ssid, **copts)

    if dev.get_status_field('bssid') == apdev[0]['bssid']:
        ap1 = apdev[0]
        ap2 = apdev[1]
        hapd1ap = hapd0
        hapd2ap = hapd1
    else:
        ap1 = apdev[1]
        ap2 = apdev[0]
        hapd1ap = hapd1
        hapd2ap = hapd0
    if test_connectivity:
        if conndev:
            hwsim_utils.test_connectivity_iface(dev, hapd1ap, conndev)
        else:
            hwsim_utils.test_connectivity(dev, hapd1ap)

    dev.scan_for_bss(ap2['bssid'], freq="2412")

    for i in range(0, roams):
        # Roaming artificially fast can make data test fail because the key is
        # set later.
        time.sleep(0.01)
        logger.info("Roam to the second AP")
        if over_ds:
            dev.roam_over_ds(ap2['bssid'], fail_test=fail_test)
        else:
            dev.roam(ap2['bssid'], fail_test=fail_test)
        if fail_test:
            return
        if dev.get_status_field('bssid') != ap2['bssid']:
            raise Exception("Did not connect to correct AP")
        if (i == 0 or i == roams - 1) and test_connectivity:
            if conndev:
                hwsim_utils.test_connectivity_iface(dev, hapd2ap, conndev)
            else:
                hwsim_utils.test_connectivity(dev, hapd2ap)

        # Roaming artificially fast can make data test fail because the key is
        # set later.
        time.sleep(0.01)
        logger.info("Roam back to the first AP")
        if over_ds:
            dev.roam_over_ds(ap1['bssid'])
        else:
            dev.roam(ap1['bssid'])
        if dev.get_status_field('bssid') != ap1['bssid']:
            raise Exception("Did not connect to correct AP")
        if (i == 0 or i == roams - 1) and test_connectivity:
            if conndev:
                hwsim_utils.test_connectivity_iface(dev, hapd1ap, conndev)
            else:
                hwsim_utils.test_connectivity(dev, hapd1ap)

def test_ap_ft(dev, apdev):
    """WPA2-PSK-FT AP"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase)
    if "[WPA2-FT/PSK-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")

def test_ap_ft_old_key(dev, apdev):
    """WPA2-PSK-FT AP (old key)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1_old_key(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2_old_key(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase)

def test_ap_ft_multi_akm(dev, apdev):
    """WPA2-PSK-FT AP with non-FT AKMs enabled"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["wpa_key_mgmt"] = "FT-PSK WPA-PSK WPA-PSK-SHA256"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["wpa_key_mgmt"] = "FT-PSK WPA-PSK WPA-PSK-SHA256"
    hapd1 = hostapd.add_ap(apdev[1], params)

    Wlantest.setup(hapd0)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase(passphrase)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase)
    if "[WPA2-PSK+FT/PSK+PSK-SHA256-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")
    dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
    dev[2].connect(ssid, psk=passphrase, key_mgmt="WPA-PSK-SHA256",
                   scan_freq="2412")

def test_ap_ft_local_key_gen(dev, apdev):
    """WPA2-PSK-FT AP with local key generation (without pull/push)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1a(ssid=ssid, passphrase=passphrase)
    params['ft_psk_generate_local'] = "1";
    del params['pmk_r1_push']
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2a(ssid=ssid, passphrase=passphrase)
    params['ft_psk_generate_local'] = "1";
    del params['pmk_r1_push']
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase)
    if "[WPA2-FT/PSK-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")

def test_ap_ft_vlan(dev, apdev):
    """WPA2-PSK-FT AP with VLAN"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd0 = hostapd.add_ap(apdev[0]['ifname'], params)

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd1 = hostapd.add_ap(apdev[1]['ifname'], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, conndev="brvlan1")
    if "[WPA2-FT/PSK-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")

def test_ap_ft_vlan_disconnected(dev, apdev):
    """WPA2-PSK-FT AP with VLAN and local key generation"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1a(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    params['ft_psk_generate_local'] = "1";
    hapd0 = hostapd.add_ap(apdev[0]['ifname'], params)

    params = ft_params2a(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    params['ft_psk_generate_local'] = "1";
    hapd1 = hostapd.add_ap(apdev[1]['ifname'], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, conndev="brvlan1")
    if "[WPA2-FT/PSK-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")

def test_ap_ft_vlan_2(dev, apdev):
    """WPA2-PSK-FT AP with VLAN and dest-AP does not have VLAN info locally"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd0 = hostapd.add_ap(apdev[0]['ifname'], params)

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    hapd1 = hostapd.add_ap(apdev[1]['ifname'], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, conndev="brvlan1",
	      force_initial_conn_to_first_ap=True)
    if "[WPA2-FT/PSK-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")

def test_ap_ft_many(dev, apdev):
    """WPA2-PSK-FT AP multiple times"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, roams=50)

def test_ap_ft_many_vlan(dev, apdev):
    """WPA2-PSK-FT AP with VLAN multiple times"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd0 = hostapd.add_ap(apdev[0]['ifname'], params)

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd1 = hostapd.add_ap(apdev[1]['ifname'], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, roams=50,
              conndev="brvlan1")

def test_ap_ft_mixed(dev, apdev):
    """WPA2-PSK-FT mixed-mode AP"""
    ssid = "test-ft-mixed"
    passphrase="12345678"

    params = ft_params1(rsn=False, ssid=ssid, passphrase=passphrase)
    hapd = hostapd.add_ap(apdev[0], params)
    key_mgmt = hapd.get_config()['key_mgmt']
    vals = key_mgmt.split(' ')
    if vals[0] != "WPA-PSK" or vals[1] != "FT-PSK":
        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
    params = ft_params2(rsn=False, ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd, hapd1, ssid, passphrase)

def test_ap_ft_pmf(dev, apdev):
    """WPA2-PSK-FT AP with PMF"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase)

def test_ap_ft_pmf_bip_cmac_128(dev, apdev):
    """WPA2-PSK-FT AP with PMF/BIP-CMAC-128"""
    run_ap_ft_pmf_bip(dev, apdev, "AES-128-CMAC")

def test_ap_ft_pmf_bip_gmac_128(dev, apdev):
    """WPA2-PSK-FT AP with PMF/BIP-GMAC-128"""
    run_ap_ft_pmf_bip(dev, apdev, "BIP-GMAC-128")

def test_ap_ft_pmf_bip_gmac_256(dev, apdev):
    """WPA2-PSK-FT AP with PMF/BIP-GMAC-256"""
    run_ap_ft_pmf_bip(dev, apdev, "BIP-GMAC-256")

def test_ap_ft_pmf_bip_cmac_256(dev, apdev):
    """WPA2-PSK-FT AP with PMF/BIP-CMAC-256"""
    run_ap_ft_pmf_bip(dev, apdev, "BIP-CMAC-256")

def run_ap_ft_pmf_bip(dev, apdev, cipher):
    if cipher not in dev[0].get_capability("group_mgmt"):
        raise HwsimSkip("Cipher %s not supported" % cipher)

    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    params["group_mgmt_cipher"] = cipher
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    params["group_mgmt_cipher"] = cipher
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase,
              group_mgmt=cipher)

def test_ap_ft_ocv(dev, apdev):
    """WPA2-PSK-FT AP with OCV"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    params["ocv"] = "1"
    try:
        hapd0 = hostapd.add_ap(apdev[0], params)
    except Exception, e:
        if "Failed to set hostapd parameter ocv" in str(e):
            raise HwsimSkip("OCV not supported")
        raise
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    params["ocv"] = "1"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, ocv="1")

def test_ap_ft_over_ds(dev, apdev):
    """WPA2-PSK-FT AP over DS"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True)
    check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-4"),
                        ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-4") ])

def cleanup_ap_ft_separate_hostapd():
    subprocess.call(["brctl", "delif", "br0ft", "veth0"],
                    stderr=open('/dev/null', 'w'))
    subprocess.call(["brctl", "delif", "br1ft", "veth1"],
                    stderr=open('/dev/null', 'w'))
    subprocess.call(["ip", "link", "del", "veth0"],
                    stderr=open('/dev/null', 'w'))
    subprocess.call(["ip", "link", "del", "veth1"],
                    stderr=open('/dev/null', 'w'))
    for ifname in [ 'br0ft', 'br1ft', 'br-ft' ]:
        subprocess.call(['ip', 'link', 'set', 'dev', ifname, 'down'],
                        stderr=open('/dev/null', 'w'))
        subprocess.call(['brctl', 'delbr', ifname],
                        stderr=open('/dev/null', 'w'))

def test_ap_ft_separate_hostapd(dev, apdev, params):
    """WPA2-PSK-FT AP and separate hostapd process"""
    try:
        run_ap_ft_separate_hostapd(dev, apdev, params, False)
    finally:
        cleanup_ap_ft_separate_hostapd()

def test_ap_ft_over_ds_separate_hostapd(dev, apdev, params):
    """WPA2-PSK-FT AP over DS and separate hostapd process"""
    try:
        run_ap_ft_separate_hostapd(dev, apdev, params, True)
    finally:
        cleanup_ap_ft_separate_hostapd()

def run_ap_ft_separate_hostapd(dev, apdev, params, over_ds):
    ssid = "test-ft"
    passphrase="12345678"
    logdir = params['logdir']
    pidfile = os.path.join(logdir, 'ap_ft_over_ds_separate_hostapd.pid')
    logfile = os.path.join(logdir, 'ap_ft_over_ds_separate_hostapd.hapd')
    global_ctrl = '/var/run/hostapd-ft'
    br_ifname = 'br-ft'

    try:
        subprocess.check_call(['brctl', 'addbr', br_ifname])
        subprocess.check_call(['brctl', 'setfd', br_ifname, '0'])
        subprocess.check_call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])

        subprocess.check_call([ "ip", "link", "add", "veth0", "type", "veth",
                                "peer", "name", "veth0br" ])
        subprocess.check_call([ "ip", "link", "add", "veth1", "type", "veth",
                                "peer", "name", "veth1br" ])
        subprocess.check_call(['ip', 'link', 'set', 'dev', 'veth0br', 'up'])
        subprocess.check_call(['ip', 'link', 'set', 'dev', 'veth1br', 'up'])
        subprocess.check_call(['brctl', 'addif', br_ifname, 'veth0br'])
        subprocess.check_call(['brctl', 'addif', br_ifname, 'veth1br'])

        subprocess.check_call(['brctl', 'addbr', 'br0ft'])
        subprocess.check_call(['brctl', 'setfd', 'br0ft', '0'])
        subprocess.check_call(['ip', 'link', 'set', 'dev', 'br0ft', 'up'])
        subprocess.check_call(['ip', 'link', 'set', 'dev', 'veth0', 'up'])
        subprocess.check_call(['brctl', 'addif', 'br0ft', 'veth0'])
        subprocess.check_call(['brctl', 'addbr', 'br1ft'])
        subprocess.check_call(['brctl', 'setfd', 'br1ft', '0'])
        subprocess.check_call(['ip', 'link', 'set', 'dev', 'br1ft', 'up'])
        subprocess.check_call(['ip', 'link', 'set', 'dev', 'veth1', 'up'])
        subprocess.check_call(['brctl', 'addif', 'br1ft', 'veth1'])
    except subprocess.CalledProcessError:
        raise HwsimSkip("Bridge or veth not supported (kernel CONFIG_VETH)")

    with HWSimRadio() as (radio, iface):
        prg = os.path.join(logdir, 'alt-hostapd/hostapd/hostapd')
        if not os.path.exists(prg):
            prg = '../../hostapd/hostapd'
        cmd = [ prg, '-B', '-ddKt',
                '-P', pidfile, '-f', logfile, '-g', global_ctrl ]
        subprocess.check_call(cmd)

        hglobal = hostapd.HostapdGlobal(global_ctrl_override=global_ctrl)
        apdev_ft = { 'ifname': iface }
        apdev2 = [ apdev_ft, apdev[1] ]

        params = ft_params1(ssid=ssid, passphrase=passphrase)
        params["r0kh"] = "ff:ff:ff:ff:ff:ff * 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
        params["r1kh"] = "00:00:00:00:00:00 00:00:00:00:00:00 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
        params['bridge'] = 'br0ft'
        hapd0 = hostapd.add_ap(apdev2[0], params,
                               global_ctrl_override=global_ctrl)
        apdev2[0]['bssid'] = hapd0.own_addr()
        params = ft_params2(ssid=ssid, passphrase=passphrase)
        params["r0kh"] = "ff:ff:ff:ff:ff:ff * 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
        params["r1kh"] = "00:00:00:00:00:00 00:00:00:00:00:00 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
        params['bridge'] = 'br1ft'
        hapd1 = hostapd.add_ap(apdev2[1], params)

        run_roams(dev[0], apdev2, hapd0, hapd1, ssid, passphrase,
                  over_ds=over_ds, test_connectivity=False)

        hglobal.terminate()

    if os.path.exists(pidfile):
        with open(pidfile, 'r') as f:
            pid = int(f.read())
            f.close()
        os.kill(pid, signal.SIGTERM)

def test_ap_ft_over_ds_ocv(dev, apdev):
    """WPA2-PSK-FT AP over DS"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    params["ocv"] = "1"
    try:
        hapd0 = hostapd.add_ap(apdev[0], params)
    except Exception, e:
        if "Failed to set hostapd parameter ocv" in str(e):
            raise HwsimSkip("OCV not supported")
        raise
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    params["ocv"] = "1"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              ocv="1")

def test_ap_ft_over_ds_disabled(dev, apdev):
    """WPA2-PSK-FT AP over DS disabled"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['ft_over_ds'] = '0'
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['ft_over_ds'] = '0'
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True)

def test_ap_ft_vlan_over_ds(dev, apdev):
    """WPA2-PSK-FT AP over DS with VLAN"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd0 = hostapd.add_ap(apdev[0]['ifname'], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd1 = hostapd.add_ap(apdev[1]['ifname'], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              conndev="brvlan1")
    check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-4"),
                        ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-4") ])

def test_ap_ft_over_ds_many(dev, apdev):
    """WPA2-PSK-FT AP over DS multiple times"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              roams=50)

def test_ap_ft_vlan_over_ds_many(dev, apdev):
    """WPA2-PSK-FT AP over DS with VLAN multiple times"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd0 = hostapd.add_ap(apdev[0]['ifname'], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd1 = hostapd.add_ap(apdev[1]['ifname'], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              roams=50, conndev="brvlan1")

@remote_compatible
def test_ap_ft_over_ds_unknown_target(dev, apdev):
    """WPA2-PSK-FT AP"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")
    dev[0].roam_over_ds("02:11:22:33:44:55", fail_test=True)

@remote_compatible
def test_ap_ft_over_ds_unexpected(dev, apdev):
    """WPA2-PSK-FT AP over DS and unexpected response"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")
    if dev[0].get_status_field('bssid') == apdev[0]['bssid']:
        ap1 = apdev[0]
        ap2 = apdev[1]
        hapd1ap = hapd0
        hapd2ap = hapd1
    else:
        ap1 = apdev[1]
        ap2 = apdev[0]
        hapd1ap = hapd1
        hapd2ap = hapd0

    addr = dev[0].own_addr()
    hapd1ap.set("ext_mgmt_frame_handling", "1")
    logger.info("Foreign STA address")
    msg = {}
    msg['fc'] = 13 << 4
    msg['da'] = addr
    msg['sa'] = ap1['bssid']
    msg['bssid'] = ap1['bssid']
    msg['payload'] = binascii.unhexlify("06021122334455660102030405060000")
    hapd1ap.mgmt_tx(msg)

    logger.info("No over-the-DS in progress")
    msg['payload'] = binascii.unhexlify("0602" + addr.replace(':', '') + "0102030405060000")
    hapd1ap.mgmt_tx(msg)

    logger.info("Non-zero status code")
    msg['payload'] = binascii.unhexlify("0602" + addr.replace(':', '') + "0102030405060100")
    hapd1ap.mgmt_tx(msg)

    hapd1ap.dump_monitor()

    dev[0].scan_for_bss(ap2['bssid'], freq="2412")
    if "OK" not in dev[0].request("FT_DS " + ap2['bssid']):
            raise Exception("FT_DS failed")

    req = hapd1ap.mgmt_rx()

    logger.info("Foreign Target AP")
    msg['payload'] = binascii.unhexlify("0602" + addr.replace(':', '') + "0102030405060000")
    hapd1ap.mgmt_tx(msg)

    addrs = addr.replace(':', '') + ap2['bssid'].replace(':', '')

    logger.info("No IEs")
    msg['payload'] = binascii.unhexlify("0602" + addrs + "0000")
    hapd1ap.mgmt_tx(msg)

    logger.info("Invalid IEs (trigger parsing failure)")
    msg['payload'] = binascii.unhexlify("0602" + addrs + "00003700")
    hapd1ap.mgmt_tx(msg)

    logger.info("Too short MDIE")
    msg['payload'] = binascii.unhexlify("0602" + addrs + "000036021122")
    hapd1ap.mgmt_tx(msg)

    logger.info("Mobility domain mismatch")
    msg['payload'] = binascii.unhexlify("0602" + addrs + "00003603112201")
    hapd1ap.mgmt_tx(msg)

    logger.info("No FTIE")
    msg['payload'] = binascii.unhexlify("0602" + addrs + "00003603a1b201")
    hapd1ap.mgmt_tx(msg)

    logger.info("FTIE SNonce mismatch")
    msg['payload'] = binascii.unhexlify("0602" + addrs + "00003603a1b201375e0000" + "00000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + "1000000000000000000000000000000000000000000000000000000000000001" + "030a6e6173322e77312e6669")
    hapd1ap.mgmt_tx(msg)

    logger.info("No R0KH-ID subelem in FTIE")
    snonce = binascii.hexlify(req['payload'][111:111+32])
    msg['payload'] = binascii.unhexlify("0602" + addrs + "00003603a1b20137520000" + "00000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + snonce)
    hapd1ap.mgmt_tx(msg)

    logger.info("No R0KH-ID subelem mismatch in FTIE")
    snonce = binascii.hexlify(req['payload'][111:111+32])
    msg['payload'] = binascii.unhexlify("0602" + addrs + "00003603a1b201375e0000" + "00000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + snonce + "030a11223344556677889900")
    hapd1ap.mgmt_tx(msg)

    logger.info("No R1KH-ID subelem in FTIE")
    r0khid = binascii.hexlify(req['payload'][145:145+10])
    msg['payload'] = binascii.unhexlify("0602" + addrs + "00003603a1b201375e0000" + "00000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + snonce + "030a" + r0khid)
    hapd1ap.mgmt_tx(msg)

    logger.info("No RSNE")
    r0khid = binascii.hexlify(req['payload'][145:145+10])
    msg['payload'] = binascii.unhexlify("0602" + addrs + "00003603a1b20137660000" + "00000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + snonce + "030a" + r0khid + "0106000102030405")
    hapd1ap.mgmt_tx(msg)

def test_ap_ft_pmf_over_ds(dev, apdev):
    """WPA2-PSK-FT AP over DS with PMF"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd1 = hostapd.add_ap(apdev[1], params)

def test_ap_ft_pmf_bip_cmac_128_over_ds(dev, apdev):
    """WPA2-PSK-FT AP over DS with PMF/BIP-CMAC-128"""
    run_ap_ft_pmf_bip_over_ds(dev, apdev, "AES-128-CMAC")

def test_ap_ft_pmf_bip_gmac_128_over_ds(dev, apdev):
    """WPA2-PSK-FT AP over DS with PMF/BIP-GMAC-128"""
    run_ap_ft_pmf_bip_over_ds(dev, apdev, "BIP-GMAC-128")

def test_ap_ft_pmf_bip_gmac_256_over_ds(dev, apdev):
    """WPA2-PSK-FT AP over DS with PMF/BIP-GMAC-256"""
    run_ap_ft_pmf_bip_over_ds(dev, apdev, "BIP-GMAC-256")

def test_ap_ft_pmf_bip_cmac_256_over_ds(dev, apdev):
    """WPA2-PSK-FT AP over DS with PMF/BIP-CMAC-256"""
    run_ap_ft_pmf_bip_over_ds(dev, apdev, "BIP-CMAC-256")

def run_ap_ft_pmf_bip_over_ds(dev, apdev, cipher):
    if cipher not in dev[0].get_capability("group_mgmt"):
        raise HwsimSkip("Cipher %s not supported" % cipher)

    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    params["group_mgmt_cipher"] = cipher
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    params["group_mgmt_cipher"] = cipher
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              group_mgmt=cipher)

def test_ap_ft_over_ds_pull(dev, apdev):
    """WPA2-PSK-FT AP over DS (pull PMK)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True)

def test_ap_ft_over_ds_pull_old_key(dev, apdev):
    """WPA2-PSK-FT AP over DS (pull PMK; old key)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1_old_key(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2_old_key(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True)

def test_ap_ft_over_ds_pull_vlan(dev, apdev):
    """WPA2-PSK-FT AP over DS (pull PMK) with VLAN"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd0 = hostapd.add_ap(apdev[0]['ifname'], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params['dynamic_vlan'] = "1";
    params['accept_mac_file'] = "hostapd.accept";
    hapd1 = hostapd.add_ap(apdev[1]['ifname'], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              conndev="brvlan1")

def test_ap_ft_sae(dev, apdev):
    """WPA2-PSK-FT-SAE AP"""
    if "SAE" not in dev[0].get_capability("auth_alg"):
        raise HwsimSkip("SAE not supported")
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['wpa_key_mgmt'] = "FT-SAE"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['wpa_key_mgmt'] = "FT-SAE"
    hapd = hostapd.add_ap(apdev[1], params)
    key_mgmt = hapd.get_config()['key_mgmt']
    if key_mgmt.split(' ')[0] != "FT-SAE":
        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)

    dev[0].request("SET sae_groups ")
    run_roams(dev[0], apdev, hapd0, hapd, ssid, passphrase, sae=True)

def test_ap_ft_sae_over_ds(dev, apdev):
    """WPA2-PSK-FT-SAE AP over DS"""
    if "SAE" not in dev[0].get_capability("auth_alg"):
        raise HwsimSkip("SAE not supported")
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['wpa_key_mgmt'] = "FT-SAE"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['wpa_key_mgmt'] = "FT-SAE"
    hapd1 = hostapd.add_ap(apdev[1], params)

    dev[0].request("SET sae_groups ")
    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, sae=True,
              over_ds=True)

def generic_ap_ft_eap(dev, apdev, vlan=False, cui=False, over_ds=False,
                      discovery=False, roams=1):
    ssid = "test-ft"
    passphrase="12345678"
    if vlan:
        identity="gpsk-vlan1"
        conndev="brvlan1"
    elif cui:
        identity="gpsk-cui"
        conndev=False
    else:
        identity="gpsk user"
        conndev=False

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase, discovery=discovery)
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    if vlan:
        params["dynamic_vlan"] = "1"
    params = dict(radius.items() + params.items())
    hapd = hostapd.add_ap(apdev[0], params)
    key_mgmt = hapd.get_config()['key_mgmt']
    if key_mgmt.split(' ')[0] != "FT-EAP":
        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
    params = ft_params2(ssid=ssid, passphrase=passphrase, discovery=discovery)
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    if vlan:
        params["dynamic_vlan"] = "1"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd, hapd1, ssid, passphrase, eap=True,
              over_ds=over_ds, roams=roams, eap_identity=identity,
              conndev=conndev)
    if "[WPA2-FT/EAP-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")
    check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-3"),
                        ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-3") ])

    # Verify EAPOL reauthentication after FT protocol
    if dev[0].get_status_field('bssid') == apdev[0]['bssid']:
        ap = hapd
    else:
        ap = hapd1
    ap.request("EAPOL_REAUTH " + dev[0].own_addr())
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
    if ev is None:
        raise Exception("EAP authentication did not start")
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=5)
    if ev is None:
        raise Exception("EAP authentication did not succeed")
    time.sleep(0.1)
    if conndev:
        hwsim_utils.test_connectivity_iface(dev[0], ap, conndev)
    else:
        hwsim_utils.test_connectivity(dev[0], ap)

def test_ap_ft_eap(dev, apdev):
    """WPA2-EAP-FT AP"""
    generic_ap_ft_eap(dev, apdev)

def test_ap_ft_eap_cui(dev, apdev):
    """WPA2-EAP-FT AP with CUI"""
    generic_ap_ft_eap(dev, apdev, vlan=False, cui=True)

def test_ap_ft_eap_vlan(dev, apdev):
    """WPA2-EAP-FT AP with VLAN"""
    generic_ap_ft_eap(dev, apdev, vlan=True)

def test_ap_ft_eap_vlan_multi(dev, apdev):
    """WPA2-EAP-FT AP with VLAN"""
    generic_ap_ft_eap(dev, apdev, vlan=True, roams=50)

def test_ap_ft_eap_over_ds(dev, apdev):
    """WPA2-EAP-FT AP using over-the-DS"""
    generic_ap_ft_eap(dev, apdev, over_ds=True)

def test_ap_ft_eap_dis(dev, apdev):
    """WPA2-EAP-FT AP with AP discovery"""
    generic_ap_ft_eap(dev, apdev, discovery=True)

def test_ap_ft_eap_dis_over_ds(dev, apdev):
    """WPA2-EAP-FT AP with AP discovery and over-the-DS"""
    generic_ap_ft_eap(dev, apdev, over_ds=True, discovery=True)

def test_ap_ft_eap_vlan(dev, apdev):
    """WPA2-EAP-FT AP with VLAN"""
    generic_ap_ft_eap(dev, apdev, vlan=True)

def test_ap_ft_eap_vlan_multi(dev, apdev):
    """WPA2-EAP-FT AP with VLAN"""
    generic_ap_ft_eap(dev, apdev, vlan=True, roams=50)

def test_ap_ft_eap_vlan_over_ds(dev, apdev):
    """WPA2-EAP-FT AP with VLAN + over_ds"""
    generic_ap_ft_eap(dev, apdev, vlan=True, over_ds=True)

def test_ap_ft_eap_vlan_over_ds_multi(dev, apdev):
    """WPA2-EAP-FT AP with VLAN + over_ds"""
    generic_ap_ft_eap(dev, apdev, vlan=True, over_ds=True, roams=50)

def generic_ap_ft_eap_pull(dev, apdev, vlan=False):
    """WPA2-EAP-FT AP (pull PMK)"""
    ssid = "test-ft"
    passphrase="12345678"
    if vlan:
        identity="gpsk-vlan1"
        conndev="brvlan1"
    else:
        identity="gpsk user"
        conndev=False

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params["pmk_r1_push"] = "0"
    if vlan:
        params["dynamic_vlan"] = "1"
    params = dict(radius.items() + params.items())
    hapd = hostapd.add_ap(apdev[0], params)
    key_mgmt = hapd.get_config()['key_mgmt']
    if key_mgmt.split(' ')[0] != "FT-EAP":
        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params["pmk_r1_push"] = "0"
    if vlan:
        params["dynamic_vlan"] = "1"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd, hapd1, ssid, passphrase, eap=True,
              eap_identity=identity, conndev=conndev)

def test_ap_ft_eap_pull(dev, apdev):
    """WPA2-EAP-FT AP (pull PMK)"""
    generic_ap_ft_eap_pull(dev, apdev)

def test_ap_ft_eap_pull_vlan(dev, apdev):
    generic_ap_ft_eap_pull(dev, apdev, vlan=True)

def test_ap_ft_eap_pull_wildcard(dev, apdev):
    """WPA2-EAP-FT AP (pull PMK) - wildcard R0KH/R1KH"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase, discovery=True)
    params['wpa_key_mgmt'] = "WPA-EAP FT-EAP"
    params["ieee8021x"] = "1"
    params["pmk_r1_push"] = "0"
    params["r0kh"] = "ff:ff:ff:ff:ff:ff * 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
    params["r1kh"] = "00:00:00:00:00:00 00:00:00:00:00:00 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
    params["ft_psk_generate_local"] = "1"
    params["eap_server"] = "0"
    params = dict(radius.items() + params.items())
    hapd = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase, discovery=True)
    params['wpa_key_mgmt'] = "WPA-EAP FT-EAP"
    params["ieee8021x"] = "1"
    params["pmk_r1_push"] = "0"
    params["r0kh"] = "ff:ff:ff:ff:ff:ff * 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
    params["r1kh"] = "00:00:00:00:00:00 00:00:00:00:00:00 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
    params["ft_psk_generate_local"] = "1"
    params["eap_server"] = "0"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd, hapd1, ssid, passphrase, eap=True)

@remote_compatible
def test_ap_ft_mismatching_rrb_key_push(dev, apdev):
    """WPA2-PSK-FT AP over DS with mismatching RRB key (push)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2_incorrect_rrb_key(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True)

@remote_compatible
def test_ap_ft_mismatching_rrb_key_pull(dev, apdev):
    """WPA2-PSK-FT AP over DS with mismatching RRB key (pull)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2_incorrect_rrb_key(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True)

@remote_compatible
def test_ap_ft_mismatching_r0kh_id_pull(dev, apdev):
    """WPA2-PSK-FT AP over DS with mismatching R0KH-ID (pull)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params["nas_identifier"] = "nas0.w1.fi"
    hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hostapd.add_ap(apdev[1], params)

    dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
    dev[0].roam_over_ds(apdev[1]['bssid'], fail_test=True)

@remote_compatible
def test_ap_ft_mismatching_rrb_r0kh_push(dev, apdev):
    """WPA2-PSK-FT AP over DS with mismatching R0KH key (push)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2_r0kh_mismatch(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True)

@remote_compatible
def test_ap_ft_mismatching_rrb_r0kh_pull(dev, apdev):
    """WPA2-PSK-FT AP over DS with mismatching R0KH key (pull)"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1_r0kh_mismatch(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True)

def test_ap_ft_mismatching_rrb_key_push_eap(dev, apdev):
    """WPA2-EAP-FT AP over DS with mismatching RRB key (push)"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2";
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2_incorrect_rrb_key(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2";
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True, eap=True)

def test_ap_ft_mismatching_rrb_key_pull_eap(dev, apdev):
    """WPA2-EAP-FT AP over DS with mismatching RRB key (pull)"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2_incorrect_rrb_key(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True, eap=True)

def test_ap_ft_mismatching_r0kh_id_pull_eap(dev, apdev):
    """WPA2-EAP-FT AP over DS with mismatching R0KH-ID (pull)"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params["nas_identifier"] = "nas0.w1.fi"
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, key_mgmt="FT-EAP", proto="WPA2", ieee80211w="1",
                   eap="GPSK", identity="gpsk user",
                   password="abcdefghijklmnop0123456789abcdef",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hostapd.add_ap(apdev[1], params)

    dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
    dev[0].roam_over_ds(apdev[1]['bssid'], fail_test=True)

def test_ap_ft_mismatching_rrb_r0kh_push_eap(dev, apdev):
    """WPA2-EAP-FT AP over DS with mismatching R0KH key (push)"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2";
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2_r0kh_mismatch(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2";
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True, eap=True)

def test_ap_ft_mismatching_rrb_r0kh_pull_eap(dev, apdev):
    """WPA2-EAP-FT AP over DS with mismatching R0KH key (pull)"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1_r0kh_mismatch(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["pmk_r1_push"] = "0"
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              fail_test=True, eap=True)

def test_ap_ft_gtk_rekey(dev, apdev):
    """WPA2-PSK-FT AP and GTK rekey"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['wpa_group_rekey'] = '1'
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="1", scan_freq="2412")

    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
    if ev is None:
        raise Exception("GTK rekey timed out after initial association")
    hwsim_utils.test_connectivity(dev[0], hapd)

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['wpa_group_rekey'] = '1'
    hapd1 = hostapd.add_ap(apdev[1], params)

    dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
    dev[0].roam(apdev[1]['bssid'])
    if dev[0].get_status_field('bssid') != apdev[1]['bssid']:
        raise Exception("Did not connect to correct AP")
    hwsim_utils.test_connectivity(dev[0], hapd1)

    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
    if ev is None:
        raise Exception("GTK rekey timed out after FT protocol")
    hwsim_utils.test_connectivity(dev[0], hapd1)

def test_ft_psk_key_lifetime_in_memory(dev, apdev, params):
    """WPA2-PSK-FT and key lifetime in memory"""
    ssid = "test-ft"
    passphrase="04c2726b4b8d5f1b4db9c07aa4d9e9d8f765cb5d25ec817e6cc4fcdd5255db0"
    psk = '93c90846ff67af9037ed83fb72b63dbeddaa81d47f926c20909b5886f1d9358d'
    pmk = binascii.unhexlify(psk)
    p = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], p)
    p = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], p)

    pid = find_wpas_process(dev[0])

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")
    # The decrypted copy of GTK is freed only after the CTRL-EVENT-CONNECTED
    # event has been delivered, so verify that wpa_supplicant has returned to
    # eloop before reading process memory.
    time.sleep(1)
    dev[0].ping()

    buf = read_process_memory(pid, pmk)

    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()

    dev[0].relog()
    pmkr0 = None
    pmkr1 = None
    ptk = None
    gtk = None
    with open(os.path.join(params['logdir'], 'log0'), 'r') as f:
        for l in f.readlines():
            if "FT: PMK-R0 - hexdump" in l:
                val = l.strip().split(':')[3].replace(' ', '')
                pmkr0 = binascii.unhexlify(val)
            if "FT: PMK-R1 - hexdump" in l:
                val = l.strip().split(':')[3].replace(' ', '')
                pmkr1 = binascii.unhexlify(val)
            if "FT: KCK - hexdump" in l:
                val = l.strip().split(':')[3].replace(' ', '')
                kck = binascii.unhexlify(val)
            if "FT: KEK - hexdump" in l:
                val = l.strip().split(':')[3].replace(' ', '')
                kek = binascii.unhexlify(val)
            if "FT: TK - hexdump" in l:
                val = l.strip().split(':')[3].replace(' ', '')
                tk = binascii.unhexlify(val)
            if "WPA: Group Key - hexdump" in l:
                val = l.strip().split(':')[3].replace(' ', '')
                gtk = binascii.unhexlify(val)
    if not pmkr0 or not pmkr1 or not kck or not kek or not tk or not gtk:
        raise Exception("Could not find keys from debug log")
    if len(gtk) != 16:
        raise Exception("Unexpected GTK length")

    logger.info("Checking keys in memory while associated")
    get_key_locations(buf, pmk, "PMK")
    get_key_locations(buf, pmkr0, "PMK-R0")
    get_key_locations(buf, pmkr1, "PMK-R1")
    if pmk not in buf:
        raise HwsimSkip("PMK not found while associated")
    if pmkr0 not in buf:
        raise HwsimSkip("PMK-R0 not found while associated")
    if pmkr1 not in buf:
        raise HwsimSkip("PMK-R1 not found while associated")
    if kck not in buf:
        raise Exception("KCK not found while associated")
    if kek not in buf:
        raise Exception("KEK not found while associated")
    #if tk in buf:
    #    raise Exception("TK found from memory")

    logger.info("Checking keys in memory after disassociation")
    buf = read_process_memory(pid, pmk)
    get_key_locations(buf, pmk, "PMK")
    get_key_locations(buf, pmkr0, "PMK-R0")
    get_key_locations(buf, pmkr1, "PMK-R1")

    # Note: PMK/PSK is still present in network configuration

    fname = os.path.join(params['logdir'],
                         'ft_psk_key_lifetime_in_memory.memctx-')
    verify_not_present(buf, pmkr0, fname, "PMK-R0")
    verify_not_present(buf, pmkr1, fname, "PMK-R1")
    verify_not_present(buf, kck, fname, "KCK")
    verify_not_present(buf, kek, fname, "KEK")
    verify_not_present(buf, tk, fname, "TK")
    if gtk in buf:
        get_key_locations(buf, gtk, "GTK")
    verify_not_present(buf, gtk, fname, "GTK")

    dev[0].request("REMOVE_NETWORK all")

    logger.info("Checking keys in memory after network profile removal")
    buf = read_process_memory(pid, pmk)
    get_key_locations(buf, pmk, "PMK")
    get_key_locations(buf, pmkr0, "PMK-R0")
    get_key_locations(buf, pmkr1, "PMK-R1")

    verify_not_present(buf, pmk, fname, "PMK")
    verify_not_present(buf, pmkr0, fname, "PMK-R0")
    verify_not_present(buf, pmkr1, fname, "PMK-R1")
    verify_not_present(buf, kck, fname, "KCK")
    verify_not_present(buf, kek, fname, "KEK")
    verify_not_present(buf, tk, fname, "TK")
    verify_not_present(buf, gtk, fname, "GTK")

@remote_compatible
def test_ap_ft_invalid_resp(dev, apdev):
    """WPA2-PSK-FT AP and invalid response IEs"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    tests = [
        # Various IEs for test coverage. The last one is FTIE with invalid
        # R1KH-ID subelement.
        "020002000000" + "3800" + "38051122334455" + "3754000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010100",
        # FTIE with invalid R0KH-ID subelement (len=0).
        "020002000000" + "3754000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010300",
        # FTIE with invalid R0KH-ID subelement (len=49).
        "020002000000" + "378500010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001033101020304050607080910111213141516171819202122232425262728293031323334353637383940414243444546474849",
        # Invalid RSNE.
        "020002000000" + "3000",
        # Required IEs missing from protected IE count.
        "020002000000" + "3603a1b201" + "375200010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001" + "3900",
        # RIC missing from protected IE count.
        "020002000000" + "3603a1b201" + "375200020203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001" + "3900",
        # Protected IE missing.
        "020002000000" + "3603a1b201" + "375200ff0203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001" + "3900" + "0000" ]
    for t in tests:
        dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
        hapd1.set("ext_mgmt_frame_handling", "1")
        hapd1.dump_monitor()
        if "OK" not in dev[0].request("ROAM " + apdev[1]['bssid']):
            raise Exception("ROAM failed")
        auth = None
        for i in range(20):
            msg = hapd1.mgmt_rx()
            if msg['subtype'] == 11:
                auth = msg
                break
        if not auth:
            raise Exception("Authentication frame not seen")

        resp = {}
        resp['fc'] = auth['fc']
        resp['da'] = auth['sa']
        resp['sa'] = auth['da']
        resp['bssid'] = auth['bssid']
        resp['payload'] = binascii.unhexlify(t)
        hapd1.mgmt_tx(resp)
        hapd1.set("ext_mgmt_frame_handling", "0")
        dev[0].wait_disconnected()

        dev[0].request("RECONNECT")
        dev[0].wait_connected()

def test_ap_ft_gcmp_256(dev, apdev):
    """WPA2-PSK-FT AP with GCMP-256 cipher"""
    if "GCMP-256" not in dev[0].get_capability("pairwise"):
        raise HwsimSkip("Cipher GCMP-256 not supported")
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['rsn_pairwise'] = "GCMP-256"
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['rsn_pairwise'] = "GCMP-256"
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase,
              pairwise_cipher="GCMP-256", group_cipher="GCMP-256")

def setup_ap_ft_oom(dev, apdev):
    skip_with_fips(dev[0])
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")
    if dev[0].get_status_field('bssid') == apdev[0]['bssid']:
        dst = apdev[1]['bssid']
    else:
        dst = apdev[0]['bssid']

    dev[0].scan_for_bss(dst, freq="2412")

    return dst

def test_ap_ft_oom(dev, apdev):
    """WPA2-PSK-FT and OOM"""
    dst = setup_ap_ft_oom(dev, apdev)
    with alloc_fail(dev[0], 1, "wpa_ft_gen_req_ies"):
        dev[0].roam(dst)

def test_ap_ft_oom2(dev, apdev):
    """WPA2-PSK-FT and OOM (2)"""
    dst = setup_ap_ft_oom(dev, apdev)
    with fail_test(dev[0], 1, "wpa_ft_mic"):
        dev[0].roam(dst, fail_test=True, assoc_reject_ok=True)

def test_ap_ft_oom3(dev, apdev):
    """WPA2-PSK-FT and OOM (3)"""
    dst = setup_ap_ft_oom(dev, apdev)
    with fail_test(dev[0], 1, "os_get_random;wpa_ft_prepare_auth_request"):
        dev[0].roam(dst)

def test_ap_ft_oom4(dev, apdev):
    """WPA2-PSK-FT and OOM (4)"""
    ssid = "test-ft"
    passphrase="12345678"
    dst = setup_ap_ft_oom(dev, apdev)
    dev[0].request("REMOVE_NETWORK all")
    with alloc_fail(dev[0], 1, "=sme_update_ft_ies"):
        dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                       scan_freq="2412")

def test_ap_ft_ap_oom(dev, apdev):
    """WPA2-PSK-FT and AP OOM"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    with alloc_fail(hapd0, 1, "wpa_ft_store_pmk_r0"):
        dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                       scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    # This roam will fail due to missing PMK-R0 (OOM prevented storing it)
    dev[0].roam(bssid1)

def test_ap_ft_ap_oom2(dev, apdev):
    """WPA2-PSK-FT and AP OOM 2"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    with alloc_fail(hapd0, 1, "wpa_ft_store_pmk_r1"):
        dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                       scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    dev[0].roam(bssid1)
    if dev[0].get_status_field('bssid') != bssid1:
        raise Exception("Did not roam to AP1")
    # This roam will fail due to missing PMK-R1 (OOM prevented storing it)
    dev[0].roam(bssid0)

def test_ap_ft_ap_oom3(dev, apdev):
    """WPA2-PSK-FT and AP OOM 3"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with alloc_fail(hapd1, 1, "wpa_ft_pull_pmk_r1"):
        # This will fail due to not being able to send out PMK-R1 pull request
        dev[0].roam(bssid1)

    with fail_test(hapd1, 2, "os_get_random;wpa_ft_pull_pmk_r1"):
        # This will fail due to not being able to send out PMK-R1 pull request
        dev[0].roam(bssid1)

    with fail_test(hapd1, 2, "aes_siv_encrypt;wpa_ft_pull_pmk_r1"):
        # This will fail due to not being able to send out PMK-R1 pull request
        dev[0].roam(bssid1)

def test_ap_ft_ap_oom3b(dev, apdev):
    """WPA2-PSK-FT and AP OOM 3b"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with fail_test(hapd1, 1, "os_get_random;wpa_ft_pull_pmk_r1"):
        # This will fail due to not being able to send out PMK-R1 pull request
        dev[0].roam(bssid1)

def test_ap_ft_ap_oom4(dev, apdev):
    """WPA2-PSK-FT and AP OOM 4"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with alloc_fail(hapd1, 1, "wpa_ft_gtk_subelem"):
        dev[0].roam(bssid1)
        if dev[0].get_status_field('bssid') != bssid1:
            raise Exception("Did not roam to AP1")

    with fail_test(hapd0, 1, "wpa_auth_get_seqnum;wpa_ft_gtk_subelem"):
        dev[0].roam(bssid0)
        if dev[0].get_status_field('bssid') != bssid0:
            raise Exception("Did not roam to AP0")

    with fail_test(hapd0, 1, "aes_wrap;wpa_ft_gtk_subelem"):
        dev[0].roam(bssid1)
        if dev[0].get_status_field('bssid') != bssid1:
            raise Exception("Did not roam to AP1")

def test_ap_ft_ap_oom5(dev, apdev):
    """WPA2-PSK-FT and AP OOM 5"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with alloc_fail(hapd1, 1, "=wpa_ft_process_auth_req"):
        # This will fail to roam
        dev[0].roam(bssid1)

    with fail_test(hapd1, 1, "os_get_random;wpa_ft_process_auth_req"):
        # This will fail to roam
        dev[0].roam(bssid1)

    with fail_test(hapd1, 1, "sha256_prf_bits;wpa_pmk_r1_to_ptk;wpa_ft_process_auth_req"):
        # This will fail to roam
        dev[0].roam(bssid1)

    with fail_test(hapd1, 3, "wpa_pmk_r1_to_ptk;wpa_ft_process_auth_req"):
        # This will fail to roam
        dev[0].roam(bssid1)

    with fail_test(hapd1, 1, "wpa_derive_pmk_r1_name;wpa_ft_process_auth_req"):
        # This will fail to roam
        dev[0].roam(bssid1)

def test_ap_ft_ap_oom6(dev, apdev):
    """WPA2-PSK-FT and AP OOM 6"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    with fail_test(hapd0, 1, "wpa_derive_pmk_r0;wpa_auth_derive_ptk_ft"):
        dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                       scan_freq="2412")
    dev[0].request("REMOVE_NETWORK all")
    dev[0].wait_disconnected()
    with fail_test(hapd0, 1, "wpa_derive_pmk_r1;wpa_auth_derive_ptk_ft"):
        dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                       scan_freq="2412")
    dev[0].request("REMOVE_NETWORK all")
    dev[0].wait_disconnected()
    with fail_test(hapd0, 1, "wpa_pmk_r1_to_ptk;wpa_auth_derive_ptk_ft"):
        dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                       scan_freq="2412")

def test_ap_ft_ap_oom7a(dev, apdev):
    """WPA2-PSK-FT and AP OOM 7a"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="2", scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with alloc_fail(hapd1, 1, "wpa_ft_igtk_subelem"):
        # This will fail to roam
        dev[0].roam(bssid1)

def test_ap_ft_ap_oom7b(dev, apdev):
    """WPA2-PSK-FT and AP OOM 7b"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="2", scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with fail_test(hapd1, 1, "aes_wrap;wpa_ft_igtk_subelem"):
        # This will fail to roam
        dev[0].roam(bssid1)

def test_ap_ft_ap_oom7c(dev, apdev):
    """WPA2-PSK-FT and AP OOM 7c"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="2", scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with alloc_fail(hapd1, 1, "=wpa_sm_write_assoc_resp_ies"):
        # This will fail to roam
        dev[0].roam(bssid1)

def test_ap_ft_ap_oom7d(dev, apdev):
    """WPA2-PSK-FT and AP OOM 7d"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="2", scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2"
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with fail_test(hapd1, 1, "wpa_ft_mic;wpa_sm_write_assoc_resp_ies"):
        # This will fail to roam
        dev[0].roam(bssid1)

def test_ap_ft_ap_oom8(dev, apdev):
    """WPA2-PSK-FT and AP OOM 8"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['ft_psk_generate_local'] = "1";
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['ft_psk_generate_local'] = "1";
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")
    with fail_test(hapd1, 1, "wpa_derive_pmk_r0;wpa_ft_psk_pmk_r1"):
        # This will fail to roam
        dev[0].roam(bssid1)
    with fail_test(hapd1, 1, "wpa_derive_pmk_r1;wpa_ft_psk_pmk_r1"):
        # This will fail to roam
        dev[0].roam(bssid1)

def test_ap_ft_ap_oom9(dev, apdev):
    """WPA2-PSK-FT and AP OOM 9"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")

    with alloc_fail(hapd0, 1, "wpa_ft_action_rx"):
        # This will fail to roam
        if "OK" not in dev[0].request("FT_DS " + bssid1):
            raise Exception("FT_DS failed")
        wait_fail_trigger(hapd0, "GET_ALLOC_FAIL")

    with alloc_fail(hapd1, 1, "wpa_ft_rrb_rx_request"):
        # This will fail to roam
        if "OK" not in dev[0].request("FT_DS " + bssid1):
            raise Exception("FT_DS failed")
        wait_fail_trigger(hapd1, "GET_ALLOC_FAIL")

    with alloc_fail(hapd1, 1, "wpa_ft_send_rrb_auth_resp"):
        # This will fail to roam
        if "OK" not in dev[0].request("FT_DS " + bssid1):
            raise Exception("FT_DS failed")
        wait_fail_trigger(hapd1, "GET_ALLOC_FAIL")

def test_ap_ft_ap_oom10(dev, apdev):
    """WPA2-PSK-FT and AP OOM 10"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    dev[0].scan_for_bss(bssid1, freq="2412")

    with fail_test(hapd0, 1, "aes_siv_decrypt;wpa_ft_rrb_rx_pull"):
        # This will fail to roam
        if "OK" not in dev[0].request("FT_DS " + bssid1):
            raise Exception("FT_DS failed")
        wait_fail_trigger(hapd0, "GET_FAIL")

    with fail_test(hapd0, 1, "wpa_derive_pmk_r1;wpa_ft_rrb_rx_pull"):
        # This will fail to roam
        if "OK" not in dev[0].request("FT_DS " + bssid1):
            raise Exception("FT_DS failed")
        wait_fail_trigger(hapd0, "GET_FAIL")

    with fail_test(hapd0, 1, "aes_siv_encrypt;wpa_ft_rrb_rx_pull"):
        # This will fail to roam
        if "OK" not in dev[0].request("FT_DS " + bssid1):
            raise Exception("FT_DS failed")
        wait_fail_trigger(hapd0, "GET_FAIL")

    with fail_test(hapd1, 1, "aes_siv_decrypt;wpa_ft_rrb_rx_resp"):
        # This will fail to roam
        if "OK" not in dev[0].request("FT_DS " + bssid1):
            raise Exception("FT_DS failed")
        wait_fail_trigger(hapd1, "GET_FAIL")

def test_ap_ft_ap_oom11(dev, apdev):
    """WPA2-PSK-FT and AP OOM 11"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    dev[0].scan_for_bss(bssid0, freq="2412")
    with fail_test(hapd0, 1, "wpa_derive_pmk_r1;wpa_ft_generate_pmk_r1"):
        dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                       scan_freq="2412")
        wait_fail_trigger(hapd0, "GET_FAIL")

    dev[1].scan_for_bss(bssid0, freq="2412")
    with fail_test(hapd0, 1, "aes_siv_encrypt;wpa_ft_generate_pmk_r1"):
        dev[1].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                       scan_freq="2412")
        wait_fail_trigger(hapd0, "GET_FAIL")

def test_ap_ft_over_ds_proto_ap(dev, apdev):
    """WPA2-PSK-FT AP over DS protocol testing for AP processing"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()
    _bssid0 = bssid0.replace(':', '')
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")
    addr = dev[0].own_addr()
    _addr = addr.replace(':', '')

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()
    _bssid1 = bssid1.replace(':', '')

    hapd0.set("ext_mgmt_frame_handling", "1")
    hdr = "d0003a01" + _bssid0 + _addr + _bssid0 + "1000"
    valid = "0601" + _addr + _bssid1
    tests = [ "0601",
              "0601" + _addr,
              "0601" + _addr + _bssid0,
              "0601" + _addr + "ffffffffffff",
              "0601" + _bssid0 + _bssid0,
              valid,
              valid + "01",
              valid + "3700",
              valid + "3600",
              valid + "3603ffffff",
              valid + "3603a1b2ff",
              valid + "3603a1b2ff" + "3700",
              valid + "3603a1b2ff" + "37520000" + 16*"00" + 32*"00" + 32*"00",
              valid + "3603a1b2ff" + "37520001" + 16*"00" + 32*"00" + 32*"00",
              valid + "3603a1b2ff" + "37550000" + 16*"00" + 32*"00" + 32*"00" + "0301aa",
              valid + "3603a1b2ff" + "37550000" + 16*"00" + 32*"00" + 32*"00" + "0301aa" + "3000",
              valid + "3603a1b2ff" + "37550000" + 16*"00" + 32*"00" + 32*"00" + "0301aa" + "30260100000fac040100000fac040100000facff00000100a225368fe0983b5828a37a0acb37f253",
              valid + "3603a1b2ff" + "37550000" + 16*"00" + 32*"00" + 32*"00" + "0301aa" + "30260100000fac040100000fac030100000fac0400000100a225368fe0983b5828a37a0acb37f253",
              valid + "3603a1b2ff" + "37550000" + 16*"00" + 32*"00" + 32*"00" + "0301aa" + "30260100000fac040100000fac040100000fac0400000100a225368fe0983b5828a37a0acb37f253",
              valid + "0001" ]
    for t in tests:
        hapd0.dump_monitor()
        if "OK" not in hapd0.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + t):
            raise Exception("MGMT_RX_PROCESS failed")

    hapd0.set("ext_mgmt_frame_handling", "0")

def test_ap_ft_over_ds_proto(dev, apdev):
    """WPA2-PSK-FT AP over DS protocol testing"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    # FT Action Response while no FT-over-DS in progress
    msg = {}
    msg['fc'] = 13 << 4
    msg['da'] = dev[0].own_addr()
    msg['sa'] = apdev[0]['bssid']
    msg['bssid'] = apdev[0]['bssid']
    msg['payload'] = binascii.unhexlify("06020200000000000200000004000000")
    hapd0.mgmt_tx(msg)

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)
    dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
    hapd0.set("ext_mgmt_frame_handling", "1")
    hapd0.dump_monitor()
    dev[0].request("FT_DS " + apdev[1]['bssid'])
    for i in range(0, 10):
        req = hapd0.mgmt_rx()
        if req is None:
            raise Exception("MGMT RX wait timed out")
        if req['subtype'] == 13:
            break
        req = None
    if not req:
        raise Exception("FT Action frame not received")

    # FT Action Response for unexpected Target AP
    msg['payload'] = binascii.unhexlify("0602020000000000" + "f20000000400" + "0000")
    hapd0.mgmt_tx(msg)

    # FT Action Response without MDIE
    msg['payload'] = binascii.unhexlify("0602020000000000" + "020000000400" + "0000")
    hapd0.mgmt_tx(msg)

    # FT Action Response without FTIE
    msg['payload'] = binascii.unhexlify("0602020000000000" + "020000000400" + "0000" + "3603a1b201")
    hapd0.mgmt_tx(msg)

    # FT Action Response with FTIE SNonce mismatch
    msg['payload'] = binascii.unhexlify("0602020000000000" + "020000000400" + "0000" + "3603a1b201" + "3766000000000000000000000000000000000000c4e67ac1999bebd00ff4ae4d5dcaf87896bb060b469f7c78d49623fb395c3455ffffff6b693fe6f8d8c5dfac0a22344750775bd09437f98b238c9f87b97f790c0106000102030406030a6e6173312e77312e6669")
    hapd0.mgmt_tx(msg)

@remote_compatible
def test_ap_ft_rrb(dev, apdev):
    """WPA2-PSK-FT RRB protocol testing"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")

    _dst_ll = binascii.unhexlify(apdev[0]['bssid'].replace(':',''))
    _src_ll = binascii.unhexlify(dev[0].own_addr().replace(':',''))
    proto = '\x89\x0d'
    ehdr = _dst_ll + _src_ll + proto

    # Too short RRB frame
    pkt = ehdr + '\x01'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # RRB discarded frame wikth unrecognized type
    pkt = ehdr + '\x02' + '\x02' + '\x01\x00' + _src_ll
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # RRB frame too short for action frame
    pkt = ehdr + '\x01' + '\x02' + '\x01\x00' + _src_ll
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # Too short RRB frame (not enough room for Action Frame body)
    pkt = ehdr + '\x01' + '\x02' + '\x00\x00' + _src_ll
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # Unexpected Action frame category
    pkt = ehdr + '\x01' + '\x02' + '\x0e\x00' + _src_ll + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # Unexpected Action in RRB Request
    pkt = ehdr + '\x01' + '\x00' + '\x0e\x00' + _src_ll + '\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # Target AP address in RRB Request does not match with own address
    pkt = ehdr + '\x01' + '\x00' + '\x0e\x00' + _src_ll + '\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # Not enough room for status code in RRB Response
    pkt = ehdr + '\x01' + '\x01' + '\x0e\x00' + _src_ll + '\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # RRB discarded frame with unknown packet_type
    pkt = ehdr + '\x01' + '\x02' + '\x0e\x00' + _src_ll + '\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # RRB Response with non-zero status code; no STA match
    pkt = ehdr + '\x01' + '\x01' + '\x10\x00' + _src_ll + '\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + '\xff\xff'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # RRB Response with zero status code and extra data; STA match
    pkt = ehdr + '\x01' + '\x01' + '\x11\x00' + _src_ll + '\x06\x01' + _src_ll + '\x00\x00\x00\x00\x00\x00' + '\x00\x00' + '\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # Too short PMK-R1 pull
    pkt = ehdr + '\x01' + '\xc8' + '\x0e\x00' + _src_ll + '\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # Too short PMK-R1 resp
    pkt = ehdr + '\x01' + '\xc9' + '\x0e\x00' + _src_ll + '\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # Too short PMK-R1 push
    pkt = ehdr + '\x01' + '\xca' + '\x0e\x00' + _src_ll + '\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

    # No matching R0KH address found for PMK-R0 pull response
    pkt = ehdr + '\x01' + '\xc9' + '\x5a\x00' + _src_ll + '\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + 76*'\00'
    if "OK" not in dev[0].request("DATA_TEST_FRAME " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

@remote_compatible
def test_rsn_ie_proto_ft_psk_sta(dev, apdev):
    """RSN element protocol testing for FT-PSK + PMF cases on STA side"""
    bssid = apdev[0]['bssid']
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "1"
    # This is the RSN element used normally by hostapd
    params['own_ie_override'] = '30140100000fac040100000fac040100000fac048c00' + '3603a1b201'
    hapd = hostapd.add_ap(apdev[0], params)
    id = dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                        ieee80211w="1", scan_freq="2412",
                        pairwise="CCMP", group="CCMP")

    tests = [ ('PMKIDCount field included',
               '30160100000fac040100000fac040100000fac048c000000' + '3603a1b201'),
              ('Extra IE before RSNE',
               'dd0400000000' + '30140100000fac040100000fac040100000fac048c00' + '3603a1b201'),
              ('PMKIDCount and Group Management Cipher suite fields included',
               '301a0100000fac040100000fac040100000fac048c000000000fac06' + '3603a1b201'),
              ('Extra octet after defined fields (future extensibility)',
               '301b0100000fac040100000fac040100000fac048c000000000fac0600' + '3603a1b201'),
              ('No RSN Capabilities field (PMF disabled in practice)',
               '30120100000fac040100000fac040100000fac04' + '3603a1b201') ]
    for txt,ie in tests:
        dev[0].request("DISCONNECT")
        dev[0].wait_disconnected()
        logger.info(txt)
        hapd.disable()
        hapd.set('own_ie_override', ie)
        hapd.enable()
        dev[0].request("BSS_FLUSH 0")
        dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
        dev[0].select_network(id, freq=2412)
        dev[0].wait_connected()

    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()

    logger.info('Invalid RSNE causing internal hostapd error')
    hapd.disable()
    hapd.set('own_ie_override', '30130100000fac040100000fac040100000fac048c' + '3603a1b201')
    hapd.enable()
    dev[0].request("BSS_FLUSH 0")
    dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
    dev[0].select_network(id, freq=2412)
    # hostapd fails to generate EAPOL-Key msg 3/4, so this connection cannot
    # complete.
    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected connection")
    dev[0].request("DISCONNECT")

    logger.info('Unexpected PMKID causing internal hostapd error')
    hapd.disable()
    hapd.set('own_ie_override', '30260100000fac040100000fac040100000fac048c000100ffffffffffffffffffffffffffffffff' + '3603a1b201')
    hapd.enable()
    dev[0].request("BSS_FLUSH 0")
    dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)
    dev[0].select_network(id, freq=2412)
    # hostapd fails to generate EAPOL-Key msg 3/4, so this connection cannot
    # complete.
    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected connection")
    dev[0].request("DISCONNECT")

def test_ap_ft_ptk_rekey(dev, apdev):
    """WPA2-PSK-FT PTK rekeying triggered by station after roam"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, ptk_rekey="1")

    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED",
                            "WPA: Key negotiation completed"], timeout=5)
    if ev is None:
        raise Exception("No event received after roam")
    if "CTRL-EVENT-DISCONNECTED" in ev:
        raise Exception("Unexpected disconnection after roam")

    if dev[0].get_status_field('bssid') == apdev[0]['bssid']:
        hapd = hapd0
    else:
        hapd = hapd1
    hwsim_utils.test_connectivity(dev[0], hapd)

def test_ap_ft_ptk_rekey_ap(dev, apdev):
    """WPA2-PSK-FT PTK rekeying triggered by AP after roam"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['wpa_ptk_rekey'] = '2'
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params['wpa_ptk_rekey'] = '2'
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase)

    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED",
                            "WPA: Key negotiation completed"], timeout=5)
    if ev is None:
        raise Exception("No event received after roam")
    if "CTRL-EVENT-DISCONNECTED" in ev:
        raise Exception("Unexpected disconnection after roam")

    if dev[0].get_status_field('bssid') == apdev[0]['bssid']:
        hapd = hapd0
    else:
        hapd = hapd1
    hwsim_utils.test_connectivity(dev[0], hapd)

def test_ap_ft_internal_rrb_check(dev, apdev):
    """RRB internal delivery only to WPA enabled BSS"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params['wpa_key_mgmt'] = "FT-EAP"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd = hostapd.add_ap(apdev[0], params)
    key_mgmt = hapd.get_config()['key_mgmt']
    if key_mgmt.split(' ')[0] != "FT-EAP":
        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)

    hapd1 = hostapd.add_ap(apdev[1], { "ssid" : ssid })

    # Connect to WPA enabled AP
    dev[0].connect(ssid, key_mgmt="FT-EAP", proto="WPA2", ieee80211w="1",
                   eap="GPSK", identity="gpsk user",
                   password="abcdefghijklmnop0123456789abcdef",
                   scan_freq="2412")

    # Try over_ds roaming to non-WPA-enabled AP.
    # If hostapd does not check hapd->wpa_auth internally, it will crash now.
    dev[0].roam_over_ds(apdev[1]['bssid'], fail_test=True)

def test_ap_ft_extra_ie(dev, apdev):
    """WPA2-PSK-FT AP with WPA2-PSK enabled and unexpected MDE"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["wpa_key_mgmt"] = "WPA-PSK FT-PSK"
    hapd0 = hostapd.add_ap(apdev[0], params)
    dev[1].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")
    dev[2].connect(ssid, psk=passphrase, key_mgmt="WPA-PSK", proto="WPA2",
                   scan_freq="2412")
    try:
        # Add Mobility Domain element to test AP validation code.
        dev[0].request("VENDOR_ELEM_ADD 13 3603a1b201")
        dev[0].connect(ssid, psk=passphrase, key_mgmt="WPA-PSK", proto="WPA2",
                       scan_freq="2412", wait_connect=False)
        ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
                                "CTRL-EVENT-ASSOC-REJECT"], timeout=10)
        if ev is None:
            raise Exception("No connection result")
        if "CTRL-EVENT-CONNECTED" in ev:
            raise Exception("Non-FT association accepted with MDE")
        if "status_code=43" not in ev:
            raise Exception("Unexpected status code: " + ev)
        dev[0].request("DISCONNECT")
    finally:
        dev[0].request("VENDOR_ELEM_REMOVE 13 *")

def test_ap_ft_ric(dev, apdev):
    """WPA2-PSK-FT AP and RIC"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    dev[0].set("ric_ies", "")
    dev[0].set("ric_ies", '""')
    if "FAIL" not in dev[0].request("SET ric_ies q"):
        raise Exception("Invalid ric_ies value accepted")

    tests = [ "3900",
              "3900ff04eeeeeeee",
              "390400000000",
              "390400000000" + "390400000000",
              "390400000000" + "dd050050f20202",
              "390400000000" + "dd3d0050f2020201" + 55*"00",
              "390400000000" + "dd3d0050f2020201aa300010270000000000000000000000000000000000000000000000000000ffffff7f00000000000000000000000040420f00ffff0000",
              "390401010000" + "dd3d0050f2020201aa3000dc050000000000000000000000000000000000000000000000000000dc050000000000000000000000000000808d5b0028230000" ]
    for t in tests:
        dev[0].set("ric_ies", t)
        run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase,
                  test_connectivity=False)
        dev[0].request("REMOVE_NETWORK all")
        dev[0].wait_disconnected()
        dev[0].dump_monitor()

def ie_hex(ies, id):
    return binascii.hexlify(struct.pack('BB', id, len(ies[id])) + ies[id])

def test_ap_ft_reassoc_proto(dev, apdev):
    """WPA2-PSK-FT AP Reassociation Request frame parsing"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="1", scan_freq="2412")
    if dev[0].get_status_field('bssid') == hapd0.own_addr():
        hapd1ap = hapd0
        hapd2ap = hapd1
    else:
        hapd1ap = hapd1
        hapd2ap = hapd0

    dev[0].scan_for_bss(hapd2ap.own_addr(), freq="2412")
    hapd2ap.set("ext_mgmt_frame_handling", "1")
    dev[0].request("ROAM " + hapd2ap.own_addr())

    while True:
        req = hapd2ap.mgmt_rx()
        hapd2ap.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + binascii.hexlify(req['frame']))
        if req['subtype'] == 11:
            break

    while True:
        req = hapd2ap.mgmt_rx()
        if req['subtype'] == 2:
            break
        hapd2ap.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + binascii.hexlify(req['frame']))

    # IEEE 802.11 header + fixed fields before IEs
    hdr = binascii.hexlify(req['frame'][0:34])
    ies = parse_ie(binascii.hexlify(req['frame'][34:]))
    # First elements: SSID, Supported Rates, Extended Supported Rates
    ies1 = ie_hex(ies, 0) + ie_hex(ies, 1) + ie_hex(ies, 50)

    rsne = ie_hex(ies, 48)
    mde = ie_hex(ies, 54)
    fte = ie_hex(ies, 55)
    tests = [ ]
    # RSN: Trying to use FT, but MDIE not included
    tests += [ rsne ]
    # RSN: Attempted to use unknown MDIE
    tests += [ rsne + "3603000000" ]
    # Invalid RSN pairwise cipher
    tests += [ "30260100000fac040100000fac030100000fac040000010029208a42cd25c85aa571567dce10dae3" ]
    # FT: No PMKID in RSNIE
    tests += [ "30160100000fac040100000fac040100000fac0400000000" + ie_hex(ies, 54) ]
    # FT: Invalid FTIE
    tests += [ rsne + mde ]
    # FT: RIC IE(s) in the frame, but not included in protected IE count
    # FT: Failed to parse FT IEs
    tests += [ rsne + mde + fte + "3900" ]
    # FT: SNonce mismatch in FTIE
    tests += [ rsne + mde + "37520000" + 16*"00" + 32*"00" + 32*"00" ]
    # FT: ANonce mismatch in FTIE
    tests += [ rsne + mde + fte[0:40] + 32*"00" + fte[104:] ]
    # FT: No R0KH-ID subelem in FTIE
    tests += [ rsne + mde + "3752" + fte[4:168] ]
    # FT: R0KH-ID in FTIE did not match with the current R0KH-ID
    tests += [ rsne + mde + "3755" + fte[4:168] + "0301ff" ]
    # FT: No R1KH-ID subelem in FTIE
    tests += [ rsne + mde + "375e" + fte[4:168] + "030a" + "nas1.w1.fi".encode("hex") ]
    # FT: Unknown R1KH-ID used in ReassocReq
    tests += [ rsne + mde + "3766" + fte[4:168] + "030a" + "nas1.w1.fi".encode("hex") + "0106000000000000" ]
    # FT: PMKID in Reassoc Req did not match with the PMKR1Name derived from auth request
    tests += [ rsne[:-32] + 16*"00" + mde + fte ]
    # Invalid MIC in FTIE
    tests += [ rsne + mde + fte[0:8] + 16*"00" + fte[40:] ]
    for t in tests:
        hapd2ap.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + ies1 + t)

def test_ap_ft_reassoc_local_fail(dev, apdev):
    """WPA2-PSK-FT AP Reassociation Request frame and local failure"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="1", scan_freq="2412")
    if dev[0].get_status_field('bssid') == hapd0.own_addr():
        hapd1ap = hapd0
        hapd2ap = hapd1
    else:
        hapd1ap = hapd1
        hapd2ap = hapd0

    dev[0].scan_for_bss(hapd2ap.own_addr(), freq="2412")
    # FT: Failed to calculate MIC
    with fail_test(hapd2ap, 1, "wpa_ft_validate_reassoc"):
        dev[0].request("ROAM " + hapd2ap.own_addr())
        ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
        dev[0].request("DISCONNECT")
        if ev is None:
            raise Exception("Association reject not seen")

def test_ap_ft_reassoc_replay(dev, apdev, params):
    """WPA2-PSK-FT AP and replayed Reassociation Request frame"""
    capfile = os.path.join(params['logdir'], "hwsim0.pcapng")
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    hapd1 = hostapd.add_ap(apdev[1], params)

    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")
    if dev[0].get_status_field('bssid') == hapd0.own_addr():
        hapd1ap = hapd0
        hapd2ap = hapd1
    else:
        hapd1ap = hapd1
        hapd2ap = hapd0

    dev[0].scan_for_bss(hapd2ap.own_addr(), freq="2412")
    hapd2ap.set("ext_mgmt_frame_handling", "1")
    dev[0].dump_monitor()
    if "OK" not in dev[0].request("ROAM " + hapd2ap.own_addr()):
        raise Exception("ROAM failed")

    reassocreq = None
    count = 0
    while count < 100:
        req = hapd2ap.mgmt_rx()
        count += 1
        hapd2ap.dump_monitor()
        hapd2ap.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + binascii.hexlify(req['frame']))
        if req['subtype'] == 2:
            reassocreq = req
            ev = hapd2ap.wait_event(["MGMT-TX-STATUS"], timeout=5)
            if ev is None:
                raise Exception("No TX status seen")
            cmd = "MGMT_TX_STATUS_PROCESS %s" % (" ".join(ev.split(' ')[1:4]))
            if "OK" not in hapd2ap.request(cmd):
                raise Exception("MGMT_TX_STATUS_PROCESS failed")
            break
    hapd2ap.set("ext_mgmt_frame_handling", "0")
    if reassocreq is None:
        raise Exception("No Reassociation Request frame seen")
    dev[0].wait_connected()
    dev[0].dump_monitor()
    hapd2ap.dump_monitor()

    hwsim_utils.test_connectivity(dev[0], hapd2ap)

    logger.info("Replay the last Reassociation Request frame")
    hapd2ap.dump_monitor()
    hapd2ap.set("ext_mgmt_frame_handling", "1")
    hapd2ap.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + binascii.hexlify(req['frame']))
    ev = hapd2ap.wait_event(["MGMT-TX-STATUS"], timeout=5)
    if ev is None:
        raise Exception("No TX status seen")
    cmd = "MGMT_TX_STATUS_PROCESS %s" % (" ".join(ev.split(' ')[1:4]))
    if "OK" not in hapd2ap.request(cmd):
        raise Exception("MGMT_TX_STATUS_PROCESS failed")
    hapd2ap.set("ext_mgmt_frame_handling", "0")

    try:
        hwsim_utils.test_connectivity(dev[0], hapd2ap)
        ok = True
    except:
        ok = False

    ap = hapd2ap.own_addr()
    sta = dev[0].own_addr()
    filt = "wlan.fc.type == 2 && " + \
           "wlan.da == " + sta + " && " + \
           "wlan.sa == " + ap
    fields = [ "wlan.ccmp.extiv" ]
    res = run_tshark(capfile, filt, fields)
    vals = res.splitlines()
    logger.info("CCMP PN: " + str(vals))
    if len(vals) < 2:
        raise Exception("Could not find all CCMP protected frames from capture")
    if len(set(vals)) < len(vals):
        raise Exception("Duplicate CCMP PN used")

    if not ok:
        raise Exception("The second hwsim connectivity test failed")

def test_ap_ft_psk_file(dev, apdev):
    """WPA2-PSK-FT AP with PSK from a file"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1a(ssid=ssid, passphrase=passphrase)
    params['wpa_psk_file'] = 'hostapd.wpa_psk'
    hapd = hostapd.add_ap(apdev[0], params)

    dev[1].connect(ssid, psk="very secret",
                   key_mgmt="FT-PSK", proto="WPA2", ieee80211w="1",
                   scan_freq="2412", wait_connect=False)
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="1", scan_freq="2412")
    dev[0].request("REMOVE_NETWORK all")
    dev[0].wait_disconnected()
    dev[0].connect(ssid, psk="very secret", key_mgmt="FT-PSK", proto="WPA2",
                   ieee80211w="1", scan_freq="2412")
    dev[0].request("REMOVE_NETWORK all")
    dev[0].wait_disconnected()
    dev[0].connect(ssid, psk="secret passphrase",
                   key_mgmt="FT-PSK", proto="WPA2", ieee80211w="1",
                   scan_freq="2412")
    dev[2].connect(ssid, psk="another passphrase for all STAs",
                   key_mgmt="FT-PSK", proto="WPA2", ieee80211w="1",
                   scan_freq="2412")
    ev = dev[1].wait_event(["WPA: 4-Way Handshake failed"], timeout=10)
    if ev is None:
        raise Exception("Timed out while waiting for failure report")
    dev[1].request("REMOVE_NETWORK all")

def test_ap_ft_eap_ap_config_change(dev, apdev):
    """WPA2-EAP-FT AP changing from 802.1X-only to FT-only"""
    ssid = "test-ft"
    passphrase="12345678"
    bssid = apdev[0]['bssid']

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase, discovery=True)
    params['wpa_key_mgmt'] = "WPA-EAP"
    params["ieee8021x"] = "1"
    params["pmk_r1_push"] = "0"
    params["r0kh"] = "ff:ff:ff:ff:ff:ff * 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
    params["r1kh"] = "00:00:00:00:00:00 00:00:00:00:00:00 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
    params["eap_server"] = "0"
    params = dict(radius.items() + params.items())
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect(ssid, key_mgmt="FT-EAP WPA-EAP", proto="WPA2",
                   eap="GPSK", identity="gpsk user",
                   password="abcdefghijklmnop0123456789abcdef",
                   scan_freq="2412")
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()
    dev[0].dump_monitor()

    hapd.disable()
    hapd.set('wpa_key_mgmt', "FT-EAP")
    hapd.enable()

    dev[0].request("BSS_FLUSH 0")
    dev[0].scan_for_bss(bssid, 2412, force_scan=True, only_new=True)

    dev[0].request("RECONNECT")
    dev[0].wait_connected()

def test_ap_ft_eap_sha384(dev, apdev):
    """WPA2-EAP-FT with SHA384"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2";
    params['wpa_key_mgmt'] = "FT-EAP-SHA384"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2";
    params['wpa_key_mgmt'] = "FT-EAP-SHA384"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, eap=True,
              sha384=True)

def test_ap_ft_eap_sha384_over_ds(dev, apdev):
    """WPA2-EAP-FT with SHA384 over DS"""
    ssid = "test-ft"
    passphrase="12345678"

    radius = hostapd.radius_params()
    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2";
    params['wpa_key_mgmt'] = "FT-EAP-SHA384"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd0 = hostapd.add_ap(apdev[0], params)
    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["ieee80211w"] = "2";
    params['wpa_key_mgmt'] = "FT-EAP-SHA384"
    params["ieee8021x"] = "1"
    params = dict(radius.items() + params.items())
    hapd1 = hostapd.add_ap(apdev[1], params)

    run_roams(dev[0], apdev, hapd0, hapd1, ssid, passphrase, over_ds=True,
              eap=True, sha384=True)

def test_ap_ft_roam_rrm(dev, apdev):
    """WPA2-PSK-FT AP and radio measurement request"""
    ssid = "test-ft"
    passphrase="12345678"

    params = ft_params1(ssid=ssid, passphrase=passphrase)
    params["rrm_beacon_report"] = "1"
    hapd0 = hostapd.add_ap(apdev[0], params)
    bssid0 = hapd0.own_addr()

    addr = dev[0].own_addr()
    dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2",
                   scan_freq="2412")
    check_beacon_req(hapd0, addr, 1)

    params = ft_params2(ssid=ssid, passphrase=passphrase)
    params["rrm_beacon_report"] = "1"
    hapd1 = hostapd.add_ap(apdev[1], params)
    bssid1 = hapd1.own_addr()

    dev[0].scan_for_bss(bssid1, freq=2412)
    dev[0].roam(bssid1)
    check_beacon_req(hapd1, addr, 2)

    dev[0].scan_for_bss(bssid0, freq=2412)
    dev[0].roam(bssid0)
    check_beacon_req(hapd0, addr, 3)