aboutsummaryrefslogtreecommitdiffstats
path: root/tests/hwsim/test_radius.py
blob: d62851077b6d734182307fd5614281212c7f3e68 (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
# RADIUS tests
# Copyright (c) 2013-2016, 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 hashlib
import hmac
import logging
logger = logging.getLogger()
import os
import select
import struct
import subprocess
import threading
import time

import hostapd
from utils import HwsimSkip, require_under_vm, skip_with_fips, alloc_fail, fail_test, wait_fail_trigger
from test_ap_hs20 import build_dhcp_ack
from test_ap_ft import ft_params1

def connect(dev, ssid, wait_connect=True):
    dev.connect(ssid, key_mgmt="WPA-EAP", scan_freq="2412",
                eap="PSK", identity="psk.user@example.com",
                password_hex="0123456789abcdef0123456789abcdef",
                wait_connect=wait_connect)

@remote_compatible
def test_radius_auth_unreachable(dev, apdev):
    """RADIUS Authentication server unreachable"""
    params = hostapd.wpa2_eap_params(ssid="radius-auth")
    params['auth_server_port'] = "18139"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-auth", wait_connect=False)
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
    if ev is None:
        raise Exception("Timeout on EAP start")
    logger.info("Checking for RADIUS retries")
    time.sleep(4)
    mib = hapd.get_mib()
    if "radiusAuthClientAccessRequests" not in mib:
        raise Exception("Missing MIB fields")
    if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
        raise Exception("Missing RADIUS Authentication retransmission")
    if int(mib["radiusAuthClientPendingRequests"]) < 1:
        raise Exception("Missing pending RADIUS Authentication request")

def test_radius_auth_unreachable2(dev, apdev):
    """RADIUS Authentication server unreachable (2)"""
    subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
    params = hostapd.wpa2_eap_params(ssid="radius-auth")
    params['auth_server_addr'] = "192.168.213.17"
    params['auth_server_port'] = "18139"
    hapd = hostapd.add_ap(apdev[0], params)
    subprocess.call(['ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
    connect(dev[0], "radius-auth", wait_connect=False)
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
    if ev is None:
        raise Exception("Timeout on EAP start")
    logger.info("Checking for RADIUS retries")
    time.sleep(4)
    mib = hapd.get_mib()
    if "radiusAuthClientAccessRequests" not in mib:
        raise Exception("Missing MIB fields")
    if int(mib["radiusAuthClientAccessRetransmissions"]) < 1:
        raise Exception("Missing RADIUS Authentication retransmission")

def test_radius_auth_unreachable3(dev, apdev):
    """RADIUS Authentication server initially unreachable, but then available"""
    subprocess.call(['ip', 'ro', 'replace', 'blackhole', '192.168.213.18'])
    params = hostapd.wpa2_eap_params(ssid="radius-auth")
    params['auth_server_addr'] = "192.168.213.18"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-auth", wait_connect=False)
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
    if ev is None:
        raise Exception("Timeout on EAP start")
    subprocess.call(['ip', 'ro', 'del', 'blackhole', '192.168.213.18'])
    time.sleep(0.1)
    dev[0].request("DISCONNECT")
    hapd.set('auth_server_addr_replace', '127.0.0.1')
    dev[0].request("RECONNECT")

    dev[0].wait_connected()

def test_radius_acct_unreachable(dev, apdev):
    """RADIUS Accounting server unreachable"""
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "18139"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-acct")
    logger.info("Checking for RADIUS retries")
    time.sleep(4)
    mib = hapd.get_mib()
    if "radiusAccClientRetransmissions" not in mib:
        raise Exception("Missing MIB fields")
    if int(mib["radiusAccClientRetransmissions"]) < 2:
        raise Exception("Missing RADIUS Accounting retransmissions")
    if int(mib["radiusAccClientPendingRequests"]) < 2:
        raise Exception("Missing pending RADIUS Accounting requests")

def test_radius_acct_unreachable2(dev, apdev):
    """RADIUS Accounting server unreachable(2)"""
    subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "192.168.213.17"
    params['acct_server_port'] = "18139"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    subprocess.call(['ip', 'ro', 'del', '192.168.213.17', 'dev', 'lo'])
    connect(dev[0], "radius-acct")
    logger.info("Checking for RADIUS retries")
    time.sleep(4)
    mib = hapd.get_mib()
    if "radiusAccClientRetransmissions" not in mib:
        raise Exception("Missing MIB fields")
    if int(mib["radiusAccClientRetransmissions"]) < 1 and int(mib["radiusAccClientPendingRequests"]) < 1:
        raise Exception("Missing pending or retransmitted RADIUS Accounting requests")

def test_radius_acct_unreachable3(dev, apdev):
    """RADIUS Accounting server initially unreachable, but then available"""
    require_under_vm()
    subprocess.call(['ip', 'ro', 'replace', 'blackhole', '192.168.213.18'])
    as_hapd = hostapd.Hostapd("as")
    as_mib_start = as_hapd.get_mib(param="radius_server")
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "192.168.213.18"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-acct")
    subprocess.call(['ip', 'ro', 'del', 'blackhole', '192.168.213.18'])
    time.sleep(0.1)
    dev[0].request("DISCONNECT")
    hapd.set('acct_server_addr_replace', '127.0.0.1')
    dev[0].request("RECONNECT")
    dev[0].wait_connected()
    time.sleep(1)
    as_mib_end = as_hapd.get_mib(param="radius_server")
    req_s = int(as_mib_start['radiusAccServTotalResponses'])
    req_e = int(as_mib_end['radiusAccServTotalResponses'])
    if req_e <= req_s:
        raise Exception("Unexpected RADIUS server acct MIB value")

def test_radius_acct_unreachable4(dev, apdev):
    """RADIUS Accounting server unreachable and multiple STAs"""
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "18139"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    for i in range(20):
        connect(dev[0], "radius-acct")
        dev[0].request("REMOVE_NETWORK all")
        dev[0].wait_disconnected()

def test_radius_acct(dev, apdev):
    """RADIUS Accounting"""
    as_hapd = hostapd.Hostapd("as")
    as_mib_start = as_hapd.get_mib(param="radius_server")
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    params['radius_auth_req_attr'] = [ "126:s:Operator", "77:s:testing",
                                       "62:d:1" ]
    params['radius_acct_req_attr'] = [ "126:s:Operator", "62:d:1",
                                       "77:s:testing" ]
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-acct")
    dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
                   eap="PAX", identity="test-class",
                   password_hex="0123456789abcdef0123456789abcdef")
    dev[2].connect("radius-acct", key_mgmt="WPA-EAP",
                   eap="GPSK", identity="gpsk-cui",
                   password="abcdefghijklmnop0123456789abcdef",
                   scan_freq="2412")
    logger.info("Checking for RADIUS counters")
    count = 0
    while True:
        mib = hapd.get_mib()
        if int(mib['radiusAccClientResponses']) >= 3:
            break
        time.sleep(0.1)
        count += 1
        if count > 10:
            raise Exception("Did not receive Accounting-Response packets")

    if int(mib['radiusAccClientRetransmissions']) > 0:
        raise Exception("Unexpected Accounting-Request retransmission")

    as_mib_end = as_hapd.get_mib(param="radius_server")

    req_s = int(as_mib_start['radiusAccServTotalRequests'])
    req_e = int(as_mib_end['radiusAccServTotalRequests'])
    if req_e < req_s + 2:
        raise Exception("Unexpected RADIUS server acct MIB value")

    acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
    acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
    if acc_e < acc_s + 1:
        raise Exception("Unexpected RADIUS server auth MIB value")

def test_radius_acct_non_ascii_ssid(dev, apdev):
    """RADIUS Accounting and non-ASCII SSID"""
    params = hostapd.wpa2_eap_params()
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    ssid2 = "740665007374"
    params['ssid2'] = ssid2
    hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid2=ssid2, key_mgmt="WPA-EAP", scan_freq="2412",
                   eap="PSK", identity="psk.user@example.com",
                   password_hex="0123456789abcdef0123456789abcdef")

def test_radius_acct_pmksa_caching(dev, apdev):
    """RADIUS Accounting with PMKSA caching"""
    as_hapd = hostapd.Hostapd("as")
    as_mib_start = as_hapd.get_mib(param="radius_server")
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-acct")
    dev[1].connect("radius-acct", key_mgmt="WPA-EAP", scan_freq="2412",
                   eap="PAX", identity="test-class",
                   password_hex="0123456789abcdef0123456789abcdef")
    for d in [ dev[0], dev[1] ]:
        d.request("REASSOCIATE")
        d.wait_connected(timeout=15, error="Reassociation timed out")

    count = 0
    while True:
        mib = hapd.get_mib()
        if int(mib['radiusAccClientResponses']) >= 4:
            break
        time.sleep(0.1)
        count += 1
        if count > 10:
            raise Exception("Did not receive Accounting-Response packets")

    if int(mib['radiusAccClientRetransmissions']) > 0:
        raise Exception("Unexpected Accounting-Request retransmission")

    as_mib_end = as_hapd.get_mib(param="radius_server")

    req_s = int(as_mib_start['radiusAccServTotalRequests'])
    req_e = int(as_mib_end['radiusAccServTotalRequests'])
    if req_e < req_s + 2:
        raise Exception("Unexpected RADIUS server acct MIB value")

    acc_s = int(as_mib_start['radiusAuthServAccessAccepts'])
    acc_e = int(as_mib_end['radiusAuthServAccessAccepts'])
    if acc_e < acc_s + 1:
        raise Exception("Unexpected RADIUS server auth MIB value")

def test_radius_acct_interim(dev, apdev):
    """RADIUS Accounting interim update"""
    as_hapd = hostapd.Hostapd("as")
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    params['radius_acct_interim_interval'] = "1"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-acct")
    logger.info("Checking for RADIUS counters")
    as_mib_start = as_hapd.get_mib(param="radius_server")
    time.sleep(3.1)
    as_mib_end = as_hapd.get_mib(param="radius_server")
    req_s = int(as_mib_start['radiusAccServTotalRequests'])
    req_e = int(as_mib_end['radiusAccServTotalRequests'])
    if req_e < req_s + 3:
        raise Exception("Unexpected RADIUS server acct MIB value")

def test_radius_acct_interim_unreachable(dev, apdev):
    """RADIUS Accounting interim update with unreachable server"""
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "18139"
    params['acct_server_shared_secret'] = "radius"
    params['radius_acct_interim_interval'] = "1"
    hapd = hostapd.add_ap(apdev[0], params)
    start = hapd.get_mib()
    connect(dev[0], "radius-acct")
    logger.info("Waiting for interium accounting updates")
    time.sleep(3.1)
    end = hapd.get_mib()
    req_s = int(start['radiusAccClientTimeouts'])
    req_e = int(end['radiusAccClientTimeouts'])
    if req_e < req_s + 2:
        raise Exception("Unexpected RADIUS server acct MIB value")

def test_radius_acct_interim_unreachable2(dev, apdev):
    """RADIUS Accounting interim update with unreachable server (retry)"""
    params = hostapd.wpa2_eap_params(ssid="radius-acct")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "18139"
    params['acct_server_shared_secret'] = "radius"
    # Use long enough interim update interval to allow RADIUS retransmission
    # case (3 seconds) to trigger first.
    params['radius_acct_interim_interval'] = "4"
    hapd = hostapd.add_ap(apdev[0], params)
    start = hapd.get_mib()
    connect(dev[0], "radius-acct")
    logger.info("Waiting for interium accounting updates")
    time.sleep(7.5)
    end = hapd.get_mib()
    req_s = int(start['radiusAccClientTimeouts'])
    req_e = int(end['radiusAccClientTimeouts'])
    if req_e < req_s + 2:
        raise Exception("Unexpected RADIUS server acct MIB value")

def test_radius_acct_ipaddr(dev, apdev):
    """RADIUS Accounting and Framed-IP-Address"""
    try:
        _test_radius_acct_ipaddr(dev, apdev)
    finally:
        subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'],
                        stderr=open('/dev/null', 'w'))
        subprocess.call(['brctl', 'delbr', 'ap-br0'],
                        stderr=open('/dev/null', 'w'))

