1# Open mode AP tests
2# Copyright (c) 2014, Qualcomm Atheros, Inc.
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 logging
9logger = logging.getLogger()
10import struct
11import subprocess
12import time
13import os
14
15import hostapd
16import hwsim_utils
17from tshark import run_tshark
18from utils import *
19from wpasupplicant import WpaSupplicant
20from wlantest import WlantestCapture
21
22@remote_compatible
23def test_ap_open(dev, apdev):
24    """AP with open mode (no security) configuration"""
25    _test_ap_open(dev, apdev)
26
27def _test_ap_open(dev, apdev):
28    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
29    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
30                   bg_scan_period="0")
31    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=5)
32    if ev is None:
33        raise Exception("No connection event received from hostapd")
34    hwsim_utils.test_connectivity(dev[0], hapd)
35
36    dev[0].request("DISCONNECT")
37    ev = hapd.wait_event(["AP-STA-DISCONNECTED"], timeout=5)
38    if ev is None:
39        raise Exception("No disconnection event received from hostapd")
40
41def test_ap_open_packet_loss(dev, apdev):
42    """AP with open mode configuration and large packet loss"""
43    params = {"ssid": "open",
44              "ignore_probe_probability": "0.5",
45              "ignore_auth_probability": "0.5",
46              "ignore_assoc_probability": "0.5",
47              "ignore_reassoc_probability": "0.5"}
48    hapd = hostapd.add_ap(apdev[0], params)
49    for i in range(0, 3):
50        dev[i].connect("open", key_mgmt="NONE", scan_freq="2412",
51                       wait_connect=False)
52    for i in range(0, 3):
53        dev[i].wait_connected(timeout=20)
54
55@remote_compatible
56def test_ap_open_unknown_action(dev, apdev):
57    """AP with open mode configuration and unknown Action frame"""
58    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
59    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
60    bssid = apdev[0]['bssid']
61    cmd = "MGMT_TX {} {} freq=2412 action=765432".format(bssid, bssid)
62    if "FAIL" in dev[0].request(cmd):
63        raise Exception("Could not send test Action frame")
64    ev = dev[0].wait_event(["MGMT-TX-STATUS"], timeout=10)
65    if ev is None:
66        raise Exception("Timeout on MGMT-TX-STATUS")
67    if "result=SUCCESS" not in ev:
68        raise Exception("AP did not ack Action frame")
69
70def test_ap_open_invalid_wmm_action(dev, apdev):
71    """AP with open mode configuration and invalid WMM Action frame"""
72    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
73    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
74    bssid = apdev[0]['bssid']
75    cmd = "MGMT_TX {} {} freq=2412 action=1100".format(bssid, bssid)
76    if "FAIL" in dev[0].request(cmd):
77        raise Exception("Could not send test Action frame")
78    ev = dev[0].wait_event(["MGMT-TX-STATUS"], timeout=10)
79    if ev is None or "result=SUCCESS" not in ev:
80        raise Exception("AP did not ack Action frame")
81
82@remote_compatible
83def test_ap_open_reconnect_on_inactivity_disconnect(dev, apdev):
84    """Reconnect to open mode AP after inactivity related disconnection"""
85    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
86    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
87    hapd.request("DEAUTHENTICATE " + dev[0].p2p_interface_addr() + " reason=4")
88    dev[0].wait_disconnected(timeout=5)
89    dev[0].wait_connected(timeout=2, error="Timeout on reconnection")
90
91@remote_compatible
92def test_ap_open_assoc_timeout(dev, apdev):
93    """AP timing out association"""
94    ssid = "test"
95    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
96    dev[0].scan(freq="2412")
97    hapd.set("ext_mgmt_frame_handling", "1")
98    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
99                   wait_connect=False)
100    for i in range(0, 10):
101        req = hapd.mgmt_rx()
102        if req is None:
103            raise Exception("MGMT RX wait timed out")
104        if req['subtype'] == 11:
105            break
106        req = None
107    if not req:
108        raise Exception("Authentication frame not received")
109
110    resp = {}
111    resp['fc'] = req['fc']
112    resp['da'] = req['sa']
113    resp['sa'] = req['da']
114    resp['bssid'] = req['bssid']
115    resp['payload'] = struct.pack('<HHH', 0, 2, 0)
116    hapd.mgmt_tx(resp)
117
118    assoc = 0
119    for i in range(0, 10):
120        req = hapd.mgmt_rx()
121        if req is None:
122            raise Exception("MGMT RX wait timed out")
123        if req['subtype'] == 0:
124            assoc += 1
125            if assoc == 3:
126                break
127    if assoc != 3:
128        raise Exception("Association Request frames not received: assoc=%d" % assoc)
129    hapd.set("ext_mgmt_frame_handling", "0")
130    dev[0].wait_connected(timeout=15)
131
132def test_ap_open_auth_drop_sta(dev, apdev):
133    """AP dropping station after successful authentication"""
134    hapd = hostapd.add_ap(apdev[0]['ifname'], {"ssid": "open"})
135    dev[0].scan(freq="2412")
136    hapd.set("ext_mgmt_frame_handling", "1")
137    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
138                   wait_connect=False)
139    for i in range(0, 10):
140        req = hapd.mgmt_rx()
141        if req is None:
142            raise Exception("MGMT RX wait timed out")
143        if req['subtype'] == 11:
144            break
145        req = None
146    if not req:
147        raise Exception("Authentication frame not received")
148
149    # turn off before sending successful response
150    hapd.set("ext_mgmt_frame_handling", "0")
151
152    resp = {}
153    resp['fc'] = req['fc']
154    resp['da'] = req['sa']
155    resp['sa'] = req['da']
156    resp['bssid'] = req['bssid']
157    resp['payload'] = struct.pack('<HHH', 0, 2, 0)
158    hapd.mgmt_tx(resp)
159
160    dev[0].wait_connected(timeout=15)
161
162@remote_compatible
163def test_ap_open_id_str(dev, apdev):
164    """AP with open mode and id_str"""
165    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
166    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412", id_str="foo",
167                   wait_connect=False)
168    ev = dev[0].wait_connected(timeout=10)
169    if "id_str=foo" not in ev:
170        raise Exception("CTRL-EVENT-CONNECT did not have matching id_str: " + ev)
171    if dev[0].get_status_field("id_str") != "foo":
172        raise Exception("id_str mismatch")
173
174@remote_compatible
175def test_ap_open_select_any(dev, apdev):
176    """AP with open mode and select any network"""
177    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
178    id = dev[0].connect("unknown", key_mgmt="NONE", scan_freq="2412",
179                        only_add_network=True)
180    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
181                   only_add_network=True)
182    dev[0].select_network(id)
183    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND",
184                            "CTRL-EVENT-CONNECTED"], timeout=10)
185    if ev is None:
186        raise Exception("No result reported")
187    if "CTRL-EVENT-CONNECTED" in ev:
188        raise Exception("Unexpected connection")
189
190    dev[0].select_network("any")
191    dev[0].wait_connected(timeout=10)
192
193@remote_compatible
194def test_ap_open_unexpected_assoc_event(dev, apdev):
195    """AP with open mode and unexpected association event"""
196    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
197    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
198    dev[0].request("DISCONNECT")
199    dev[0].wait_disconnected(timeout=15)
200    dev[0].dump_monitor()
201    # This association will be ignored by wpa_supplicant since the current
202    # state is not to try to connect after that DISCONNECT command.
203    dev[0].cmd_execute(['iw', 'dev', dev[0].ifname, 'connect', 'open', "2412",
204                        apdev[0]['bssid']])
205    ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.3)
206    dev[0].cmd_execute(['iw', 'dev', dev[0].ifname, 'disconnect'])
207    dev[0].dump_monitor()
208    if ev is not None:
209        raise Exception("Unexpected connection")
210
211def test_ap_open_external_assoc(dev, apdev):
212    """AP with open mode and external association"""
213    hapd = hostapd.add_ap(apdev[0], {"ssid": "open-ext-assoc"})
214    try:
215        dev[0].request("STA_AUTOCONNECT 0")
216        id = dev[0].connect("open-ext-assoc", key_mgmt="NONE", scan_freq="2412",
217                            only_add_network=True)
218        dev[0].request("ENABLE_NETWORK %s no-connect" % id)
219        dev[0].dump_monitor()
220        # This will be accepted due to matching network
221        dev[0].cmd_execute(['iw', 'dev', dev[0].ifname, 'connect',
222                            'open-ext-assoc', "2412", apdev[0]['bssid']])
223        ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED",
224                                "CTRL-EVENT-CONNECTED"], timeout=10)
225        if ev is None:
226            raise Exception("Connection timed out")
227        if "CTRL-EVENT-DISCONNECTED" in ev:
228            raise Exception("Unexpected disconnection event")
229        dev[0].dump_monitor()
230        dev[0].request("DISCONNECT")
231        dev[0].wait_disconnected(timeout=5)
232    finally:
233        dev[0].request("STA_AUTOCONNECT 1")
234
235@remote_compatible
236def test_ap_bss_load(dev, apdev):
237    """AP with open mode (no security) configuration"""
238    hapd = hostapd.add_ap(apdev[0],
239                          {"ssid": "open",
240                           "bss_load_update_period": "10",
241                           "chan_util_avg_period": "20"})
242    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
243    # this does not really get much useful output with mac80211_hwsim currently,
244    # but run through the channel survey update couple of times
245    for i in range(0, 10):
246        hwsim_utils.test_connectivity(dev[0], hapd)
247        hwsim_utils.test_connectivity(dev[0], hapd)
248        hwsim_utils.test_connectivity(dev[0], hapd)
249        time.sleep(0.15)
250    avg = hapd.get_status_field("chan_util_avg")
251    if avg is None:
252        raise Exception("No STATUS chan_util_avg seen")
253
254def test_ap_bss_load_fail(dev, apdev):
255    """BSS Load update failing to get survey data"""
256    hapd = hostapd.add_ap(apdev[0],
257                          {"ssid": "open",
258                           "bss_load_update_period": "1"})
259    with fail_test(hapd, 1, "wpa_driver_nl80211_get_survey"):
260        wait_fail_trigger(hapd, "GET_FAIL")
261
262def hapd_out_of_mem(hapd, apdev, count, func):
263    with alloc_fail(hapd, count, func):
264        started = False
265        try:
266            hostapd.add_ap(apdev, {"ssid": "open"})
267            started = True
268        except:
269            pass
270        if started:
271            raise Exception("hostapd interface started even with memory allocation failure: %d:%s" % (count, func))
272
273def test_ap_open_out_of_memory(dev, apdev):
274    """hostapd failing to setup interface due to allocation failure"""
275    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
276    flags2 = hapd.request("DRIVER_FLAGS2").splitlines()[1:]
277    hapd_out_of_mem(hapd, apdev[1], 1, "hostapd_alloc_bss_data")
278
279    for i in range(1, 3):
280        hapd_out_of_mem(hapd, apdev[1], i, "hostapd_iface_alloc")
281
282    for i in range(1, 5):
283        hapd_out_of_mem(hapd, apdev[1], i, "hostapd_config_defaults;hostapd_config_alloc")
284
285    hapd_out_of_mem(hapd, apdev[1], 1, "hostapd_config_alloc")
286
287    hapd_out_of_mem(hapd, apdev[1], 1, "hostapd_driver_init")
288
289    for i in range(1, 3):
290        hapd_out_of_mem(hapd, apdev[1], i, "=wpa_driver_nl80211_drv_init")
291
292    if 'CONTROL_PORT_RX' not in flags2:
293        # eloop_register_read_sock() call from i802_init()
294        hapd_out_of_mem(hapd, apdev[1], 1, "eloop_sock_table_add_sock;?eloop_register_sock;?eloop_register_read_sock;=i802_init")
295
296    # verify that a new interface can still be added when memory allocation does
297    # not fail
298    hostapd.add_ap(apdev[1], {"ssid": "open"})
299
300def test_bssid_ignore_accept(dev, apdev):
301    """BSSID ignore/accept list"""
302    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
303    hapd2 = hostapd.add_ap(apdev[1], {"ssid": "open"})
304
305    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
306                   bssid_accept=apdev[1]['bssid'])
307    dev[1].connect("open", key_mgmt="NONE", scan_freq="2412",
308                   bssid_ignore=apdev[1]['bssid'])
309    dev[2].connect("open", key_mgmt="NONE", scan_freq="2412",
310                   bssid_accept="00:00:00:00:00:00/00:00:00:00:00:00",
311                   bssid_ignore=apdev[1]['bssid'])
312    if dev[0].get_status_field('bssid') != apdev[1]['bssid']:
313        raise Exception("dev[0] connected to unexpected AP")
314    if dev[1].get_status_field('bssid') != apdev[0]['bssid']:
315        raise Exception("dev[1] connected to unexpected AP")
316    if dev[2].get_status_field('bssid') != apdev[0]['bssid']:
317        raise Exception("dev[2] connected to unexpected AP")
318    dev[0].request("REMOVE_NETWORK all")
319    dev[1].request("REMOVE_NETWORK all")
320    dev[2].request("REMOVE_NETWORK all")
321
322    dev[2].connect("open", key_mgmt="NONE", scan_freq="2412",
323                   bssid_accept="00:00:00:00:00:00", wait_connect=False)
324    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
325                   bssid_accept="11:22:33:44:55:66/ff:00:00:00:00:00 " + apdev[1]['bssid'] + " aa:bb:cc:dd:ee:ff")
326    dev[1].connect("open", key_mgmt="NONE", scan_freq="2412",
327                   bssid_ignore="11:22:33:44:55:66/ff:00:00:00:00:00 " + apdev[1]['bssid'] + " aa:bb:cc:dd:ee:ff")
328    if dev[0].get_status_field('bssid') != apdev[1]['bssid']:
329        raise Exception("dev[0] connected to unexpected AP")
330    if dev[1].get_status_field('bssid') != apdev[0]['bssid']:
331        raise Exception("dev[1] connected to unexpected AP")
332    dev[0].request("REMOVE_NETWORK all")
333    dev[1].request("REMOVE_NETWORK all")
334    ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
335    if ev is not None:
336        raise Exception("Unexpected dev[2] connectin")
337    dev[2].request("REMOVE_NETWORK all")
338
339def test_ap_open_wpas_in_bridge(dev, apdev):
340    """Open mode AP and wpas interface in a bridge"""
341    br_ifname = 'sta-br0'
342    ifname = 'wlan5'
343    try:
344        _test_ap_open_wpas_in_bridge(dev, apdev)
345    finally:
346        subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
347        subprocess.call(['brctl', 'delif', br_ifname, ifname])
348        subprocess.call(['brctl', 'delbr', br_ifname])
349        subprocess.call(['iw', ifname, 'set', '4addr', 'off'])
350
351def _test_ap_open_wpas_in_bridge(dev, apdev):
352    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
353
354    br_ifname = 'sta-br0'
355    ifname = 'wlan5'
356    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
357    # First, try a failure case of adding an interface
358    try:
359        wpas.interface_add(ifname, br_ifname=br_ifname)
360        raise Exception("Interface addition succeeded unexpectedly")
361    except Exception as e:
362        if "Failed to add" in str(e):
363            logger.info("Ignore expected interface_add failure due to missing bridge interface: " + str(e))
364        else:
365            raise
366
367    # Next, add the bridge interface and add the interface again
368    subprocess.call(['brctl', 'addbr', br_ifname])
369    subprocess.call(['brctl', 'setfd', br_ifname, '0'])
370    subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
371    subprocess.call(['iw', ifname, 'set', '4addr', 'on'])
372    subprocess.check_call(['brctl', 'addif', br_ifname, ifname])
373    wpas.interface_add(ifname, br_ifname=br_ifname)
374
375    wpas.connect("open", key_mgmt="NONE", scan_freq="2412")
376
377@remote_compatible
378def test_ap_open_start_disabled(dev, apdev):
379    """AP with open mode and beaconing disabled"""
380    hapd = hostapd.add_ap(apdev[0], {"ssid": "open",
381                                     "start_disabled": "1"})
382    bssid = apdev[0]['bssid']
383
384    dev[0].flush_scan_cache()
385    dev[0].scan(freq=2412, only_new=True)
386    if dev[0].get_bss(bssid) is not None:
387        raise Exception("AP was seen beaconing")
388    if "OK" not in hapd.request("RELOAD"):
389        raise Exception("RELOAD failed")
390    dev[0].scan_for_bss(bssid, freq=2412)
391    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
392
393@remote_compatible
394def test_ap_open_start_disabled2(dev, apdev):
395    """AP with open mode and beaconing disabled (2)"""
396    hapd = hostapd.add_ap(apdev[0], {"ssid": "open",
397                                     "start_disabled": "1"})
398    bssid = apdev[0]['bssid']
399
400    dev[0].flush_scan_cache()
401    dev[0].scan(freq=2412, only_new=True)
402    if dev[0].get_bss(bssid) is not None:
403        raise Exception("AP was seen beaconing")
404    if "OK" not in hapd.request("UPDATE_BEACON"):
405        raise Exception("UPDATE_BEACON failed")
406    dev[0].scan_for_bss(bssid, freq=2412)
407    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
408    if "OK" not in hapd.request("UPDATE_BEACON"):
409        raise Exception("UPDATE_BEACON failed")
410    dev[0].request("DISCONNECT")
411    dev[0].wait_disconnected()
412    dev[0].request("RECONNECT")
413    dev[0].wait_connected()
414
415@remote_compatible
416def test_ap_open_ifdown(dev, apdev):
417    """AP with open mode and external ifconfig down"""
418    params = {"ssid": "open",
419              "ap_max_inactivity": "1"}
420    hapd = hostapd.add_ap(apdev[0], params)
421    bssid = apdev[0]['bssid']
422
423    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
424    dev[1].connect("open", key_mgmt="NONE", scan_freq="2412")
425    hapd.cmd_execute(['ip', 'link', 'set', 'dev', apdev[0]['ifname'], 'down'])
426    ev = hapd.wait_event(["AP-STA-DISCONNECTED"], timeout=10)
427    if ev is None:
428        raise Exception("Timeout on AP-STA-DISCONNECTED (1)")
429    ev = hapd.wait_event(["AP-STA-DISCONNECTED"], timeout=5)
430    if ev is None:
431        raise Exception("Timeout on AP-STA-DISCONNECTED (2)")
432    ev = hapd.wait_event(["INTERFACE-DISABLED"], timeout=5)
433    if ev is None:
434        raise Exception("No INTERFACE-DISABLED event")
435    # The following wait tests beacon loss detection in mac80211 on dev0.
436    # dev1 is used to test stopping of AP side functionality on client polling.
437    dev[1].request("REMOVE_NETWORK all")
438    hapd.cmd_execute(['ip', 'link', 'set', 'dev', apdev[0]['ifname'], 'up'])
439    dev[0].wait_disconnected()
440    dev[1].wait_disconnected()
441    ev = hapd.wait_event(["INTERFACE-ENABLED"], timeout=10)
442    if ev is None:
443        raise Exception("No INTERFACE-ENABLED event")
444    dev[0].wait_connected()
445    hwsim_utils.test_connectivity(dev[0], hapd)
446
447def test_ap_open_disconnect_in_ps(dev, apdev, params):
448    """Disconnect with the client in PS to regression-test a kernel bug"""
449    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
450    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
451                   bg_scan_period="0")
452    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=5)
453    if ev is None:
454        raise Exception("No connection event received from hostapd")
455
456    time.sleep(0.2)
457    # enable power save mode
458    hwsim_utils.set_powersave(dev[0], hwsim_utils.PS_ENABLED)
459    time.sleep(0.1)
460    try:
461        # inject some traffic
462        sa = hapd.own_addr()
463        da = dev[0].own_addr()
464        hapd.request('DATA_TEST_CONFIG 1')
465        hapd.request('DATA_TEST_TX {} {} 0'.format(da, sa))
466        hapd.request('DATA_TEST_CONFIG 0')
467
468        # let the AP send couple of Beacon frames
469        time.sleep(0.3)
470
471        # disconnect - with traffic pending - shouldn't cause kernel warnings
472        dev[0].request("DISCONNECT")
473    finally:
474        hwsim_utils.set_powersave(dev[0], hwsim_utils.PS_DISABLED)
475
476    time.sleep(0.2)
477    out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
478                     "wlan_mgt.tim.partial_virtual_bitmap",
479                     ["wlan_mgt.tim.partial_virtual_bitmap"])
480    if out is not None:
481        state = 0
482        for l in out.splitlines():
483            pvb = int(l, 16)
484            if pvb > 0 and state == 0:
485                state = 1
486            elif pvb == 0 and state == 1:
487                state = 2
488        if state != 2:
489            raise Exception("Didn't observe TIM bit getting set and unset (state=%d)" % state)
490
491def test_ap_open_sta_ps(dev, apdev):
492    """Station power save operation"""
493    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
494    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
495                   bg_scan_period="0")
496    hapd.wait_sta()
497
498    time.sleep(0.2)
499    try:
500        dev[0].cmd_execute(['iw', 'dev', dev[0].ifname,
501                            'set', 'power_save', 'on'])
502        run_ap_open_sta_ps(dev, hapd)
503    finally:
504        dev[0].cmd_execute(['iw', 'dev', dev[0].ifname,
505                            'set', 'power_save', 'off'])
506
507def run_ap_open_sta_ps(dev, hapd):
508    hwsim_utils.test_connectivity(dev[0], hapd)
509    # Give time to enter PS
510    time.sleep(0.2)
511
512    phyname = dev[0].get_driver_status_field("phyname")
513    hw_conf = '/sys/kernel/debug/ieee80211/' + phyname + '/hw_conf'
514
515    try:
516        ok = False
517        for i in range(10):
518            with open(hw_conf, 'r') as f:
519                val = int(f.read())
520            if val & 2:
521                ok = True
522                break
523            time.sleep(0.2)
524
525        if not ok:
526            raise Exception("STA did not enter power save")
527
528        dev[0].dump_monitor()
529        hapd.dump_monitor()
530        hapd.request("DEAUTHENTICATE " + dev[0].own_addr())
531        dev[0].wait_disconnected()
532    except FileNotFoundError:
533        raise HwsimSkip("Kernel does not support inspecting HW PS state")
534
535def test_ap_open_ps_mc_buf(dev, apdev, params):
536    """Multicast buffering with a station in power save"""
537    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
538    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
539                   bg_scan_period="0")
540    hapd.wait_sta()
541
542    buffered_mcast = 0
543    try:
544        dev[0].cmd_execute(['iw', 'dev', dev[0].ifname,
545                            'set', 'power_save', 'on'])
546        # Give time to enter PS
547        time.sleep(0.3)
548
549        for i in range(10):
550            # Verify that multicast frames are released
551            hwsim_utils.run_multicast_connectivity_test(hapd, dev[0])
552
553            # Check frames were buffered until DTIM
554            out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
555                             "wlan.fc.type_subtype == 0x0008",
556                             ["wlan.tim.bmapctl.multicast"])
557            for line in out.splitlines():
558                buffered_mcast = int(line)
559                if buffered_mcast == 1:
560                    break
561            if buffered_mcast == 1:
562                break
563    finally:
564        dev[0].cmd_execute(['iw', 'dev', dev[0].ifname,
565                            'set', 'power_save', 'off'])
566
567    if buffered_mcast != 1:
568        raise Exception("AP did not buffer multicast frames")
569
570@remote_compatible
571def test_ap_open_select_network(dev, apdev):
572    """Open mode connection and SELECT_NETWORK to change network"""
573    hapd1 = hostapd.add_ap(apdev[0], {"ssid": "open"})
574    bssid1 = apdev[0]['bssid']
575    hapd2 = hostapd.add_ap(apdev[1], {"ssid": "open2"})
576    bssid2 = apdev[1]['bssid']
577
578    id1 = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
579                         only_add_network=True)
580    id2 = dev[0].connect("open2", key_mgmt="NONE", scan_freq="2412")
581    hwsim_utils.test_connectivity(dev[0], hapd2)
582
583    dev[0].select_network(id1)
584    dev[0].wait_connected()
585    res = dev[0].request("BSSID_IGNORE")
586    if bssid1 in res or bssid2 in res:
587        raise Exception("Unexpected BSSID ignore list entry")
588    hwsim_utils.test_connectivity(dev[0], hapd1)
589
590    dev[0].select_network(id2)
591    dev[0].wait_connected()
592    hwsim_utils.test_connectivity(dev[0], hapd2)
593    res = dev[0].request("BSSID_IGNORE")
594    if bssid1 in res or bssid2 in res:
595        raise Exception("Unexpected BSSID ignore list entry(2)")
596
597@remote_compatible
598def test_ap_open_disable_enable(dev, apdev):
599    """AP with open mode getting disabled and re-enabled"""
600    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
601    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
602                   bg_scan_period="0")
603
604    for i in range(2):
605        hapd.request("DISABLE")
606        dev[0].wait_disconnected()
607        hapd.request("ENABLE")
608        dev[0].wait_connected()
609        hwsim_utils.test_connectivity(dev[0], hapd)
610
611def sta_enable_disable(dev, bssid):
612    dev.scan_for_bss(bssid, freq=2412)
613    work_id = dev.request("RADIO_WORK add block-work")
614    ev = dev.wait_event(["EXT-RADIO-WORK-START"])
615    if ev is None:
616        raise Exception("Timeout while waiting radio work to start")
617    id = dev.connect("open", key_mgmt="NONE", scan_freq="2412",
618                     only_add_network=True)
619    dev.request("ENABLE_NETWORK %d" % id)
620    if "connect@" not in dev.request("RADIO_WORK show"):
621        raise Exception("connect radio work missing")
622    dev.request("DISABLE_NETWORK %d" % id)
623    dev.request("RADIO_WORK done " + work_id)
624
625    ok = False
626    for i in range(30):
627        if "connect@" not in dev.request("RADIO_WORK show"):
628            ok = True
629            break
630        time.sleep(0.1)
631    if not ok:
632        raise Exception("connect radio work not completed")
633    ev = dev.wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
634    if ev is not None:
635        raise Exception("Unexpected connection")
636    dev.request("DISCONNECT")
637
638def test_ap_open_sta_enable_disable(dev, apdev):
639    """AP with open mode and wpa_supplicant ENABLE/DISABLE_NETWORK"""
640    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
641    bssid = apdev[0]['bssid']
642
643    sta_enable_disable(dev[0], bssid)
644
645    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
646    wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
647    sta_enable_disable(wpas, bssid)
648
649@remote_compatible
650def test_ap_open_select_twice(dev, apdev):
651    """AP with open mode and select network twice"""
652    id = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
653                        only_add_network=True)
654    dev[0].select_network(id)
655    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
656    if ev is None:
657        raise Exception("No result reported")
658    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
659    # Verify that the second SELECT_NETWORK starts a new scan immediately by
660    # waiting less than the default scan period.
661    dev[0].select_network(id)
662    dev[0].wait_connected(timeout=3)
663
664@remote_compatible
665def test_ap_open_reassoc_not_found(dev, apdev):
666    """AP with open mode and REASSOCIATE not finding a match"""
667    id = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
668                        only_add_network=True)
669    dev[0].select_network(id)
670    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
671    if ev is None:
672        raise Exception("No result reported")
673    dev[0].request("DISCONNECT")
674
675    time.sleep(0.1)
676    dev[0].dump_monitor()
677
678    dev[0].request("REASSOCIATE")
679    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
680    if ev is None:
681        raise Exception("No result reported")
682    dev[0].request("DISCONNECT")
683
684@remote_compatible
685def test_ap_open_sta_statistics(dev, apdev):
686    """AP with open mode and STA statistics"""
687    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
688    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
689    addr = dev[0].own_addr()
690
691    stats1 = hapd.get_sta(addr)
692    logger.info("stats1: " + str(stats1))
693    time.sleep(0.4)
694    stats2 = hapd.get_sta(addr)
695    logger.info("stats2: " + str(stats2))
696    hwsim_utils.test_connectivity(dev[0], hapd)
697    stats3 = hapd.get_sta(addr)
698    logger.info("stats3: " + str(stats3))
699
700    # Cannot require specific inactive_msec changes without getting rid of all
701    # unrelated traffic, so for now, just print out the results in the log for
702    # manual checks.
703
704@remote_compatible
705def test_ap_open_poll_sta(dev, apdev):
706    """AP with open mode and STA poll"""
707    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
708    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
709    addr = dev[0].own_addr()
710
711    if "OK" not in hapd.request("POLL_STA " + addr):
712        raise Exception("POLL_STA failed")
713    ev = hapd.wait_event(["AP-STA-POLL-OK"], timeout=5)
714    if ev is None:
715        raise Exception("Poll response not seen")
716    if addr not in ev:
717        raise Exception("Unexpected poll response: " + ev)
718
719def test_ap_open_poll_sta_no_ack(dev, apdev):
720    """AP with open mode and STA poll without ACK"""
721    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
722    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
723    addr = dev[0].own_addr()
724
725    hapd.set("ext_mgmt_frame_handling", "1")
726    dev[0].request("DISCONNECT")
727    dev[0].wait_disconnected()
728    # eat up the deauth frame, so it cannot be processed
729    # after we disable ext_mgmt_frame_handling again
730    hapd.wait_event(["MGMT-RX"], timeout=1)
731    hapd.set("ext_mgmt_frame_handling", "0")
732    if "OK" not in hapd.request("POLL_STA " + addr):
733        raise Exception("POLL_STA failed")
734    ev = hapd.wait_event(["AP-STA-POLL-OK"], timeout=1)
735    if ev is not None:
736        raise Exception("Unexpected poll response reported")
737
738def test_ap_open_pmf_default(dev, apdev):
739    """AP with open mode (no security) configuration and pmf=2"""
740    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
741    dev[1].connect("open", key_mgmt="NONE", scan_freq="2412",
742                   ieee80211w="2", wait_connect=False)
743    dev[2].connect("open", key_mgmt="NONE", scan_freq="2412",
744                   ieee80211w="1")
745    try:
746        dev[0].request("SET pmf 2")
747        dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
748
749        dev[0].request("DISCONNECT")
750        dev[0].wait_disconnected()
751    finally:
752        dev[0].request("SET pmf 0")
753    dev[2].request("DISCONNECT")
754    dev[2].wait_disconnected()
755
756    ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
757    if ev is not None:
758        raise Exception("Unexpected dev[1] connection")
759    dev[1].request("DISCONNECT")
760
761def test_ap_open_drv_fail(dev, apdev):
762    """AP with open mode and driver operations failing"""
763    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
764
765    with fail_test(dev[0], 1, "wpa_driver_nl80211_authenticate"):
766        dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
767                       wait_connect=False)
768        wait_fail_trigger(dev[0], "GET_FAIL")
769        dev[0].request("REMOVE_NETWORK all")
770
771    with fail_test(dev[0], 1, "wpa_driver_nl80211_associate"):
772        dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
773                       wait_connect=False)
774        wait_fail_trigger(dev[0], "GET_FAIL")
775        dev[0].request("REMOVE_NETWORK all")
776
777def run_multicast_to_unicast(dev, apdev, convert):
778    params = {"ssid": "open"}
779    params["multicast_to_unicast"] = "1" if convert else "0"
780    hapd = hostapd.add_ap(apdev[0], params)
781    dev[0].scan_for_bss(hapd.own_addr(), freq=2412)
782    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
783    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=5)
784    if ev is None:
785        raise Exception("No connection event received from hostapd")
786    hwsim_utils.test_connectivity(dev[0], hapd, multicast_to_unicast=convert)
787    dev[0].request("DISCONNECT")
788    ev = hapd.wait_event(["AP-STA-DISCONNECTED"], timeout=5)
789    if ev is None:
790        raise Exception("No disconnection event received from hostapd")
791
792def test_ap_open_multicast_to_unicast(dev, apdev):
793    """Multicast-to-unicast conversion enabled"""
794    run_multicast_to_unicast(dev, apdev, True)
795
796def test_ap_open_multicast_to_unicast_disabled(dev, apdev):
797    """Multicast-to-unicast conversion disabled"""
798    run_multicast_to_unicast(dev, apdev, False)
799
800def test_ap_open_drop_duplicate(dev, apdev, params):
801    """AP dropping duplicate management frames"""
802    hapd = hostapd.add_ap(apdev[0], {"ssid": "open",
803                                     "interworking": "1"})
804    hapd.set("ext_mgmt_frame_handling", "1")
805    bssid = hapd.own_addr().replace(':', '')
806    addr = "020304050607"
807    auth = "b0003a01" + bssid + addr + bssid + '1000000001000000'
808    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % auth):
809        raise Exception("MGMT_RX_PROCESS failed")
810    auth = "b0083a01" + bssid + addr + bssid + '1000000001000000'
811    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % auth):
812        raise Exception("MGMT_RX_PROCESS failed")
813
814    ies = "00046f70656e010802040b160c12182432043048606c2d1a3c101bffff0000000000000000000001000000000000000000007f0a04000a020140004000013b155151525354737475767778797a7b7c7d7e7f808182dd070050f202000100"
815    assoc_req = "00003a01" + bssid + addr + bssid + "2000" + "21040500" + ies
816    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % assoc_req):
817        raise Exception("MGMT_RX_PROCESS failed")
818    assoc_req = "00083a01" + bssid + addr + bssid + "2000" + "21040500" + ies
819    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % assoc_req):
820        raise Exception("MGMT_RX_PROCESS failed")
821    reassoc_req = "20083a01" + bssid + addr + bssid + "2000" + "21040500" + ies
822    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % reassoc_req):
823        raise Exception("MGMT_RX_PROCESS failed")
824    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % reassoc_req):
825        raise Exception("MGMT_RX_PROCESS failed")
826
827    action = "d0003a01" + bssid + addr + bssid + "1000" + "040a006c0200000600000102000101"
828    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % action):
829        raise Exception("MGMT_RX_PROCESS failed")
830
831    action = "d0083a01" + bssid + addr + bssid + "1000" + "040a006c0200000600000102000101"
832    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % action):
833        raise Exception("MGMT_RX_PROCESS failed")
834
835    out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
836                     "wlan.fc.type == 0", ["wlan.fc.subtype"])
837    num_auth = 0
838    num_assoc = 0
839    num_reassoc = 0
840    num_action = 0
841    for subtype in out.splitlines():
842        val = int(subtype)
843        if val == 11:
844            num_auth += 1
845        elif val == 1:
846            num_assoc += 1
847        elif val == 3:
848            num_reassoc += 1
849        elif val == 13:
850            num_action += 1
851    if num_auth != 1:
852        raise Exception("Unexpected number of Authentication frames: %d" % num_auth)
853    if num_assoc != 1:
854        raise Exception("Unexpected number of association frames: %d" % num_assoc)
855    if num_reassoc != 1:
856        raise Exception("Unexpected number of reassociation frames: %d" % num_reassoc)
857    if num_action != 1:
858        raise Exception("Unexpected number of Action frames: %d" % num_action)
859
860def test_ap_open_select_network_freq(dev, apdev):
861    """AP with open mode and use for SELECT_NETWORK freq parameter"""
862    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
863    id = dev[0].connect("open", key_mgmt="NONE", only_add_network=True)
864    dev[0].select_network(id, freq=2412)
865    start = os.times()[4]
866    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
867    if ev is None:
868        raise Exception("Scan not started")
869    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=15)
870    if ev is None:
871        raise Exception("Scan not completed")
872    end = os.times()[4]
873    logger.info("Scan duration: {} seconds".format(end - start))
874    if end - start > 3:
875        raise Exception("Scan took unexpectedly long time")
876    dev[0].wait_connected()
877
878def test_ap_open_noncountry(dev, apdev):
879    """AP with open mode and noncountry entity as Country String"""
880    _test_ap_open_country(dev, apdev, "XX", "0x58")
881
882def test_ap_open_country_table_e4(dev, apdev):
883    """AP with open mode and Table E-4 Country String"""
884    _test_ap_open_country(dev, apdev, "DE", "0x04")
885
886def test_ap_open_country_indoor(dev, apdev):
887    """AP with open mode and indoor country code"""
888    _test_ap_open_country(dev, apdev, "DE", "0x49")
889
890def test_ap_open_country_outdoor(dev, apdev):
891    """AP with open mode and outdoor country code"""
892    _test_ap_open_country(dev, apdev, "DE", "0x4f")
893
894def _test_ap_open_country(dev, apdev, country_code, country3):
895    try:
896        hapd = None
897        hapd = run_ap_open_country(dev, apdev, country_code, country3)
898    finally:
899        clear_regdom(hapd, dev)
900
901def run_ap_open_country(dev, apdev, country_code, country3):
902    hapd = hostapd.add_ap(apdev[0], {"ssid": "open",
903                                     "country_code": country_code,
904                                     "country3": country3,
905                                     "ieee80211d": "1"})
906    dev[0].scan_for_bss(hapd.own_addr(), freq=2412)
907    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
908    dev[0].wait_regdom(country_ie=True)
909    return hapd
910
911def test_ap_open_disable_select(dev, apdev):
912    """DISABLE_NETWORK for connected AP followed by SELECT_NETWORK"""
913    hapd1 = hostapd.add_ap(apdev[0], {"ssid": "open"})
914    hapd2 = hostapd.add_ap(apdev[1], {"ssid": "open"})
915    id = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
916
917    dev[0].request("DISABLE_NETWORK %d" % id)
918    dev[0].wait_disconnected()
919    res = dev[0].request("BSSID_IGNORE")
920    if hapd1.own_addr() in res or hapd2.own_addr() in res:
921        raise Exception("Unexpected BSSID ignore list entry added")
922    dev[0].request("SELECT_NETWORK %d" % id)
923    dev[0].wait_connected()
924
925def test_ap_open_reassoc_same(dev, apdev):
926    """AP with open mode and STA reassociating back to same AP without auth exchange"""
927    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
928    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
929    try:
930        dev[0].request("SET reassoc_same_bss_optim 1")
931        dev[0].request("REATTACH")
932        dev[0].wait_connected()
933        hwsim_utils.test_connectivity(dev[0], hapd)
934    finally:
935        dev[0].request("SET reassoc_same_bss_optim 0")
936
937def test_ap_open_no_reflection(dev, apdev):
938    """AP with open mode, STA sending packets to itself"""
939    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
940    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
941
942    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=5)
943    if ev is None:
944        raise Exception("No connection event received from hostapd")
945    # test normal connectivity is OK
946    hwsim_utils.test_connectivity(dev[0], hapd)
947
948    # test that we can't talk to ourselves
949    addr = dev[0].own_addr()
950    res = dev[0].request('DATA_TEST_CONFIG 1')
951    try:
952        assert 'OK' in res
953
954        cmd = "DATA_TEST_TX {} {} {}".format(addr, addr, 0)
955        dev[0].request(cmd)
956
957        ev = dev[0].wait_event(["DATA-TEST-RX"], timeout=1)
958
959        if ev is not None and "DATA-TEST-RX {} {}".format(addr, addr) in ev:
960            raise Exception("STA can unexpectedly talk to itself")
961    finally:
962        dev[0].request('DATA_TEST_CONFIG 0')
963
964def test_ap_no_auth_ack(dev, apdev):
965    """AP not receiving Authentication frame ACK"""
966    hapd = hostapd.add_ap(apdev[0], {"ssid": "open",
967                                     "ap_max_inactivity": "1"})
968    hapd.set("ext_mgmt_frame_handling", "1")
969
970    # Avoid race condition with TX status reporting for the broadcast
971    # Deauthentication frame.
972    hapd.wait_event(["MGMT-TX-STATUS"], timeout=0.1)
973
974    bssid = hapd.own_addr()
975    addr = "02:01:02:03:04:05"
976    frame = "b0003a01" + bssid.replace(':', '') + addr.replace(':', '') + bssid.replace(':', '') + "1000" + "000001000000"
977    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + frame):
978        raise Exception("MGMT_RX_PROCESS failed")
979    ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
980    if ev is None:
981        raise Exception("TX status for Authentication frame not reported")
982    if "ok=0 buf=b0" not in ev:
983        raise Exception("Unexpected TX status contents: " + ev)
984
985    # wait for STA to be removed due to timeout
986    ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
987    if ev is None:
988        raise Exception("TX status for Deauthentication frame not reported")
989    if "ok=0 buf=c0" not in ev:
990        raise Exception("Unexpected TX status contents (disconnect): " + ev)
991
992def test_ap_open_layer_2_update(dev, apdev, params):
993    """AP with open mode (no security) and Layer 2 Update frame"""
994    prefix = "ap_open_layer_2_update"
995    ifname = apdev[0]["ifname"]
996    cap = os.path.join(params['logdir'], prefix + "." + ifname + ".pcap")
997
998    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
999    with WlantestCapture(ifname, cap):
1000        dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
1001        hapd.wait_sta()
1002        hwsim_utils.test_connectivity(dev[0], hapd)
1003        time.sleep(1)
1004        hwsim_utils.test_connectivity(dev[0], hapd)
1005
1006    # Check for Layer 2 Update frame and unexpected frames from the station
1007    # that did not fully complete authentication.
1008    res = run_tshark(cap, "basicxid.llc.xid.format == 0x81",
1009                     ["eth.src"], wait=False)
1010    real_sta_seen = False
1011    unexpected_sta_seen = False
1012    real_addr = dev[0].own_addr()
1013    for l in res.splitlines():
1014        if l == real_addr:
1015            real_sta_seen = True
1016        else:
1017            unexpected_sta_seen = True
1018    if unexpected_sta_seen:
1019        raise Exception("Layer 2 Update frame from unexpected STA seen")
1020    if not real_sta_seen:
1021        raise Exception("Layer 2 Update frame from real STA not seen")
1022