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