def _test_radius_acct_ipaddr(dev, apdev):
    params = { "ssid": "radius-acct-open",
               'acct_server_addr': "127.0.0.1",
               'acct_server_port': "1813",
               'acct_server_shared_secret': "radius",
               'proxy_arp': '1',
               'ap_isolate': '1',
               'bridge': 'ap-br0' }
    hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
    try:
        hapd.enable()
    except:
        # For now, do not report failures due to missing kernel support
        raise HwsimSkip("Could not start hostapd - assume proxyarp not supported in kernel version")
    bssid = apdev[0]['bssid']

    subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
    subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])

    dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
    addr0 = dev[0].own_addr()

    pkt = build_dhcp_ack(dst_ll="ff:ff:ff:ff:ff:ff", src_ll=bssid,
                         ip_src="192.168.1.1", ip_dst="255.255.255.255",
                         yiaddr="192.168.1.123", chaddr=addr0)
    if "OK" not in hapd.request("DATA_TEST_FRAME ifname=ap-br0 " + binascii.hexlify(pkt)):
        raise Exception("DATA_TEST_FRAME failed")

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

def send_and_check_reply(srv, req, code, error_cause=0):
    reply = srv.SendPacket(req)
    logger.debug("RADIUS response from hostapd")
    for i in reply.keys():
        logger.debug("%s: %s" % (i, reply[i]))
    if reply.code != code:
        raise Exception("Unexpected response code")
    if error_cause:
        if 'Error-Cause' not in reply:
            raise Exception("Missing Error-Cause")
            if reply['Error-Cause'][0] != error_cause:
                raise Exception("Unexpected Error-Cause: {}".format(reply['Error-Cause']))

