1# Cipher suite tests
2# Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi>
3#
4# This software may be distributed under the terms of the BSD license.
5# See README for more details.
6
7from remotehost import remote_compatible
8import time
9import logging
10logger = logging.getLogger()
11import os
12import subprocess
13
14import hwsim_utils
15import hostapd
16from utils import *
17from wlantest import Wlantest
18from wpasupplicant import WpaSupplicant
19
20KT_PTK, KT_GTK, KT_IGTK, KT_BIGTK = range(4)
21
22def check_cipher(dev, ap, cipher, group_cipher=None):
23    if cipher not in dev.get_capability("pairwise"):
24        raise HwsimSkip("Cipher %s not supported" % cipher)
25    if group_cipher and group_cipher not in dev.get_capability("group"):
26        raise HwsimSkip("Cipher %s not supported" % group_cipher)
27    params = {"ssid": "test-wpa2-psk",
28              "wpa_passphrase": "12345678",
29              "wpa": "2",
30              "wpa_key_mgmt": "WPA-PSK",
31              "rsn_pairwise": cipher}
32    if group_cipher:
33        params["group_cipher"] = group_cipher
34    else:
35        group_cipher = cipher
36    hapd = hostapd.add_ap(ap, params)
37    dev.connect("test-wpa2-psk", psk="12345678",
38                pairwise=cipher, group=group_cipher, scan_freq="2412")
39    hapd.wait_sta()
40    hwsim_utils.test_connectivity(dev, hapd)
41
42def check_group_mgmt_cipher(dev, ap, cipher, sta_req_cipher=None):
43    if cipher not in dev.get_capability("group_mgmt"):
44        raise HwsimSkip("Cipher %s not supported" % cipher)
45    params = {"ssid": "test-wpa2-psk-pmf",
46              "wpa_passphrase": "12345678",
47              "wpa": "2",
48              "ieee80211w": "2",
49              "wpa_key_mgmt": "WPA-PSK-SHA256",
50              "rsn_pairwise": "CCMP",
51              "group_mgmt_cipher": cipher}
52    hapd = hostapd.add_ap(ap, params)
53
54    Wlantest.setup(hapd)
55    wt = Wlantest()
56    wt.flush()
57    wt.add_passphrase("12345678")
58
59    dev.connect("test-wpa2-psk-pmf", psk="12345678", ieee80211w="2",
60                key_mgmt="WPA-PSK-SHA256", group_mgmt=sta_req_cipher,
61                pairwise="CCMP", group="CCMP", scan_freq="2412")
62    hapd.wait_sta()
63    hwsim_utils.test_connectivity(dev, hapd)
64    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff")
65    dev.wait_disconnected()
66    if wt.get_bss_counter('valid_bip_mmie', ap['bssid']) < 1:
67        raise Exception("No valid BIP MMIE seen")
68    if wt.get_bss_counter('bip_deauth', ap['bssid']) < 1:
69        raise Exception("No valid BIP deauth seen")
70
71    if cipher == "AES-128-CMAC":
72        group_mgmt = "BIP"
73    else:
74        group_mgmt = cipher
75    res = wt.info_bss('group_mgmt', ap['bssid']).strip()
76    if res != group_mgmt:
77        raise Exception("Unexpected group mgmt cipher: " + res)
78
79@remote_compatible
80def test_ap_cipher_tkip(dev, apdev):
81    """WPA2-PSK/TKIP connection"""
82    skip_with_fips(dev[0])
83    skip_without_tkip(dev[0])
84    check_cipher(dev[0], apdev[0], "TKIP")
85
86@remote_compatible
87def test_ap_cipher_tkip_countermeasures_ap(dev, apdev):
88    """WPA-PSK/TKIP countermeasures (detected by AP)"""
89    skip_with_fips(dev[0])
90    skip_without_tkip(dev[0])
91    testfile = "/sys/kernel/debug/ieee80211/%s/netdev:%s/tkip_mic_test" % (dev[0].get_driver_status_field("phyname"), dev[0].ifname)
92    if dev[0].cmd_execute(["ls", testfile])[0] != 0:
93        raise HwsimSkip("tkip_mic_test not supported in mac80211")
94
95    params = {"ssid": "tkip-countermeasures",
96              "wpa_passphrase": "12345678",
97              "wpa": "1",
98              "wpa_key_mgmt": "WPA-PSK",
99              "wpa_pairwise": "TKIP"}
100    hapd = hostapd.add_ap(apdev[0], params)
101
102    dev[0].connect("tkip-countermeasures", psk="12345678",
103                   pairwise="TKIP", group="TKIP", scan_freq="2412")
104
105    dev[0].dump_monitor()
106    dev[0].cmd_execute(["echo", "-n", apdev[0]['bssid'], ">", testfile],
107                       shell=True)
108    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
109    if ev is not None:
110        raise Exception("Unexpected disconnection on first Michael MIC failure")
111
112    dev[0].cmd_execute(["echo", "-n", "ff:ff:ff:ff:ff:ff", ">", testfile],
113                       shell=True)
114    ev = dev[0].wait_disconnected(timeout=10,
115                                  error="No disconnection after two Michael MIC failures")
116    if "reason=14" not in ev:
117        raise Exception("Unexpected disconnection reason: " + ev)
118    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
119    if ev is not None:
120        raise Exception("Unexpected connection during TKIP countermeasures")
121
122def test_ap_cipher_tkip_countermeasures_ap_mixed_mode(dev, apdev):
123    """WPA+WPA2-PSK/TKIP countermeasures (detected by mixed mode AP)"""
124    skip_with_fips(dev[0])
125    skip_without_tkip(dev[0])
126    testfile = "/sys/kernel/debug/ieee80211/%s/netdev:%s/tkip_mic_test" % (dev[0].get_driver_status_field("phyname"), dev[0].ifname)
127    if dev[0].cmd_execute(["ls", testfile])[0] != 0:
128        raise HwsimSkip("tkip_mic_test not supported in mac80211")
129
130    params = {"ssid": "tkip-countermeasures",
131              "wpa_passphrase": "12345678",
132              "wpa": "3",
133              "wpa_key_mgmt": "WPA-PSK",
134              "wpa_pairwise": "TKIP",
135              "rsn_pairwise": "CCMP"}
136    hapd = hostapd.add_ap(apdev[0], params)
137
138    dev[0].connect("tkip-countermeasures", psk="12345678",
139                   pairwise="TKIP", group="TKIP", scan_freq="2412")
140    dev[1].connect("tkip-countermeasures", psk="12345678",
141                   pairwise="CCMP", scan_freq="2412")
142
143    dev[0].dump_monitor()
144    dev[0].cmd_execute(["echo", "-n", apdev[0]['bssid'], ">", testfile],
145                       shell=True)
146    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
147    if ev is not None:
148        raise Exception("Unexpected disconnection on first Michael MIC failure")
149
150    dev[0].cmd_execute(["echo", "-n", "ff:ff:ff:ff:ff:ff", ">", testfile],
151                       shell=True)
152
153    ev = dev[0].wait_disconnected(timeout=10,
154                                  error="No disconnection after two Michael MIC failures")
155    if "reason=14" not in ev:
156        raise Exception("Unexpected disconnection reason: " + ev)
157
158    ev = dev[1].wait_disconnected(timeout=10,
159                                  error="No disconnection after two Michael MIC failures (2)")
160    if "reason=14" not in ev:
161        raise Exception("Unexpected disconnection reason (2): " + ev)
162
163    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
164    if ev is not None:
165        raise Exception("Unexpected connection during TKIP countermeasures (1)")
166    ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
167    if ev is not None:
168        raise Exception("Unexpected connection during TKIP countermeasures (2)")
169
170@remote_compatible
171def test_ap_cipher_tkip_countermeasures_sta(dev, apdev):
172    """WPA-PSK/TKIP countermeasures (detected by STA)"""
173    skip_with_fips(dev[0])
174    skip_without_tkip(dev[0])
175    params = {"ssid": "tkip-countermeasures",
176              "wpa_passphrase": "12345678",
177              "wpa": "1",
178              "wpa_key_mgmt": "WPA-PSK",
179              "wpa_pairwise": "TKIP"}
180    hapd = hostapd.add_ap(apdev[0], params)
181
182    testfile = "/sys/kernel/debug/ieee80211/%s/netdev:%s/tkip_mic_test" % (hapd.get_driver_status_field("phyname"), apdev[0]['ifname'])
183    if hapd.cmd_execute(["ls", testfile])[0] != 0:
184        raise HwsimSkip("tkip_mic_test not supported in mac80211")
185
186    dev[0].connect("tkip-countermeasures", psk="12345678",
187                   pairwise="TKIP", group="TKIP", scan_freq="2412")
188
189    dev[0].dump_monitor()
190    hapd.cmd_execute(["echo", "-n", dev[0].own_addr(), ">", testfile],
191                     shell=True)
192    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
193    if ev is not None:
194        raise Exception("Unexpected disconnection on first Michael MIC failure")
195
196    hapd.cmd_execute(["echo", "-n", "ff:ff:ff:ff:ff:ff", ">", testfile],
197                     shell=True)
198    ev = dev[0].wait_disconnected(timeout=10,
199                                  error="No disconnection after two Michael MIC failures")
200    if "reason=14 locally_generated=1" not in ev:
201        raise Exception("Unexpected disconnection reason: " + ev)
202    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
203    if ev is not None:
204        raise Exception("Unexpected connection during TKIP countermeasures")
205
206@long_duration_test
207def test_ap_cipher_tkip_countermeasures_sta2(dev, apdev):
208    """WPA-PSK/TKIP countermeasures (detected by two STAs)"""
209    skip_with_fips(dev[0])
210    skip_without_tkip(dev[0])
211    params = {"ssid": "tkip-countermeasures",
212              "wpa_passphrase": "12345678",
213              "wpa": "1",
214              "wpa_key_mgmt": "WPA-PSK",
215              "wpa_pairwise": "TKIP"}
216    hapd = hostapd.add_ap(apdev[0], params)
217
218    testfile = "/sys/kernel/debug/ieee80211/%s/netdev:%s/tkip_mic_test" % (hapd.get_driver_status_field("phyname"), apdev[0]['ifname'])
219    if hapd.cmd_execute(["ls", testfile])[0] != 0:
220        raise HwsimSkip("tkip_mic_test not supported in mac80211")
221
222    dev[0].connect("tkip-countermeasures", psk="12345678",
223                   pairwise="TKIP", group="TKIP", scan_freq="2412")
224    dev[0].dump_monitor()
225    id = dev[1].connect("tkip-countermeasures", psk="12345678",
226                        pairwise="TKIP", group="TKIP", scan_freq="2412")
227    dev[1].dump_monitor()
228
229    hapd.cmd_execute(["echo", "-n", "ff:ff:ff:ff:ff:ff", ">", testfile],
230                     shell=True)
231    ev = dev[0].wait_disconnected(timeout=10,
232                                  error="No disconnection after two Michael MIC failure")
233    if "reason=14" not in ev:
234        raise Exception("Unexpected disconnection reason: " + ev)
235    ev = dev[1].wait_disconnected(timeout=5,
236                                  error="No disconnection after two Michael MIC failure")
237    if "reason=14" not in ev:
238        raise Exception("Unexpected disconnection reason: " + ev)
239    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
240    if ev is not None:
241        raise Exception("Unexpected connection during TKIP countermeasures")
242    ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
243    if ev is not None:
244        raise Exception("Unexpected connection during TKIP countermeasures")
245
246    dev[0].request("REMOVE_NETWORK all")
247    logger.info("Waiting for TKIP countermeasures to end")
248    connected = False
249    start = os.times()[4]
250    while True:
251        now = os.times()[4]
252        if start + 70 < now:
253            break
254        dev[0].connect("tkip-countermeasures", psk="12345678",
255                       pairwise="TKIP", group="TKIP", scan_freq="2412",
256                       wait_connect=False)
257        ev = dev[0].wait_event(["CTRL-EVENT-AUTH-REJECT",
258                                "CTRL-EVENT-CONNECTED"], timeout=10)
259        if ev is None:
260            raise Exception("No connection result")
261        if "CTRL-EVENT-CONNECTED" in ev:
262            connected = True
263            break
264        if "status_code=1" not in ev:
265            raise Exception("Unexpected connection failure reason during TKIP countermeasures: " + ev)
266        dev[0].request("REMOVE_NETWORK all")
267        time.sleep(1)
268        dev[0].dump_monitor()
269        dev[1].dump_monitor()
270    if not connected:
271        raise Exception("No connection after TKIP countermeasures terminated")
272
273    ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
274    if ev is None:
275        dev[1].request("DISCONNECT")
276        dev[1].select_network(id)
277        dev[1].wait_connected()
278
279@remote_compatible
280def test_ap_cipher_ccmp(dev, apdev):
281    """WPA2-PSK/CCMP connection"""
282    check_cipher(dev[0], apdev[0], "CCMP")
283
284def test_ap_cipher_gcmp(dev, apdev):
285    """WPA2-PSK/GCMP connection"""
286    check_cipher(dev[0], apdev[0], "GCMP")
287
288def test_ap_cipher_ccmp_256(dev, apdev):
289    """WPA2-PSK/CCMP-256 connection"""
290    check_cipher(dev[0], apdev[0], "CCMP-256")
291
292def test_ap_cipher_gcmp_256(dev, apdev):
293    """WPA2-PSK/GCMP-256 connection"""
294    check_cipher(dev[0], apdev[0], "GCMP-256")
295
296def test_ap_cipher_gcmp_256_group_gcmp_256(dev, apdev):
297    """WPA2-PSK/GCMP-256 connection with group cipher override GCMP-256"""
298    check_cipher(dev[0], apdev[0], "GCMP-256", "GCMP-256")
299
300def test_ap_cipher_gcmp_256_group_gcmp(dev, apdev):
301    """WPA2-PSK/GCMP-256 connection with group cipher override GCMP"""
302    check_cipher(dev[0], apdev[0], "GCMP-256", "GCMP")
303
304def test_ap_cipher_gcmp_256_group_ccmp_256(dev, apdev):
305    """WPA2-PSK/GCMP-256 connection with group cipher override CCMP-256"""
306    check_cipher(dev[0], apdev[0], "GCMP-256", "CCMP-256")
307
308def test_ap_cipher_gcmp_256_group_ccmp(dev, apdev):
309    """WPA2-PSK/GCMP-256 connection with group cipher override CCMP"""
310    check_cipher(dev[0], apdev[0], "GCMP-256", "CCMP")
311
312def test_ap_cipher_gcmp_ccmp(dev, apdev, params):
313    """WPA2-PSK/GCMP/CCMP ciphers"""
314    config = os.path.join(params['logdir'], 'ap_cipher_gcmp_ccmp.conf')
315
316    for cipher in ["CCMP", "GCMP", "CCMP-256", "GCMP-256"]:
317        if cipher not in dev[0].get_capability("pairwise"):
318            raise HwsimSkip("Cipher %s not supported" % cipher)
319        if cipher not in dev[0].get_capability("group"):
320            raise HwsimSkip("Group cipher %s not supported" % cipher)
321
322    params = {"ssid": "test-wpa2-psk",
323              "wpa_passphrase": "12345678",
324              "wpa": "2",
325              "wpa_key_mgmt": "WPA-PSK",
326              "rsn_pairwise": "CCMP GCMP CCMP-256 GCMP-256"}
327    hapd = hostapd.add_ap(apdev[0], params)
328
329
330    for cipher in ["CCMP", "GCMP", "CCMP-256", "GCMP-256"]:
331        dev[0].connect("test-wpa2-psk", psk="12345678",
332                       pairwise=cipher, group="CCMP", scan_freq="2412")
333        if dev[0].get_status_field("group_cipher") != "CCMP":
334            raise Exception("Unexpected group_cipher")
335        if dev[0].get_status_field("pairwise_cipher") != cipher:
336            raise Exception("Unexpected pairwise_cipher")
337        dev[0].request("REMOVE_NETWORK all")
338        dev[0].wait_disconnected()
339
340    dev[0].connect("test-wpa2-psk", psk="12345678",
341                   pairwise="CCMP CCMP-256 GCMP GCMP-256",
342                   group="CCMP CCMP-256 GCMP GCMP-256", scan_freq="2412")
343    if dev[0].get_status_field("group_cipher") != "CCMP":
344        raise Exception("Unexpected group_cipher")
345    res = dev[0].get_status_field("pairwise_cipher")
346    if res != "CCMP-256" and res != "GCMP-256":
347        raise Exception("Unexpected pairwise_cipher")
348
349    try:
350        with open(config, "w") as f:
351            f.write("network={\n" +
352                    "\tssid=\"test-wpa2-psk\"\n" +
353                    "\tkey_mgmt=WPA-PSK\n" +
354                    "\tpsk=\"12345678\"\n" +
355                    "\tpairwise=GCMP\n" +
356                    "\tgroup=CCMP\n" +
357                    "\tscan_freq=2412\n" +
358                    "}\n")
359
360        wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
361        wpas.interface_add("wlan5", config=config)
362        wpas.wait_connected()
363        if wpas.get_status_field("group_cipher") != "CCMP":
364            raise Exception("Unexpected group_cipher")
365        if wpas.get_status_field("pairwise_cipher") != "GCMP":
366            raise Exception("Unexpected pairwise_cipher")
367    finally:
368        os.remove(config)
369
370@remote_compatible
371def test_ap_cipher_mixed_wpa_wpa2(dev, apdev):
372    """WPA2-PSK/CCMP/ and WPA-PSK/TKIP mixed configuration"""
373    skip_with_fips(dev[0])
374    skip_without_tkip(dev[0])
375    ssid = "test-wpa-wpa2-psk"
376    passphrase = "12345678"
377    params = {"ssid": ssid,
378              "wpa_passphrase": passphrase,
379              "wpa": "3",
380              "wpa_key_mgmt": "WPA-PSK",
381              "rsn_pairwise": "CCMP",
382              "wpa_pairwise": "TKIP"}
383    hapd = hostapd.add_ap(apdev[0], params)
384    dev[0].flush_scan_cache()
385    dev[0].connect(ssid, psk=passphrase, proto="WPA2",
386                   pairwise="CCMP", group="TKIP", scan_freq="2412")
387    status = dev[0].get_status()
388    if status['key_mgmt'] != 'WPA2-PSK':
389        raise Exception("Incorrect key_mgmt reported")
390    if status['pairwise_cipher'] != 'CCMP':
391        raise Exception("Incorrect pairwise_cipher reported")
392    if status['group_cipher'] != 'TKIP':
393        raise Exception("Incorrect group_cipher reported")
394    bss = dev[0].get_bss(apdev[0]['bssid'])
395    if bss['ssid'] != ssid:
396        raise Exception("Unexpected SSID in the BSS entry")
397    if "[WPA-PSK-TKIP]" not in bss['flags']:
398        raise Exception("Missing BSS flag WPA-PSK-TKIP")
399    if "[WPA2-PSK-CCMP]" not in bss['flags']:
400        raise Exception("Missing BSS flag WPA2-PSK-CCMP")
401    hapd.wait_sta()
402    hwsim_utils.test_connectivity(dev[0], hapd)
403
404    dev[1].connect(ssid, psk=passphrase, proto="WPA",
405                   pairwise="TKIP", group="TKIP", scan_freq="2412")
406    status = dev[1].get_status()
407    if status['key_mgmt'] != 'WPA-PSK':
408        raise Exception("Incorrect key_mgmt reported")
409    if status['pairwise_cipher'] != 'TKIP':
410        raise Exception("Incorrect pairwise_cipher reported")
411    if status['group_cipher'] != 'TKIP':
412        raise Exception("Incorrect group_cipher reported")
413    hapd.wait_sta()
414    hwsim_utils.test_connectivity(dev[1], hapd)
415    hwsim_utils.test_connectivity(dev[0], dev[1])
416
417@remote_compatible
418def test_ap_cipher_wpa_sae(dev, apdev):
419    """WPA-PSK/TKIP and SAE mixed AP - WPA IE and RSNXE coexistence"""
420    skip_with_fips(dev[0])
421    skip_without_tkip(dev[0])
422    check_sae_capab(dev[0])
423    ssid = "test-wpa-sae"
424    passphrase = "12345678"
425    params = {"ssid": ssid,
426              "wpa_passphrase": passphrase,
427              "wpa": "3",
428              "wpa_key_mgmt": "WPA-PSK SAE",
429              "rsn_pairwise": "CCMP",
430              "wpa_pairwise": "TKIP",
431              "sae_pwe": "1"}
432    hapd = hostapd.add_ap(apdev[0], params)
433    dev[0].flush_scan_cache()
434
435    dev[0].connect(ssid, psk=passphrase, proto="WPA",
436                   pairwise="TKIP", group="TKIP", scan_freq="2412")
437    status = dev[0].get_status()
438    if status['key_mgmt'] != 'WPA-PSK':
439        raise Exception("Incorrect key_mgmt reported")
440    if status['pairwise_cipher'] != 'TKIP':
441        raise Exception("Incorrect pairwise_cipher reported")
442    if status['group_cipher'] != 'TKIP':
443        raise Exception("Incorrect group_cipher reported")
444    hapd.wait_sta()
445    hwsim_utils.test_connectivity(dev[0], hapd)
446
447@remote_compatible
448def test_ap_cipher_bip(dev, apdev):
449    """WPA2-PSK with BIP"""
450    check_group_mgmt_cipher(dev[0], apdev[0], "AES-128-CMAC")
451
452def test_ap_cipher_bip_req(dev, apdev):
453    """WPA2-PSK with BIP required"""
454    check_group_mgmt_cipher(dev[0], apdev[0], "AES-128-CMAC", "AES-128-CMAC")
455
456def test_ap_cipher_bip_req2(dev, apdev):
457    """WPA2-PSK with BIP required (2)"""
458    check_group_mgmt_cipher(dev[0], apdev[0], "AES-128-CMAC",
459                            "AES-128-CMAC BIP-GMAC-128 BIP-GMAC-256 BIP-CMAC-256")
460
461def test_ap_cipher_bip_gmac_128(dev, apdev):
462    """WPA2-PSK with BIP-GMAC-128"""
463    check_group_mgmt_cipher(dev[0], apdev[0], "BIP-GMAC-128")
464
465def test_ap_cipher_bip_gmac_128_req(dev, apdev):
466    """WPA2-PSK with BIP-GMAC-128 required"""
467    check_group_mgmt_cipher(dev[0], apdev[0], "BIP-GMAC-128", "BIP-GMAC-128")
468
469def test_ap_cipher_bip_gmac_256(dev, apdev):
470    """WPA2-PSK with BIP-GMAC-256"""
471    check_group_mgmt_cipher(dev[0], apdev[0], "BIP-GMAC-256")
472
473def test_ap_cipher_bip_gmac_256_req(dev, apdev):
474    """WPA2-PSK with BIP-GMAC-256 required"""
475    check_group_mgmt_cipher(dev[0], apdev[0], "BIP-GMAC-256", "BIP-GMAC-256")
476
477def test_ap_cipher_bip_cmac_256(dev, apdev):
478    """WPA2-PSK with BIP-CMAC-256"""
479    check_group_mgmt_cipher(dev[0], apdev[0], "BIP-CMAC-256")
480
481def test_ap_cipher_bip_cmac_256_req(dev, apdev):
482    """WPA2-PSK with BIP-CMAC-256 required"""
483    check_group_mgmt_cipher(dev[0], apdev[0], "BIP-CMAC-256", "BIP-CMAC-256")
484
485def test_ap_cipher_bip_req_mismatch(dev, apdev):
486    """WPA2-PSK with BIP cipher mismatch"""
487    group_mgmt = dev[0].get_capability("group_mgmt")
488    for cipher in ["AES-128-CMAC", "BIP-GMAC-256"]:
489        if cipher not in group_mgmt:
490            raise HwsimSkip("Cipher %s not supported" % cipher)
491
492    params = {"ssid": "test-wpa2-psk-pmf",
493              "wpa_passphrase": "12345678",
494              "wpa": "2",
495              "ieee80211w": "2",
496              "wpa_key_mgmt": "WPA-PSK-SHA256",
497              "rsn_pairwise": "CCMP",
498              "group_mgmt_cipher": "AES-128-CMAC"}
499    hapd = hostapd.add_ap(apdev[0], params)
500
501    dev[0].scan_for_bss(hapd.own_addr(), 2412)
502    id = dev[0].connect("test-wpa2-psk-pmf", psk="12345678", ieee80211w="2",
503                        key_mgmt="WPA-PSK-SHA256", group_mgmt="BIP-GMAC-256",
504                        pairwise="CCMP", group="CCMP", scan_freq="2412",
505                        wait_connect=False)
506    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND",
507                            "CTRL-EVENT-CONNECTED"], timeout=10)
508    if ev is None:
509        raise Exception("Network selection result not indicated")
510    if "CTRL-EVENT-CONNECTED" in ev:
511        raise Exception("Unexpected connection")
512
513    dev[0].request("DISCONNECT")
514    dev[0].set_network(id, "group_mgmt", "AES-128-CMAC")
515    dev[0].select_network(id)
516    dev[0].wait_connected()
517
518def get_rx_spec(phy, keytype=KT_PTK):
519    keys = "/sys/kernel/debug/ieee80211/%s/keys" % (phy)
520    try:
521        for key in os.listdir(keys):
522            keydir = keys + "/" + key
523            with open(keydir + '/keyidx') as f:
524                keyid = int(f.read())
525            if keytype in (KT_PTK, KT_GTK) and keyid not in (0, 1, 2, 3):
526                continue
527            if keytype == KT_IGTK and keyid not in (4, 5):
528                continue
529            if keytype == KT_BIGTK and keyid not in (6, 7):
530                continue
531            files = os.listdir(keydir)
532            if keytype == KT_PTK and "station" not in files:
533                continue
534            if keytype != KT_PTK and "station" in files:
535                continue
536            with open(keydir + "/rx_spec") as f:
537                return f.read()
538    except OSError as e:
539        raise HwsimSkip("debugfs not supported in mac80211")
540    return None
541
542def get_tk_replay_counter(phy, keytype=KT_PTK):
543    keys = "/sys/kernel/debug/ieee80211/%s/keys" % (phy)
544    try:
545        for key in os.listdir(keys):
546            keydir = keys + "/" + key
547            with open(keydir + '/keyidx') as f:
548                keyid = int(f.read())
549            if keytype in (KT_PTK, KT_GTK) and keyid not in (0, 1, 2, 3):
550                continue
551            if keytype == KT_IGTK and keyid not in (4, 5):
552                continue
553            if keytype == KT_BIGTK and keyid not in (6, 7):
554                continue
555            files = os.listdir(keydir)
556            if keytype == KT_PTK and "station" not in files:
557                continue
558            if keytype != KT_PTK and "station" in files:
559                continue
560            with open(keydir + "/replays") as f:
561                return int(f.read())
562    except OSError as e:
563        raise HwsimSkip("debugfs not supported in mac80211")
564    return None
565
566def test_ap_cipher_replay_protection_ap_ccmp(dev, apdev):
567    """CCMP replay protection on AP"""
568    run_ap_cipher_replay_protection_ap(dev, apdev, "CCMP")
569
570def test_ap_cipher_replay_protection_ap_tkip(dev, apdev):
571    """TKIP replay protection on AP"""
572    skip_without_tkip(dev[0])
573    run_ap_cipher_replay_protection_ap(dev, apdev, "TKIP")
574
575def test_ap_cipher_replay_protection_ap_gcmp(dev, apdev):
576    """GCMP replay protection on AP"""
577    if "GCMP" not in dev[0].get_capability("pairwise"):
578        raise HwsimSkip("GCMP not supported")
579    run_ap_cipher_replay_protection_ap(dev, apdev, "GCMP")
580
581def run_ap_cipher_replay_protection_ap(dev, apdev, cipher):
582    params = {"ssid": "test-wpa2-psk",
583              "wpa_passphrase": "12345678",
584              "wpa": "2",
585              "wpa_key_mgmt": "WPA-PSK",
586              "rsn_pairwise": cipher}
587    hapd = hostapd.add_ap(apdev[0], params)
588    phy = hapd.get_driver_status_field("phyname")
589
590    Wlantest.setup(hapd)
591    wt = Wlantest()
592    wt.flush()
593    wt.add_passphrase("12345678")
594
595    dev[0].connect("test-wpa2-psk", psk="12345678",
596                   pairwise=cipher, group=cipher, scan_freq="2412")
597    hapd.wait_sta()
598
599    if cipher != "TKIP":
600        replays = get_tk_replay_counter(phy)
601        if replays != 0:
602            raise Exception("Unexpected replay reported (1)")
603
604    for i in range(5):
605        hwsim_utils.test_connectivity(dev[0], hapd)
606
607    if cipher != "TKIP":
608        replays = get_tk_replay_counter(phy)
609        if replays != 0:
610            raise Exception("Unexpected replay reported (2)")
611
612    if "OK" not in dev[0].request("RESET_PN"):
613        raise Exception("RESET_PN failed")
614    time.sleep(0.1)
615    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1,
616                                  success_expected=False)
617
618    if cipher != "TKIP":
619        replays = get_tk_replay_counter(phy)
620        if replays < 1:
621            raise Exception("Replays not reported")
622
623def test_ap_cipher_replay_protection_sta_ccmp(dev, apdev):
624    """CCMP replay protection on STA (TK)"""
625    run_ap_cipher_replay_protection_sta(dev, apdev, "CCMP")
626
627def test_ap_cipher_replay_protection_sta_tkip(dev, apdev):
628    """TKIP replay protection on STA (TK)"""
629    skip_without_tkip(dev[0])
630    run_ap_cipher_replay_protection_sta(dev, apdev, "TKIP")
631
632def test_ap_cipher_replay_protection_sta_gcmp(dev, apdev):
633    """GCMP replay protection on STA (TK)"""
634    if "GCMP" not in dev[0].get_capability("pairwise"):
635        raise HwsimSkip("GCMP not supported")
636    run_ap_cipher_replay_protection_sta(dev, apdev, "GCMP")
637
638def test_ap_cipher_replay_protection_sta_gtk_ccmp(dev, apdev):
639    """CCMP replay protection on STA (GTK)"""
640    run_ap_cipher_replay_protection_sta(dev, apdev, "CCMP", keytype=KT_GTK)
641
642def test_ap_cipher_replay_protection_sta_gtk_tkip(dev, apdev):
643    """TKIP replay protection on STA (GTK)"""
644    skip_without_tkip(dev[0])
645    run_ap_cipher_replay_protection_sta(dev, apdev, "TKIP", keytype=KT_GTK)
646
647def test_ap_cipher_replay_protection_sta_gtk_gcmp(dev, apdev):
648    """GCMP replay protection on STA (GTK)"""
649    if "GCMP" not in dev[0].get_capability("pairwise"):
650        raise HwsimSkip("GCMP not supported")
651    run_ap_cipher_replay_protection_sta(dev, apdev, "GCMP", keytype=KT_GTK)
652
653def test_ap_cipher_replay_protection_sta_igtk(dev, apdev):
654    """CCMP replay protection on STA (IGTK)"""
655    run_ap_cipher_replay_protection_sta(dev, apdev, "CCMP", keytype=KT_IGTK)
656
657def test_ap_cipher_replay_protection_sta_bigtk(dev, apdev):
658    """CCMP replay protection on STA (BIGTK)"""
659    run_ap_cipher_replay_protection_sta(dev, apdev, "CCMP", keytype=KT_BIGTK)
660
661def run_ap_cipher_replay_protection_sta(dev, apdev, cipher, keytype=KT_PTK):
662    params = {"ssid": "test-wpa2-psk",
663              "wpa_passphrase": "12345678",
664              "wpa": "2",
665              "wpa_key_mgmt": "WPA-PSK",
666              "rsn_pairwise": cipher}
667    if keytype == KT_IGTK or keytype == KT_BIGTK:
668        params['ieee80211w'] = '2'
669    if keytype == KT_BIGTK:
670        params['beacon_prot'] = '1'
671    hapd = hostapd.add_ap(apdev[0], params)
672
673    Wlantest.setup(hapd)
674    wt = Wlantest()
675    wt.flush()
676    wt.add_passphrase("12345678")
677
678    phy = dev[0].get_driver_status_field("phyname")
679    dev[0].connect("test-wpa2-psk", psk="12345678", ieee80211w='1',
680                   beacon_prot='1',
681                   pairwise=cipher, group=cipher, scan_freq="2412")
682    hapd.wait_sta()
683
684    if keytype == KT_BIGTK:
685        time.sleep(1)
686
687    if cipher != "TKIP":
688        replays = get_tk_replay_counter(phy, keytype)
689        if replays != 0:
690            raise Exception("Unexpected replay reported (1)")
691
692    for i in range(5):
693        hwsim_utils.test_connectivity(dev[0], hapd)
694
695    if cipher != "TKIP":
696        replays = get_tk_replay_counter(phy, keytype)
697        if replays != 0:
698            raise Exception("Unexpected replay reported (2)")
699
700    if keytype == KT_IGTK:
701        hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff test=1")
702        ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
703        if ev:
704            dev[0].wait_connected()
705
706    addr = "ff:ff:ff:ff:ff:ff" if keytype != KT_PTK else dev[0].own_addr()
707    cmd = "RESET_PN " + addr
708    if keytype == KT_IGTK:
709        cmd += " IGTK"
710    if keytype == KT_BIGTK:
711        cmd += " BIGTK"
712    if "OK" not in hapd.request(cmd):
713        raise Exception("RESET_PN failed")
714    time.sleep(0.1)
715    if keytype == KT_IGTK:
716        hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff test=1")
717        ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
718    elif keytype == KT_BIGTK:
719        time.sleep(1)
720    else:
721        hwsim_utils.test_connectivity(dev[0], hapd, timeout=1,
722                                      success_expected=False)
723
724    if cipher != "TKIP":
725        replays = get_tk_replay_counter(phy, keytype)
726        if replays < 1:
727            raise Exception("Replays not reported")
728
729@disable_ipv6
730def test_ap_wpa2_delayed_m3_retransmission(dev, apdev):
731    """Delayed M3 retransmission"""
732    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
733    hapd = hostapd.add_ap(apdev[0], params)
734
735    Wlantest.setup(hapd)
736    wt = Wlantest()
737    wt.flush()
738    wt.add_passphrase("12345678")
739
740    phy = dev[0].get_driver_status_field("phyname")
741    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
742    hapd.wait_sta()
743
744    for i in range(5):
745        hwsim_utils.test_connectivity(dev[0], hapd)
746
747    time.sleep(0.1)
748    before_tk = get_rx_spec(phy, keytype=KT_PTK).splitlines()
749    before_gtk = get_rx_spec(phy, keytype=KT_GTK).splitlines()
750    addr = dev[0].own_addr()
751    if "OK" not in hapd.request("RESEND_M3 " + addr):
752        raise Exception("RESEND_M3 failed")
753    time.sleep(0.1)
754    after_tk = get_rx_spec(phy, keytype=KT_PTK).splitlines()
755    after_gtk = get_rx_spec(phy, keytype=KT_GTK).splitlines()
756
757    if "OK" not in hapd.request("RESET_PN " + addr):
758        raise Exception("RESET_PN failed")
759    time.sleep(0.1)
760    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1,
761                                  success_expected=False)
762    dev[0].request("DISCONNECT")
763    dev[0].wait_disconnected()
764
765    for i in range(len(before_tk)):
766        b = int(before_tk[i], 16)
767        a = int(after_tk[i], 16)
768        if a < b:
769            raise Exception("TK RX counter decreased: idx=%d before=%d after=%d" % (i, b, a))
770
771    for i in range(len(before_gtk)):
772        b = int(before_gtk[i], 16)
773        a = int(after_gtk[i], 16)
774        if a < b:
775            raise Exception("GTK RX counter decreased: idx=%d before=%d after=%d" % (i, b, a))
776
777@disable_ipv6
778def test_ap_wpa2_delayed_m1_m3_retransmission(dev, apdev):
779    """Delayed M1+M3 retransmission"""
780    run_ap_wpa2_delayed_m1_m3_retransmission(dev, apdev, False)
781
782@disable_ipv6
783def test_ap_wpa2_delayed_m1_m3_retransmission2(dev, apdev):
784    """Delayed M1+M3 retransmission (change M1 ANonce)"""
785    run_ap_wpa2_delayed_m1_m3_retransmission(dev, apdev, True)
786
787def run_ap_wpa2_delayed_m1_m3_retransmission(dev, apdev,
788                                             change_m1_anonce=False):
789    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
790    hapd = hostapd.add_ap(apdev[0], params)
791
792    Wlantest.setup(hapd)
793    wt = Wlantest()
794    wt.flush()
795    wt.add_passphrase("12345678")
796
797    phy = dev[0].get_driver_status_field("phyname")
798    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
799    hapd.wait_sta()
800
801    for i in range(5):
802        hwsim_utils.test_connectivity(dev[0], hapd)
803
804    time.sleep(0.1)
805    before_tk = get_rx_spec(phy, keytype=KT_PTK).splitlines()
806    before_gtk = get_rx_spec(phy, keytype=KT_GTK).splitlines()
807    addr = dev[0].own_addr()
808    if change_m1_anonce:
809        if "OK" not in hapd.request("RESEND_M1 " + addr + " change-anonce"):
810            raise Exception("RESEND_M1 failed")
811    if "OK" not in hapd.request("RESEND_M1 " + addr):
812        raise Exception("RESEND_M1 failed")
813    if "OK" not in hapd.request("RESEND_M3 " + addr):
814        raise Exception("RESEND_M3 failed")
815    time.sleep(0.1)
816    after_tk = get_rx_spec(phy, keytype=KT_PTK).splitlines()
817    after_gtk = get_rx_spec(phy, keytype=KT_GTK).splitlines()
818
819    if "OK" not in hapd.request("RESET_PN " + addr):
820        raise Exception("RESET_PN failed")
821    time.sleep(0.1)
822    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1,
823                                  success_expected=False)
824    dev[0].request("DISCONNECT")
825    dev[0].wait_disconnected()
826
827    for i in range(len(before_tk)):
828        b = int(before_tk[i], 16)
829        a = int(after_tk[i], 16)
830        if a < b:
831            raise Exception("TK RX counter decreased: idx=%d before=%d after=%d" % (i, b, a))
832
833    for i in range(len(before_gtk)):
834        b = int(before_gtk[i], 16)
835        a = int(after_gtk[i], 16)
836        if a < b:
837            raise Exception("GTK RX counter decreased: idx=%d before=%d after=%d" % (i, b, a))
838
839@disable_ipv6
840def test_ap_wpa2_delayed_group_m1_retransmission(dev, apdev):
841    """Delayed group M1 retransmission"""
842    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
843    hapd = hostapd.add_ap(apdev[0], params)
844
845    Wlantest.setup(hapd)
846    wt = Wlantest()
847    wt.flush()
848    wt.add_passphrase("12345678")
849
850    phy = dev[0].get_driver_status_field("phyname")
851    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
852    hapd.wait_sta()
853
854    for i in range(5):
855        hwsim_utils.test_connectivity(dev[0], hapd)
856
857    time.sleep(0.1)
858    before = get_rx_spec(phy, keytype=KT_GTK).splitlines()
859    addr = dev[0].own_addr()
860    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr):
861        raise Exception("RESEND_GROUP_M1 failed")
862    time.sleep(0.1)
863    after = get_rx_spec(phy, keytype=KT_GTK).splitlines()
864
865    if "OK" not in hapd.request("RESET_PN ff:ff:ff:ff:ff:ff"):
866        raise Exception("RESET_PN failed")
867    time.sleep(0.1)
868    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1,
869                                  success_expected=False)
870    dev[0].request("DISCONNECT")
871    dev[0].wait_disconnected()
872
873    for i in range(len(before)):
874        b = int(before[i], 16)
875        a = int(after[i], 16)
876        if a < b:
877            raise Exception("RX counter decreased: idx=%d before=%d after=%d" % (i, b, a))
878
879@disable_ipv6
880def test_ap_wpa2_delayed_group_m1_retransmission_igtk(dev, apdev):
881    """Delayed group M1 retransmission (check IGTK protection)"""
882    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678",
883                                 ieee80211w="2")
884    hapd = hostapd.add_ap(apdev[0], params)
885
886    Wlantest.setup(hapd)
887    wt = Wlantest()
888    wt.flush()
889    wt.add_passphrase("12345678")
890
891    phy = dev[0].get_driver_status_field("phyname")
892    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412",
893                   ieee80211w="1")
894    hapd.wait_sta()
895
896    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1)
897
898    # deauth once to see that works OK
899    addr = dev[0].own_addr()
900    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff")
901    dev[0].wait_disconnected(timeout=10)
902
903    # now to check the protection
904    dev[0].request("RECONNECT")
905    dev[0].wait_connected()
906    hapd.wait_sta()
907
908    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1)
909
910    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr):
911        raise Exception("RESEND_GROUP_M1 failed")
912    if "OK" not in hapd.request("RESET_PN ff:ff:ff:ff:ff:ff IGTK"):
913        raise Exception("RESET_PN failed")
914
915    time.sleep(0.1)
916    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff test=1")
917
918    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.1)
919    if ev is not None:
920        raise Exception("Unexpected disconnection")
921
922    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1)
923
924    dev[0].request("DISCONNECT")
925    dev[0].wait_disconnected()
926
927def test_ap_wpa2_delayed_m1_m3_zero_tk(dev, apdev):
928    """Delayed M1+M3 retransmission and zero TK"""
929    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
930    hapd = hostapd.add_ap(apdev[0], params)
931
932    Wlantest.setup(hapd)
933    wt = Wlantest()
934    wt.flush()
935    wt.add_passphrase("12345678")
936
937    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
938    hapd.wait_sta()
939
940    hwsim_utils.test_connectivity(dev[0], hapd)
941    addr = dev[0].own_addr()
942    if "OK" not in hapd.request("RESEND_M1 " + addr + " change-anonce"):
943        raise Exception("RESEND_M1 failed")
944    if "OK" not in hapd.request("RESEND_M1 " + addr):
945        raise Exception("RESEND_M1 failed")
946    if "OK" not in hapd.request("RESEND_M3 " + addr):
947        raise Exception("RESEND_M3 failed")
948
949    KEY_FLAG_RX = 0x04
950    KEY_FLAG_TX = 0x08
951    KEY_FLAG_PAIRWISE = 0x20
952    KEY_FLAG_RX_TX = KEY_FLAG_RX | KEY_FLAG_TX
953    KEY_FLAG_PAIRWISE_RX_TX = KEY_FLAG_PAIRWISE | KEY_FLAG_RX_TX
954    if "OK" not in hapd.request("SET_KEY 3 %s %d %d %s %s %d" % (addr, 0, 1, 6*"00", 16*"00", KEY_FLAG_PAIRWISE_RX_TX)):
955        raise Exception("SET_KEY failed")
956    time.sleep(0.1)
957    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1, broadcast=False,
958                                  success_expected=False)
959    dev[0].request("DISCONNECT")
960    dev[0].wait_disconnected()
961
962def test_ap_wpa2_plaintext_m1_m3(dev, apdev):
963    """Plaintext M1/M3 during PTK rekey"""
964    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
965    hapd = hostapd.add_ap(apdev[0], params)
966
967    Wlantest.setup(hapd)
968    wt = Wlantest()
969    wt.flush()
970    wt.add_passphrase("12345678")
971
972    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
973
974    time.sleep(0.1)
975    addr = dev[0].own_addr()
976    if "OK" not in hapd.request("RESEND_M1 " + addr + " plaintext"):
977        raise Exception("RESEND_M1 failed")
978    time.sleep(0.1)
979    if "OK" not in hapd.request("RESEND_M3 " + addr + " plaintext"):
980        raise Exception("RESEND_M3 failed")
981    time.sleep(0.1)
982
983def test_ap_wpa2_plaintext_m1_m3_pmf(dev, apdev):
984    """Plaintext M1/M3 during PTK rekey (PMF)"""
985    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
986    params["ieee80211w"] = "2"
987    hapd = hostapd.add_ap(apdev[0], params)
988
989    Wlantest.setup(hapd)
990    wt = Wlantest()
991    wt.flush()
992    wt.add_passphrase("12345678")
993
994    dev[0].connect("test-wpa2-psk", psk="12345678", ieee80211w="2",
995                   scan_freq="2412")
996
997    time.sleep(0.1)
998    addr = dev[0].own_addr()
999    if "OK" not in hapd.request("RESEND_M1 " + addr + " plaintext"):
1000        raise Exception("RESEND_M1 failed")
1001    time.sleep(0.1)
1002    if "OK" not in hapd.request("RESEND_M3 " + addr + " plaintext"):
1003        raise Exception("RESEND_M3 failed")
1004    time.sleep(0.1)
1005
1006def test_ap_wpa2_plaintext_m3(dev, apdev):
1007    """Plaintext M3 during PTK rekey"""
1008    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
1009    hapd = hostapd.add_ap(apdev[0], params)
1010
1011    Wlantest.setup(hapd)
1012    wt = Wlantest()
1013    wt.flush()
1014    wt.add_passphrase("12345678")
1015
1016    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
1017
1018    time.sleep(0.1)
1019    addr = dev[0].own_addr()
1020    if "OK" not in hapd.request("RESEND_M1 " + addr):
1021        raise Exception("RESEND_M1 failed")
1022    time.sleep(0.1)
1023    if "OK" not in hapd.request("RESEND_M3 " + addr + " plaintext"):
1024        raise Exception("RESEND_M3 failed")
1025    time.sleep(0.1)
1026
1027def test_ap_wpa2_plaintext_group_m1(dev, apdev):
1028    """Plaintext group M1"""
1029    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
1030    hapd = hostapd.add_ap(apdev[0], params)
1031
1032    Wlantest.setup(hapd)
1033    wt = Wlantest()
1034    wt.flush()
1035    wt.add_passphrase("12345678")
1036
1037    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
1038
1039    time.sleep(0.1)
1040    addr = dev[0].own_addr()
1041    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr + " plaintext"):
1042        raise Exception("RESEND_GROUP_M1 failed")
1043    time.sleep(0.2)
1044    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr):
1045        raise Exception("RESEND_GROUP_M1 failed")
1046    time.sleep(0.1)
1047
1048def test_ap_wpa2_plaintext_group_m1_pmf(dev, apdev):
1049    """Plaintext group M1 (PMF)"""
1050    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
1051    params["ieee80211w"] = "2"
1052    hapd = hostapd.add_ap(apdev[0], params)
1053
1054    Wlantest.setup(hapd)
1055    wt = Wlantest()
1056    wt.flush()
1057    wt.add_passphrase("12345678")
1058
1059    dev[0].connect("test-wpa2-psk", psk="12345678", ieee80211w="2",
1060                   scan_freq="2412")
1061
1062    time.sleep(0.1)
1063    addr = dev[0].own_addr()
1064    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr + " plaintext"):
1065        raise Exception("RESEND_GROUP_M1 failed")
1066    time.sleep(0.2)
1067    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr):
1068        raise Exception("RESEND_GROUP_M1 failed")
1069    time.sleep(0.1)
1070
1071def test_ap_wpa2_test_command_failures(dev, apdev):
1072    """EAPOL/key config test command failures"""
1073    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
1074    hapd = hostapd.add_ap(apdev[0], params)
1075    tests = ["RESEND_M1 foo",
1076             "RESEND_M1 22:22:22:22:22:22",
1077             "RESEND_M3 foo",
1078             "RESEND_M3 22:22:22:22:22:22",
1079             "RESEND_GROUP_M1 foo",
1080             "RESEND_GROUP_M1 22:22:22:22:22:22",
1081             "SET_KEY foo",
1082             "SET_KEY 3 foo",
1083             "SET_KEY 3 22:22:22:22:22:22",
1084             "SET_KEY 3 22:22:22:22:22:22 1",
1085             "SET_KEY 3 22:22:22:22:22:22 1 1",
1086             "SET_KEY 3 22:22:22:22:22:22 1 1 q",
1087             "SET_KEY 3 22:22:22:22:22:22 1 1 112233445566",
1088             "SET_KEY 3 22:22:22:22:22:22 1 1 112233445566 1",
1089             "SET_KEY 3 22:22:22:22:22:22 1 1 112233445566 12",
1090             "SET_KEY 3 22:22:22:22:22:22 1 1 112233445566 12 1",
1091             "SET_KEY 3 22:22:22:22:22:22 1 1 112233445566 12 1 ",
1092             "RESET_PN ff:ff:ff:ff:ff:ff BIGTK",
1093             "RESET_PN ff:ff:ff:ff:ff:ff IGTK",
1094             "RESET_PN 22:22:22:22:22:22",
1095             "RESET_PN foo"]
1096    for t in tests:
1097        if "FAIL" not in hapd.request(t):
1098            raise Exception("Invalid command accepted: " + t)
1099
1100def test_ap_wpa2_gtk_initial_rsc_tkip(dev, apdev):
1101    """Initial group cipher RSC (TKIP)"""
1102    skip_without_tkip(dev[0])
1103    run_ap_wpa2_gtk_initial_rsc(dev, apdev, "TKIP")
1104
1105def test_ap_wpa2_gtk_initial_rsc_ccmp(dev, apdev):
1106    """Initial group cipher RSC (CCMP)"""
1107    run_ap_wpa2_gtk_initial_rsc(dev, apdev, "CCMP")
1108
1109def test_ap_wpa2_gtk_initial_rsc_ccmp_256(dev, apdev):
1110    """Initial group cipher RSC (CCMP-256)"""
1111    run_ap_wpa2_gtk_initial_rsc(dev, apdev, "CCMP-256")
1112
1113def test_ap_wpa2_gtk_initial_rsc_gcmp(dev, apdev):
1114    """Initial group cipher RSC (GCMP)"""
1115    run_ap_wpa2_gtk_initial_rsc(dev, apdev, "GCMP")
1116
1117def test_ap_wpa2_gtk_initial_rsc_gcmp_256(dev, apdev):
1118    """Initial group cipher RSC (GCMP-256)"""
1119    run_ap_wpa2_gtk_initial_rsc(dev, apdev, "GCMP-256")
1120
1121def run_ap_wpa2_gtk_initial_rsc(dev, apdev, cipher):
1122    if cipher not in dev[0].get_capability("pairwise") or \
1123       cipher not in dev[0].get_capability("group"):
1124        raise HwsimSkip("Cipher %s not supported" % cipher)
1125
1126    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
1127    params["rsn_pairwise"] = cipher
1128    params["group_cipher"] = cipher
1129    params["gtk_rsc_override"] = "341200000000"
1130    hapd = hostapd.add_ap(apdev[0], params)
1131
1132    Wlantest.setup(hapd)
1133    wt = Wlantest()
1134    wt.flush()
1135    wt.add_passphrase("12345678")
1136
1137    dev[0].connect("test-wpa2-psk", psk="12345678", proto="WPA2",
1138                   pairwise=cipher, group=cipher, scan_freq="2412")
1139    hapd.wait_sta()
1140    # Verify that unicast traffic works, but broadcast traffic does not.
1141    hwsim_utils.test_connectivity(dev[0], hapd, broadcast=False)
1142    hwsim_utils.test_connectivity(dev[0], hapd, success_expected=False)
1143    hwsim_utils.test_connectivity(dev[0], hapd, success_expected=False)
1144
1145def test_ap_wpa2_igtk_initial_rsc_aes_128_cmac(dev, apdev):
1146    """Initial management group cipher RSC (AES-128-CMAC)"""
1147    run_ap_wpa2_igtk_initial_rsc(dev, apdev, "AES-128-CMAC")
1148
1149def test_ap_wpa2_igtk_initial_rsc_bip_gmac_128(dev, apdev):
1150    """Initial management group cipher RSC (BIP-GMAC-128)"""
1151    run_ap_wpa2_igtk_initial_rsc(dev, apdev, "BIP-GMAC-128")
1152
1153def test_ap_wpa2_igtk_initial_rsc_bip_gmac_256(dev, apdev):
1154    """Initial management group cipher RSC (BIP-GMAC-256)"""
1155    run_ap_wpa2_igtk_initial_rsc(dev, apdev, "BIP-GMAC-256")
1156
1157def test_ap_wpa2_igtk_initial_rsc_bip_cmac_256(dev, apdev):
1158    """Initial management group cipher RSC (BIP-CMAC-256)"""
1159    run_ap_wpa2_igtk_initial_rsc(dev, apdev, "BIP-CMAC-256")
1160
1161def run_ap_wpa2_igtk_initial_rsc(dev, apdev, cipher):
1162    if cipher not in dev[0].get_capability("group_mgmt"):
1163        raise HwsimSkip("Cipher %s not supported" % cipher)
1164
1165    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
1166    params["ieee80211w"] = "2"
1167    params["rsn_pairwise"] = "CCMP"
1168    params["group_cipher"] = "CCMP"
1169    params["group_mgmt_cipher"] = cipher
1170    params["igtk_rsc_override"] = "341200000000"
1171    hapd = hostapd.add_ap(apdev[0], params)
1172
1173    Wlantest.setup(hapd)
1174    wt = Wlantest()
1175    wt.flush()
1176    wt.add_passphrase("12345678")
1177
1178    dev[0].connect("test-wpa2-psk", psk="12345678", proto="WPA2",
1179                   ieee80211w="2", pairwise="CCMP", group="CCMP",
1180                   group_mgmt=cipher,
1181                   scan_freq="2412")
1182    hapd.wait_sta()
1183    # Verify that broadcast robust management frames are dropped.
1184    dev[0].note("Sending broadcast Deauthentication and Disassociation frames with too small IPN")
1185    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff test=1")
1186    hapd.request("DISASSOCIATE ff:ff:ff:ff:ff:ff test=1")
1187    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff test=1")
1188    hapd.request("DISASSOCIATE ff:ff:ff:ff:ff:ff test=1")
1189    dev[0].note("Done sending broadcast Deauthentication and Disassociation frames with too small IPN")
1190    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
1191    if ev is not None:
1192        raise Exception("Unexpected disconnection")
1193
1194    # Verify thar unicast robust management frames go through.
1195    hapd.request("DEAUTHENTICATE " + dev[0].own_addr() + " reason=123 test=1")
1196    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
1197    if ev is None:
1198        raise Exception("Disconnection not reported")
1199    if "reason=123" not in ev:
1200        raise Exception("Unexpected disconnection reason: " + ev)
1201