def test_radius_acct_psk(dev, apdev):
    """RADIUS Accounting - PSK"""
    as_hapd = hostapd.Hostapd("as")
    params = hostapd.wpa2_params(ssid="radius-acct", passphrase="12345678")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect("radius-acct", psk="12345678", scan_freq="2412")

def test_radius_acct_psk_sha256(dev, apdev):
    """RADIUS Accounting - PSK SHA256"""
    as_hapd = hostapd.Hostapd("as")
    params = hostapd.wpa2_params(ssid="radius-acct", passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect("radius-acct", key_mgmt="WPA-PSK-SHA256",
                   psk="12345678", scan_freq="2412")

def test_radius_acct_ft_psk(dev, apdev):
    """RADIUS Accounting - FT-PSK"""
    as_hapd = hostapd.Hostapd("as")
    params = ft_params1(ssid="radius-acct", passphrase="12345678")
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect("radius-acct", key_mgmt="FT-PSK",
                   psk="12345678", scan_freq="2412")

def test_radius_acct_ieee8021x(dev, apdev):
    """RADIUS Accounting - IEEE 802.1X"""
    skip_with_fips(dev[0])
    as_hapd = hostapd.Hostapd("as")
    params = hostapd.radius_params()
    params["ssid"] = "radius-acct-1x"
    params["ieee8021x"] = "1"
    params["wep_key_len_broadcast"] = "13"
    params["wep_key_len_unicast"] = "13"
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect("radius-acct-1x", key_mgmt="IEEE8021X", eap="PSK",
                   identity="psk.user@example.com",
                   password_hex="0123456789abcdef0123456789abcdef",
                   scan_freq="2412")

def test_radius_das_disconnect(dev, apdev):
    """RADIUS Dynamic Authorization Extensions - Disconnect"""
    try:
        import pyrad.client
        import pyrad.packet
        import pyrad.dictionary
        import radius_das
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    params = hostapd.wpa2_eap_params(ssid="radius-das")
    params['radius_das_port'] = "3799"
    params['radius_das_client'] = "127.0.0.1 secret"
    params['radius_das_require_event_timestamp'] = "1"
    params['own_ip_addr'] = "127.0.0.1"
    params['nas_identifier'] = "nas.example.com"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-das")
    addr = dev[0].p2p_interface_addr()
    sta = hapd.get_sta(addr)
    id = sta['dot1xAuthSessionId']

    dict = pyrad.dictionary.Dictionary("dictionary.radius")

    srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
                              secret="secret", dict=dict)
    srv.retries = 1
    srv.timeout = 1

    logger.info("Disconnect-Request with incorrect secret")
    req = radius_das.DisconnectPacket(dict=dict, secret="incorrect",
                                      User_Name="foo",
                                      NAS_Identifier="localhost",
                                      Event_Timestamp=int(time.time()))
    logger.debug(req)
    try:
        reply = srv.SendPacket(req)
        raise Exception("Unexpected response to Disconnect-Request")
    except pyrad.client.Timeout:
        logger.info("Disconnect-Request with incorrect secret properly ignored")

    logger.info("Disconnect-Request without Event-Timestamp")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      User_Name="psk.user@example.com")
    logger.debug(req)
    try:
        reply = srv.SendPacket(req)
        raise Exception("Unexpected response to Disconnect-Request")
    except pyrad.client.Timeout:
        logger.info("Disconnect-Request without Event-Timestamp properly ignored")

    logger.info("Disconnect-Request with non-matching Event-Timestamp")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      User_Name="psk.user@example.com",
                                      Event_Timestamp=123456789)
    logger.debug(req)
    try:
        reply = srv.SendPacket(req)
        raise Exception("Unexpected response to Disconnect-Request")
    except pyrad.client.Timeout:
        logger.info("Disconnect-Request with non-matching Event-Timestamp properly ignored")

    logger.info("Disconnect-Request with unsupported attribute")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      User_Name="foo",
                                      User_Password="foo",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 401)

    logger.info("Disconnect-Request with invalid Calling-Station-Id")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      User_Name="foo",
                                      Calling_Station_Id="foo",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 407)

    logger.info("Disconnect-Request with mismatching User-Name")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      User_Name="foo",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)

    logger.info("Disconnect-Request with mismatching Calling-Station-Id")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      Calling_Station_Id="12:34:56:78:90:aa",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)

    logger.info("Disconnect-Request with mismatching Acct-Session-Id")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      Acct_Session_Id="12345678-87654321",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)

    logger.info("Disconnect-Request with mismatching Acct-Session-Id (len)")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      Acct_Session_Id="12345678",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)

    logger.info("Disconnect-Request with mismatching Acct-Multi-Session-Id")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      Acct_Multi_Session_Id="12345678+87654321",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)

    logger.info("Disconnect-Request with mismatching Acct-Multi-Session-Id (len)")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      Acct_Multi_Session_Id="12345678",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)

    logger.info("Disconnect-Request with no session identification attributes")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 503)

    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    logger.info("Disconnect-Request with mismatching NAS-IP-Address")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="192.168.3.4",
                                      Acct_Session_Id=id,
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 403)

    logger.info("Disconnect-Request with mismatching NAS-Identifier")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_Identifier="unknown.example.com",
                                      Acct_Session_Id=id,
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, 403)

    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    logger.info("Disconnect-Request with matching Acct-Session-Id")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      Acct_Session_Id=id,
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    dev[0].wait_disconnected(timeout=10)
    dev[0].wait_connected(timeout=10, error="Re-connection timed out")

    logger.info("Disconnect-Request with matching Acct-Multi-Session-Id")
    sta = hapd.get_sta(addr)
    multi_sess_id = sta['authMultiSessionId']
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      Acct_Multi_Session_Id=multi_sess_id,
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    dev[0].wait_disconnected(timeout=10)
    dev[0].wait_connected(timeout=10, error="Re-connection timed out")

    logger.info("Disconnect-Request with matching User-Name")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_Identifier="nas.example.com",
                                      User_Name="psk.user@example.com",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    dev[0].wait_disconnected(timeout=10)
    dev[0].wait_connected(timeout=10, error="Re-connection timed out")

    logger.info("Disconnect-Request with matching Calling-Station-Id")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      Calling_Station_Id=addr,
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    dev[0].wait_disconnected(timeout=10)
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", "CTRL-EVENT-CONNECTED"])
    if ev is None:
        raise Exception("Timeout while waiting for re-connection")
    if "CTRL-EVENT-EAP-STARTED" not in ev:
        raise Exception("Unexpected skipping of EAP authentication in reconnection")
    dev[0].wait_connected(timeout=10, error="Re-connection timed out")

    logger.info("Disconnect-Request with matching Calling-Station-Id and non-matching CUI")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      Calling_Station_Id=addr,
                                      Chargeable_User_Identity="foo@example.com",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=503)

    logger.info("Disconnect-Request with matching CUI")
    dev[1].connect("radius-das", key_mgmt="WPA-EAP",
                   eap="GPSK", identity="gpsk-cui",
                   password="abcdefghijklmnop0123456789abcdef",
                   scan_freq="2412")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      Chargeable_User_Identity="gpsk-chargeable-user-identity",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    dev[1].wait_disconnected(timeout=10)
    dev[1].wait_connected(timeout=10, error="Re-connection timed out")

    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    connect(dev[2], "radius-das")

    logger.info("Disconnect-Request with matching User-Name - multiple sessions matching")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_Identifier="nas.example.com",
                                      User_Name="psk.user@example.com",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=508)

    logger.info("Disconnect-Request with User-Name matching multiple sessions, Calling-Station-Id only one")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_Identifier="nas.example.com",
                                      Calling_Station_Id=addr,
                                      User_Name="psk.user@example.com",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    dev[0].wait_disconnected(timeout=10)
    dev[0].wait_connected(timeout=10, error="Re-connection timed out")

    ev = dev[2].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    logger.info("Disconnect-Request with matching Acct-Multi-Session-Id after disassociation")
    sta = hapd.get_sta(addr)
    multi_sess_id = sta['authMultiSessionId']
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected(timeout=10)
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      Acct_Multi_Session_Id=multi_sess_id,
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    dev[0].request("RECONNECT")
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
    if ev is None:
        raise Exception("Timeout on EAP start")
    dev[0].wait_connected(timeout=15)

    logger.info("Disconnect-Request with matching User-Name after disassociation")
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected(timeout=10)
    dev[2].request("DISCONNECT")
    dev[2].wait_disconnected(timeout=10)
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      User_Name="psk.user@example.com",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    logger.info("Disconnect-Request with matching CUI after disassociation")
    dev[1].request("DISCONNECT")
    dev[1].wait_disconnected(timeout=10)
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      Chargeable_User_Identity="gpsk-chargeable-user-identity",
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    logger.info("Disconnect-Request with matching Calling-Station-Id after disassociation")
    dev[0].request("RECONNECT")
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
    if ev is None:
        raise Exception("Timeout on EAP start")
    dev[0].wait_connected(timeout=15)
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected(timeout=10)
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      Calling_Station_Id=addr,
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

    logger.info("Disconnect-Request with mismatching Calling-Station-Id after disassociation")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      Calling_Station_Id=addr,
                                      Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.DisconnectNAK, error_cause=503)

def add_message_auth_req(req):
    req.authenticator = req.CreateAuthenticator()
    hmac_obj = hmac.new(req.secret)
    hmac_obj.update(struct.pack("B", req.code))
    hmac_obj.update(struct.pack("B", req.id))

    # request attributes
    req.AddAttribute("Message-Authenticator", 16*"\x00")
    attrs = req._PktEncodeAttributes()

    # Length
    flen = 4 + 16 + len(attrs)
    hmac_obj.update(struct.pack(">H", flen))
    hmac_obj.update(16*"\x00") # all zeros Authenticator in calculation
    hmac_obj.update(attrs)
    del req[80]
    req.AddAttribute("Message-Authenticator", hmac_obj.digest())

def test_radius_das_disconnect_time_window(dev, apdev):
    """RADIUS Dynamic Authorization Extensions - Disconnect - time window"""
    try:
        import pyrad.client
        import pyrad.packet
        import pyrad.dictionary
        import radius_das
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    params = hostapd.wpa2_eap_params(ssid="radius-das")
    params['radius_das_port'] = "3799"
    params['radius_das_client'] = "127.0.0.1 secret"
    params['radius_das_require_event_timestamp'] = "1"
    params['radius_das_require_message_authenticator'] = "1"
    params['radius_das_time_window'] = "10"
    params['own_ip_addr'] = "127.0.0.1"
    params['nas_identifier'] = "nas.example.com"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-das")
    addr = dev[0].own_addr()
    sta = hapd.get_sta(addr)
    id = sta['dot1xAuthSessionId']

    dict = pyrad.dictionary.Dictionary("dictionary.radius")

    srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
                              secret="secret", dict=dict)
    srv.retries = 1
    srv.timeout = 1

    logger.info("Disconnect-Request with unsupported attribute")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      Calling_Station_Id=addr,
                                      Event_Timestamp=int(time.time()) - 50)
    add_message_auth_req(req)
    logger.debug(req)
    try:
        reply = srv.SendPacket(req)
        raise Exception("Unexpected response to Disconnect-Request")
    except pyrad.client.Timeout:
        logger.info("Disconnect-Request with non-matching Event-Timestamp properly ignored")

    logger.info("Disconnect-Request with unsupported attribute")
    req = radius_das.DisconnectPacket(dict=dict, secret="secret",
                                      NAS_IP_Address="127.0.0.1",
                                      NAS_Identifier="nas.example.com",
                                      Calling_Station_Id=addr,
                                      Event_Timestamp=int(time.time()))
    add_message_auth_req(req)
    send_and_check_reply(srv, req, pyrad.packet.DisconnectACK)

def test_radius_das_coa(dev, apdev):
    """RADIUS Dynamic Authorization Extensions - CoA"""
    try:
        import pyrad.client
        import pyrad.packet
        import pyrad.dictionary
        import radius_das
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    params = hostapd.wpa2_eap_params(ssid="radius-das")
    params['radius_das_port'] = "3799"
    params['radius_das_client'] = "127.0.0.1 secret"
    params['radius_das_require_event_timestamp'] = "1"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-das")
    addr = dev[0].p2p_interface_addr()
    sta = hapd.get_sta(addr)
    id = sta['dot1xAuthSessionId']

    dict = pyrad.dictionary.Dictionary("dictionary.radius")

    srv = pyrad.client.Client(server="127.0.0.1", acctport=3799,
                              secret="secret", dict=dict)
    srv.retries = 1
    srv.timeout = 1

    # hostapd does not currently support CoA-Request, so NAK is expected
    logger.info("CoA-Request with matching Acct-Session-Id")
    req = radius_das.CoAPacket(dict=dict, secret="secret",
                               Acct_Session_Id=id,
                               Event_Timestamp=int(time.time()))
    send_and_check_reply(srv, req, pyrad.packet.CoANAK, error_cause=405)

def test_radius_ipv6(dev, apdev):
    """RADIUS connection over IPv6"""
    params = {}
    params['ssid'] = 'as'
    params['beacon_int'] = '2000'
    params['radius_server_clients'] = 'auth_serv/radius_clients_ipv6.conf'
    params['radius_server_ipv6'] = '1'
    params['radius_server_auth_port'] = '18129'
    params['radius_server_acct_port'] = '18139'
    params['eap_server'] = '1'
    params['eap_user_file'] = 'auth_serv/eap_user.conf'
    params['ca_cert'] = 'auth_serv/ca.pem'
    params['server_cert'] = 'auth_serv/server.pem'
    params['private_key'] = 'auth_serv/server.key'
    hostapd.add_ap(apdev[1], params)

    params = hostapd.wpa2_eap_params(ssid="radius-ipv6")
    params['auth_server_addr'] = "::0"
    params['auth_server_port'] = "18129"
    params['acct_server_addr'] = "::0"
    params['acct_server_port'] = "18139"
    params['acct_server_shared_secret'] = "radius"
    params['own_ip_addr'] = "::0"
    hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-ipv6")

def test_radius_macacl(dev, apdev):
    """RADIUS MAC ACL"""
    params = hostapd.radius_params()
    params["ssid"] = "radius"
    params["macaddr_acl"] = "2"
    hostapd.add_ap(apdev[0], params)
    dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")

    # Invalid VLAN ID from RADIUS server
    dev[2].connect("radius", key_mgmt="NONE", scan_freq="2412")
    dev[2].request("REMOVE_NETWORK all")
    dev[2].wait_disconnected()
    dev[2].connect("radius", key_mgmt="NONE", scan_freq="2412")

def test_radius_macacl_acct(dev, apdev):
    """RADIUS MAC ACL and accounting enabled"""
    params = hostapd.radius_params()
    params["ssid"] = "radius"
    params["macaddr_acl"] = "2"
    params['acct_server_addr'] = "127.0.0.1"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "radius"
    hostapd.add_ap(apdev[0], params)
    dev[0].connect("radius", key_mgmt="NONE", scan_freq="2412")
    dev[1].connect("radius", key_mgmt="NONE", scan_freq="2412")
    dev[1].request("DISCONNECT")
    dev[1].wait_disconnected()
    dev[1].request("RECONNECT")

def test_radius_failover(dev, apdev):
    """RADIUS Authentication and Accounting server failover"""
    subprocess.call(['ip', 'ro', 'replace', '192.168.213.17', 'dev', 'lo'])
    as_hapd = hostapd.Hostapd("as")
    as_mib_start = as_hapd.get_mib(param="radius_server")
    params = hostapd.wpa2_eap_params(ssid="radius-failover")
    params["auth_server_addr"] = "192.168.213.17"
    params["auth_server_port"] = "1812"
    params["auth_server_shared_secret"] = "testing"
    params['acct_server_addr'] = "192.168.213.17"
    params['acct_server_port'] = "1813"
    params['acct_server_shared_secret'] = "testing"
    params['radius_retry_primary_interval'] = "20"
    hapd = hostapd.add_ap(apdev[0], params, no_enable=True)
    hapd.set("auth_server_addr", "127.0.0.1")
    hapd.set("auth_server_port", "1812")
    hapd.set("auth_server_shared_secret", "radius")
    hapd.set('acct_server_addr', "127.0.0.1")
    hapd.set('acct_server_port', "1813")
    hapd.set('acct_server_shared_secret', "radius")
    hapd.enable()
    ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
    if ev is None:
        raise Exception("AP startup timed out")
        if "AP-ENABLED" not in ev:
            raise Exception("AP startup failed")
    start = os.times()[4]

    try:
        subprocess.call(['ip', 'ro', 'replace', 'prohibit', '192.168.213.17'])
        dev[0].request("SET EAPOL::authPeriod 5")
        connect(dev[0], "radius-failover", wait_connect=False)
        dev[0].wait_connected(timeout=20)
    finally:
        dev[0].request("SET EAPOL::authPeriod 30")
        subprocess.call(['ip', 'ro', 'del', '192.168.213.17'])

    as_mib_end = as_hapd.get_mib(param="radius_server")
    req_s = int(as_mib_start['radiusAccServTotalRequests'])
    req_e = int(as_mib_end['radiusAccServTotalRequests'])
    if req_e <= req_s:
        raise Exception("Unexpected RADIUS server acct MIB value")

    end = os.times()[4]
    try:
        subprocess.call(['ip', 'ro', 'replace', 'prohibit', '192.168.213.17'])
        dev[1].request("SET EAPOL::authPeriod 5")
        if end - start < 21:
            time.sleep(21 - (end - start))
        connect(dev[1], "radius-failover", wait_connect=False)
        dev[1].wait_connected(timeout=20)
    finally:
        dev[1].request("SET EAPOL::authPeriod 30")
        subprocess.call(['ip', 'ro', 'del', '192.168.213.17'])

def run_pyrad_server(srv, t_events):
    srv.RunWithStop(t_events)

def test_radius_protocol(dev, apdev):
    """RADIUS Authentication protocol tests with a fake server"""
    try:
        import pyrad.server
        import pyrad.packet
        import pyrad.dictionary
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    class TestServer(pyrad.server.Server):
        def _HandleAuthPacket(self, pkt):
            pyrad.server.Server._HandleAuthPacket(self, pkt)
            logger.info("Received authentication request")
            reply = self.CreateReplyPacket(pkt)
            reply.code = pyrad.packet.AccessAccept
            if self.t_events['msg_auth'].is_set():
                logger.info("Add Message-Authenticator")
                if self.t_events['wrong_secret'].is_set():
                    logger.info("Use incorrect RADIUS shared secret")
                    pw = "incorrect"
                else:
                    pw = reply.secret
                hmac_obj = hmac.new(pw)
                hmac_obj.update(struct.pack("B", reply.code))
                hmac_obj.update(struct.pack("B", reply.id))

                # reply attributes
                reply.AddAttribute("Message-Authenticator",
                                   "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
                attrs = reply._PktEncodeAttributes()

                # Length
                flen = 4 + 16 + len(attrs)
                hmac_obj.update(struct.pack(">H", flen))
                hmac_obj.update(pkt.authenticator)
                hmac_obj.update(attrs)
                if self.t_events['double_msg_auth'].is_set():
                    logger.info("Include two Message-Authenticator attributes")
                else:
                    del reply[80]
                reply.AddAttribute("Message-Authenticator", hmac_obj.digest())
            self.SendReplyPacket(pkt.fd, reply)

        def RunWithStop(self, t_events):
            self._poll = select.poll()
            self._fdmap = {}
            self._PrepareSockets()
            self.t_events = t_events

            while not t_events['stop'].is_set():
                for (fd, event) in self._poll.poll(1000):
                    if event == select.POLLIN:
                        try:
                            fdo = self._fdmap[fd]
                            self._ProcessInput(fdo)
                        except pyrad.server.ServerPacketError as err:
                            logger.info("pyrad server dropping packet: " + str(err))
                        except pyrad.packet.PacketError as err:
                            logger.info("pyrad server received invalid packet: " + str(err))
                    else:
                        logger.error("Unexpected event in pyrad server main loop")

    srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
                     authport=18138, acctport=18139)
    srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
                                                     "radius",
                                                     "localhost")
    srv.BindToAddress("")
    t_events = {}
    t_events['stop'] = threading.Event()
    t_events['msg_auth'] = threading.Event()
    t_events['wrong_secret'] = threading.Event()
    t_events['double_msg_auth'] = threading.Event()
    t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
    t.start()

    try:
        params = hostapd.wpa2_eap_params(ssid="radius-test")
        params['auth_server_port'] = "18138"
        hapd = hostapd.add_ap(apdev[0], params)
        connect(dev[0], "radius-test", wait_connect=False)
        ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
        if ev is None:
            raise Exception("Timeout on EAP start")
        time.sleep(1)
        dev[0].request("REMOVE_NETWORK all")
        time.sleep(0.1)
        dev[0].dump_monitor()
        t_events['msg_auth'].set()
        t_events['wrong_secret'].set()
        connect(dev[0], "radius-test", wait_connect=False)
        time.sleep(1)
        dev[0].request("REMOVE_NETWORK all")
        time.sleep(0.1)
        dev[0].dump_monitor()
        t_events['wrong_secret'].clear()
        connect(dev[0], "radius-test", wait_connect=False)
        time.sleep(1)
        dev[0].request("REMOVE_NETWORK all")
        time.sleep(0.1)
        dev[0].dump_monitor()
        t_events['double_msg_auth'].set()
        connect(dev[0], "radius-test", wait_connect=False)
        time.sleep(1)
    finally:
        t_events['stop'].set()
        t.join()

def test_radius_psk(dev, apdev):
    """WPA2 with PSK from RADIUS"""
    try:
        import pyrad.server
        import pyrad.packet
        import pyrad.dictionary
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    class TestServer(pyrad.server.Server):
        def _HandleAuthPacket(self, pkt):
            pyrad.server.Server._HandleAuthPacket(self, pkt)
            logger.info("Received authentication request")
            reply = self.CreateReplyPacket(pkt)
            reply.code = pyrad.packet.AccessAccept
            a = "\xab\xcd"
            secret = reply.secret
            if self.t_events['long'].is_set():
                p = b'\x10' + "0123456789abcdef" + 15 * b'\x00'
                b = hashlib.md5(secret + pkt.authenticator + a).digest()
                pp = bytearray(p[0:16])
                bb = bytearray(b)
                cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))

                b = hashlib.md5(reply.secret + bytes(cc)).digest()
                pp = bytearray(p[16:32])
                bb = bytearray(b)
                cc += bytearray(pp[i] ^ bb[i] for i in range(len(bb)))

                data = '\x00' + a + bytes(cc)
            else:
                p = b'\x08' + "12345678" + 7 * b'\x00'
                b = hashlib.md5(secret + pkt.authenticator + a).digest()
                pp = bytearray(p)
                bb = bytearray(b)
                cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
                data = '\x00' + a + bytes(cc)
            reply.AddAttribute("Tunnel-Password", data)
            self.SendReplyPacket(pkt.fd, reply)

        def RunWithStop(self, t_events):
            self._poll = select.poll()
            self._fdmap = {}
            self._PrepareSockets()
            self.t_events = t_events

            while not t_events['stop'].is_set():
                for (fd, event) in self._poll.poll(1000):
                    if event == select.POLLIN:
                        try:
                            fdo = self._fdmap[fd]
                            self._ProcessInput(fdo)
                        except pyrad.server.ServerPacketError as err:
                            logger.info("pyrad server dropping packet: " + str(err))
                        except pyrad.packet.PacketError as err:
                            logger.info("pyrad server received invalid packet: " + str(err))
                    else:
                        logger.error("Unexpected event in pyrad server main loop")

    srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
                     authport=18138, acctport=18139)
    srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
                                                     "radius",
                                                     "localhost")
    srv.BindToAddress("")
    t_events = {}
    t_events['stop'] = threading.Event()
    t_events['long'] = threading.Event()
    t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
    t.start()

    try:
        ssid = "test-wpa2-psk"
        params = hostapd.radius_params()
        params['ssid'] = ssid
        params["wpa"] = "2"
        params["wpa_key_mgmt"] = "WPA-PSK"
        params["rsn_pairwise"] = "CCMP"
        params['macaddr_acl'] = '2'
        params['wpa_psk_radius'] = '2'
        params['auth_server_port'] = "18138"
        hapd = hostapd.add_ap(apdev[0], params)
        dev[0].connect(ssid, psk="12345678", scan_freq="2412")
        t_events['long'].set()
        dev[1].connect(ssid, psk="0123456789abcdef", scan_freq="2412")
    finally:
        t_events['stop'].set()
        t.join()

def test_radius_psk_invalid(dev, apdev):
    """WPA2 with invalid PSK from RADIUS"""
    try:
        import pyrad.server
        import pyrad.packet
        import pyrad.dictionary
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    class TestServer(pyrad.server.Server):
        def _HandleAuthPacket(self, pkt):
            pyrad.server.Server._HandleAuthPacket(self, pkt)
            logger.info("Received authentication request")
            reply = self.CreateReplyPacket(pkt)
            reply.code = pyrad.packet.AccessAccept
            a = "\xab\xcd"
            secret = reply.secret
            p = b'\x07' + "1234567" + 8 * b'\x00'
            b = hashlib.md5(secret + pkt.authenticator + a).digest()
            pp = bytearray(p)
            bb = bytearray(b)
            cc = bytearray(pp[i] ^ bb[i] for i in range(len(bb)))
            data = '\x00' + a + bytes(cc)
            reply.AddAttribute("Tunnel-Password", data)
            self.SendReplyPacket(pkt.fd, reply)

        def RunWithStop(self, t_events):
            self._poll = select.poll()
            self._fdmap = {}
            self._PrepareSockets()
            self.t_events = t_events

            while not t_events['stop'].is_set():
                for (fd, event) in self._poll.poll(1000):
                    if event == select.POLLIN:
                        try:
                            fdo = self._fdmap[fd]
                            self._ProcessInput(fdo)
                        except pyrad.server.ServerPacketError as err:
                            logger.info("pyrad server dropping packet: " + str(err))
                        except pyrad.packet.PacketError as err:
                            logger.info("pyrad server received invalid packet: " + str(err))
                    else:
                        logger.error("Unexpected event in pyrad server main loop")

    srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
                     authport=18138, acctport=18139)
    srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
                                                     "radius",
                                                     "localhost")
    srv.BindToAddress("")
    t_events = {}
    t_events['stop'] = threading.Event()
    t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
    t.start()

    try:
        ssid = "test-wpa2-psk"
        params = hostapd.radius_params()
        params['ssid'] = ssid
        params["wpa"] = "2"
        params["wpa_key_mgmt"] = "WPA-PSK"
        params["rsn_pairwise"] = "CCMP"
        params['macaddr_acl'] = '2'
        params['wpa_psk_radius'] = '2'
        params['auth_server_port'] = "18138"
        hapd = hostapd.add_ap(apdev[0], params)
        dev[0].connect(ssid, psk="12345678", scan_freq="2412",
                       wait_connect=False)
        time.sleep(1)
    finally:
        t_events['stop'].set()
        t.join()

def test_radius_auth_force_client_addr(dev, apdev):
    """RADIUS client address specified"""
    params = hostapd.wpa2_eap_params(ssid="radius-auth")
    params['radius_client_addr'] = "127.0.0.1"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-auth")

@remote_compatible
def test_radius_auth_force_invalid_client_addr(dev, apdev):
    """RADIUS client address specified and invalid address"""
    params = hostapd.wpa2_eap_params(ssid="radius-auth")
    #params['radius_client_addr'] = "10.11.12.14"
    params['radius_client_addr'] = "1::2"
    hapd = hostapd.add_ap(apdev[0], params)
    connect(dev[0], "radius-auth", wait_connect=False)
    ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"])
    if ev is None:
        raise Exception("Timeout on EAP start")
    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected connection")

def add_message_auth(req):
    req.authenticator = req.CreateAuthenticator()
    hmac_obj = hmac.new(req.secret)
    hmac_obj.update(struct.pack("B", req.code))
    hmac_obj.update(struct.pack("B", req.id))

    # request attributes
    req.AddAttribute("Message-Authenticator",
                     "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
    attrs = req._PktEncodeAttributes()

    # Length
    flen = 4 + 16 + len(attrs)
    hmac_obj.update(struct.pack(">H", flen))
    hmac_obj.update(req.authenticator)
    hmac_obj.update(attrs)
    del req[80]
    req.AddAttribute("Message-Authenticator", hmac_obj.digest())

def test_radius_server_failures(dev, apdev):
    """RADIUS server failure cases"""
    try:
        import pyrad.client
        import pyrad.packet
        import pyrad.dictionary
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    dict = pyrad.dictionary.Dictionary("dictionary.radius")
    client = pyrad.client.Client(server="127.0.0.1", authport=1812,
                                 secret="radius", dict=dict)
    client.retries = 1
    client.timeout = 1

    # unexpected State
    req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
                                  User_Name="foo")
    req['State'] = 'foo-state'
    add_message_auth(req)
    reply = client.SendPacket(req)
    if reply.code != pyrad.packet.AccessReject:
        raise Exception("Unexpected RADIUS response code " + str(reply.code))

    # no EAP-Message
    req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
                                  User_Name="foo")
    add_message_auth(req)
    try:
        reply = client.SendPacket(req)
        raise Exception("Unexpected response")
    except pyrad.client.Timeout:
        pass

def test_ap_vlan_wpa2_psk_radius_required(dev, apdev):
    """AP VLAN with WPA2-PSK and RADIUS attributes required"""
    try:
        import pyrad.server
        import pyrad.packet
        import pyrad.dictionary
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    class TestServer(pyrad.server.Server):
        def _HandleAuthPacket(self, pkt):
            pyrad.server.Server._HandleAuthPacket(self, pkt)
            logger.info("Received authentication request")
            reply = self.CreateReplyPacket(pkt)
            reply.code = pyrad.packet.AccessAccept
            secret = reply.secret
            if self.t_events['extra'].is_set():
                reply.AddAttribute("Chargeable-User-Identity", "test-cui")
                reply.AddAttribute("User-Name", "test-user")
            if self.t_events['long'].is_set():
                reply.AddAttribute("Tunnel-Type", 13)
                reply.AddAttribute("Tunnel-Medium-Type", 6)
                reply.AddAttribute("Tunnel-Private-Group-ID", "1")
            self.SendReplyPacket(pkt.fd, reply)

        def RunWithStop(self, t_events):
            self._poll = select.poll()
            self._fdmap = {}
            self._PrepareSockets()
            self.t_events = t_events

            while not t_events['stop'].is_set():
                for (fd, event) in self._poll.poll(1000):
                    if event == select.POLLIN:
                        try:
                            fdo = self._fdmap[fd]
                            self._ProcessInput(fdo)
                        except pyrad.server.ServerPacketError as err:
                            logger.info("pyrad server dropping packet: " + str(err))
                        except pyrad.packet.PacketError as err:
                            logger.info("pyrad server received invalid packet: " + str(err))
                    else:
                        logger.error("Unexpected event in pyrad server main loop")

    srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
                     authport=18138, acctport=18139)
    srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
                                                     "radius",
                                                     "localhost")
    srv.BindToAddress("")
    t_events = {}
    t_events['stop'] = threading.Event()
    t_events['long'] = threading.Event()
    t_events['extra'] = threading.Event()
    t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
    t.start()

    try:
        ssid = "test-wpa2-psk"
        params = hostapd.radius_params()
        params['ssid'] = ssid
        params["wpa"] = "2"
        params["wpa_key_mgmt"] = "WPA-PSK"
        params["rsn_pairwise"] = "CCMP"
        params['macaddr_acl'] = '2'
        params['dynamic_vlan'] = "2"
        params['wpa_passphrase'] = '0123456789abcdefghi'
        params['auth_server_port'] = "18138"
        hapd = hostapd.add_ap(apdev[0], params)

        logger.info("connecting without VLAN")
        dev[0].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
                       wait_connect=False)
        ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED",
                                "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
        if ev is None:
            raise Exception("Timeout on connection attempt")
        if "CTRL-EVENT-CONNECTED" in ev:
            raise Exception("Unexpected success without vlan parameters")
        logger.info("connecting without VLAN failed as expected")

        logger.info("connecting without VLAN (CUI/User-Name)")
        t_events['extra'].set()
        dev[1].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
                       wait_connect=False)
        ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED",
                                "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
        if ev is None:
            raise Exception("Timeout on connection attempt")
        if "CTRL-EVENT-CONNECTED" in ev:
            raise Exception("Unexpected success without vlan parameters(2)")
        logger.info("connecting without VLAN failed as expected(2)")
        t_events['extra'].clear()

        t_events['long'].set()
        logger.info("connecting with VLAN")
        dev[2].connect(ssid, psk="0123456789abcdefghi", scan_freq="2412",
                       wait_connect=False)
        ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED",
                                "CTRL-EVENT-SSID-TEMP-DISABLED"], timeout=20)
        if ev is None:
            raise Exception("Timeout on connection attempt")
        if "CTRL-EVENT-SSID-TEMP-DISABLED" in ev:
            raise Exception("Unexpected failure with vlan parameters")
        logger.info("connecting with VLAN succeeded as expected")
    finally:
        t_events['stop'].set()
        t.join()

def test_radius_mppe_failure(dev, apdev):
    """RADIUS failure when adding MPPE keys"""
    params = { "ssid": "as", "beacon_int": "2000",
               "radius_server_clients": "auth_serv/radius_clients.conf",
               "radius_server_auth_port": '18127',
               "eap_server": "1",
               "eap_user_file": "auth_serv/eap_user.conf",
               "ca_cert": "auth_serv/ca.pem",
               "server_cert": "auth_serv/server.pem",
               "private_key": "auth_serv/server.key" }
    authsrv = hostapd.add_ap(apdev[1], params)

    params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap")
    params['auth_server_port'] = "18127"
    hapd = hostapd.add_ap(apdev[0], params)

    with fail_test(authsrv, 1, "os_get_random;radius_msg_add_mppe_keys"):
        dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", eap="TTLS",
                       identity="user", anonymous_identity="ttls",
                       password="password",
                       ca_cert="auth_serv/ca.pem", phase2="autheap=GTC",
                       wait_connect=False, scan_freq="2412")
        dev[0].wait_disconnected()
        dev[0].request("REMOVE_NETWORK all")

def test_radius_acct_failure(dev, apdev):
    """RADIUS Accounting and failure to add attributes"""
    # Connection goes through, but Accounting-Request cannot be sent out due to
    # NAS-Identifier being too long to fit into a RADIUS attribute.
    params = { "ssid": "radius-acct-open",
               'acct_server_addr': "127.0.0.1",
               'acct_server_port': "1813",
               'acct_server_shared_secret': "radius",
               'nas_identifier': 255*'A' }
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")

def test_radius_acct_failure_oom(dev, apdev):
    """RADIUS Accounting and failure to add attributes due to OOM"""
    params = { "ssid": "radius-acct-open",
               'acct_server_addr': "127.0.0.1",
               'acct_server_port': "1813",
               'acct_server_shared_secret': "radius",
               'radius_acct_interim_interval': "1",
               'nas_identifier': 250*'A',
               'radius_acct_req_attr': [ "126:s:" + 250*'B',
                                         "77:s:" + 250*'C',
                                         "127:s:" + 250*'D',
                                         "181:s:" + 250*'E' ] }
    hapd = hostapd.add_ap(apdev[0], params)

    with alloc_fail(hapd, 1, "radius_msg_add_attr;=accounting_msg"):
        dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
        wait_fail_trigger(hapd, "GET_ALLOC_FAIL")

    with alloc_fail(hapd, 1, "accounting_sta_report"):
        dev[1].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
        wait_fail_trigger(hapd, "GET_ALLOC_FAIL")

def test_radius_acct_failure_sta_data(dev, apdev):
    """RADIUS Accounting and failure to get STA data"""
    params = { "ssid": "radius-acct-open",
               'acct_server_addr': "127.0.0.1",
               'acct_server_port': "1813",
               'acct_server_shared_secret': "radius" }
    hapd = hostapd.add_ap(apdev[0], params)

    with fail_test(hapd, 1, "accounting_sta_update_stats"):
        dev[0].connect("radius-acct-open", key_mgmt="NONE", scan_freq="2412")
        dev[0].request("DISCONNECT")
        dev[0].wait_disconnected()