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], {"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                if line == "True":
559                    buffered_mcast = 1
560                elif line == "False":
561                    buffered_mcast = 0
562                else:
563                    buffered_mcast = int(line)
564                if buffered_mcast == 1:
565                    break
566            if buffered_mcast == 1:
567                break
568    finally:
569        dev[0].cmd_execute(['iw', 'dev', dev[0].ifname,
570                            'set', 'power_save', 'off'])
571
572    if buffered_mcast != 1:
573        raise Exception("AP did not buffer multicast frames")
574
575@remote_compatible
576def test_ap_open_select_network(dev, apdev):
577    """Open mode connection and SELECT_NETWORK to change network"""
578    hapd1 = hostapd.add_ap(apdev[0], {"ssid": "open"})
579    bssid1 = apdev[0]['bssid']
580    hapd2 = hostapd.add_ap(apdev[1], {"ssid": "open2"})
581    bssid2 = apdev[1]['bssid']
582
583    id1 = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
584                         only_add_network=True)
585    id2 = dev[0].connect("open2", key_mgmt="NONE", scan_freq="2412")
586    hwsim_utils.test_connectivity(dev[0], hapd2)
587
588    dev[0].select_network(id1)
589    dev[0].wait_connected()
590    res = dev[0].request("BSSID_IGNORE")
591    if bssid1 in res or bssid2 in res:
592        raise Exception("Unexpected BSSID ignore list entry")
593    hwsim_utils.test_connectivity(dev[0], hapd1)
594
595    dev[0].select_network(id2)
596    dev[0].wait_connected()
597    hwsim_utils.test_connectivity(dev[0], hapd2)
598    res = dev[0].request("BSSID_IGNORE")
599    if bssid1 in res or bssid2 in res:
600        raise Exception("Unexpected BSSID ignore list entry(2)")
601
602@remote_compatible
603def test_ap_open_disable_enable(dev, apdev):
604    """AP with open mode getting disabled and re-enabled"""
605    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
606    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
607                   bg_scan_period="0")
608
609    for i in range(2):
610        hapd.request("DISABLE")
611        dev[0].wait_disconnected()
612        hapd.request("ENABLE")
613        dev[0].wait_connected()
614        hwsim_utils.test_connectivity(dev[0], hapd)
615
616def sta_enable_disable(dev, bssid):
617    dev.scan_for_bss(bssid, freq=2412)
618    work_id = dev.request("RADIO_WORK add block-work")
619    ev = dev.wait_event(["EXT-RADIO-WORK-START"])
620    if ev is None:
621        raise Exception("Timeout while waiting radio work to start")
622    id = dev.connect("open", key_mgmt="NONE", scan_freq="2412",
623                     only_add_network=True)
624    dev.request("ENABLE_NETWORK %d" % id)
625    if "connect@" not in dev.request("RADIO_WORK show"):
626        raise Exception("connect radio work missing")
627    dev.request("DISABLE_NETWORK %d" % id)
628    dev.request("RADIO_WORK done " + work_id)
629
630    ok = False
631    for i in range(30):
632        if "connect@" not in dev.request("RADIO_WORK show"):
633            ok = True
634            break
635        time.sleep(0.1)
636    if not ok:
637        raise Exception("connect radio work not completed")
638    ev = dev.wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
639    if ev is not None:
640        raise Exception("Unexpected connection")
641    dev.request("DISCONNECT")
642
643def test_ap_open_sta_enable_disable(dev, apdev):
644    """AP with open mode and wpa_supplicant ENABLE/DISABLE_NETWORK"""
645    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
646    bssid = apdev[0]['bssid']
647
648    sta_enable_disable(dev[0], bssid)
649
650    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
651    wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
652    sta_enable_disable(wpas, bssid)
653
654@remote_compatible
655def test_ap_open_select_twice(dev, apdev):
656    """AP with open mode and select network twice"""
657    id = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
658                        only_add_network=True)
659    dev[0].select_network(id)
660    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
661    if ev is None:
662        raise Exception("No result reported")
663    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
664    # Verify that the second SELECT_NETWORK starts a new scan immediately by
665    # waiting less than the default scan period.
666    dev[0].select_network(id)
667    dev[0].wait_connected(timeout=3)
668
669@remote_compatible
670def test_ap_open_reassoc_not_found(dev, apdev):
671    """AP with open mode and REASSOCIATE not finding a match"""
672    id = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
673                        only_add_network=True)
674    dev[0].select_network(id)
675    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
676    if ev is None:
677        raise Exception("No result reported")
678    dev[0].request("DISCONNECT")
679
680    time.sleep(0.1)
681    dev[0].dump_monitor()
682
683    dev[0].request("REASSOCIATE")
684    ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND"], timeout=10)
685    if ev is None:
686        raise Exception("No result reported")
687    dev[0].request("DISCONNECT")
688
689@remote_compatible
690def test_ap_open_sta_statistics(dev, apdev):
691    """AP with open mode and STA statistics"""
692    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
693    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
694    addr = dev[0].own_addr()
695
696    stats1 = hapd.get_sta(addr)
697    logger.info("stats1: " + str(stats1))
698    time.sleep(0.4)
699    stats2 = hapd.get_sta(addr)
700    logger.info("stats2: " + str(stats2))
701    hwsim_utils.test_connectivity(dev[0], hapd)
702    stats3 = hapd.get_sta(addr)
703    logger.info("stats3: " + str(stats3))
704
705    # Cannot require specific inactive_msec changes without getting rid of all
706    # unrelated traffic, so for now, just print out the results in the log for
707    # manual checks.
708
709@remote_compatible
710def test_ap_open_poll_sta(dev, apdev):
711    """AP with open mode and STA poll"""
712    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
713    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
714    addr = dev[0].own_addr()
715
716    if "OK" not in hapd.request("POLL_STA " + addr):
717        raise Exception("POLL_STA failed")
718    ev = hapd.wait_event(["AP-STA-POLL-OK"], timeout=5)
719    if ev is None:
720        raise Exception("Poll response not seen")
721    if addr not in ev:
722        raise Exception("Unexpected poll response: " + ev)
723
724def test_ap_open_poll_sta_no_ack(dev, apdev):
725    """AP with open mode and STA poll without ACK"""
726    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
727    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
728    addr = dev[0].own_addr()
729
730    hapd.set("ext_mgmt_frame_handling", "1")
731    dev[0].request("DISCONNECT")
732    dev[0].wait_disconnected()
733    # eat up the deauth frame, so it cannot be processed
734    # after we disable ext_mgmt_frame_handling again
735    hapd.wait_event(["MGMT-RX"], timeout=1)
736    hapd.set("ext_mgmt_frame_handling", "0")
737    if "OK" not in hapd.request("POLL_STA " + addr):
738        raise Exception("POLL_STA failed")
739    ev = hapd.wait_event(["AP-STA-POLL-OK"], timeout=1)
740    if ev is not None:
741        raise Exception("Unexpected poll response reported")
742
743def test_ap_open_pmf_default(dev, apdev):
744    """AP with open mode (no security) configuration and pmf=2"""
745    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
746    dev[1].connect("open", key_mgmt="NONE", scan_freq="2412",
747                   ieee80211w="2", wait_connect=False)
748    dev[2].connect("open", key_mgmt="NONE", scan_freq="2412",
749                   ieee80211w="1")
750    try:
751        dev[0].request("SET pmf 2")
752        dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
753
754        dev[0].request("DISCONNECT")
755        dev[0].wait_disconnected()
756    finally:
757        dev[0].request("SET pmf 0")
758    dev[2].request("DISCONNECT")
759    dev[2].wait_disconnected()
760
761    ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
762    if ev is not None:
763        raise Exception("Unexpected dev[1] connection")
764    dev[1].request("DISCONNECT")
765
766def test_ap_open_drv_fail(dev, apdev):
767    """AP with open mode and driver operations failing"""
768    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
769
770    with fail_test(dev[0], 1, "wpa_driver_nl80211_authenticate"):
771        dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
772                       wait_connect=False)
773        wait_fail_trigger(dev[0], "GET_FAIL")
774        dev[0].request("REMOVE_NETWORK all")
775
776    with fail_test(dev[0], 1, "wpa_driver_nl80211_associate"):
777        dev[0].connect("open", key_mgmt="NONE", scan_freq="2412",
778                       wait_connect=False)
779        wait_fail_trigger(dev[0], "GET_FAIL")
780        dev[0].request("REMOVE_NETWORK all")
781
782def run_multicast_to_unicast(dev, apdev, convert):
783    params = {"ssid": "open"}
784    params["multicast_to_unicast"] = "1" if convert else "0"
785    hapd = hostapd.add_ap(apdev[0], params)
786    dev[0].scan_for_bss(hapd.own_addr(), freq=2412)
787    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
788    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=5)
789    if ev is None:
790        raise Exception("No connection event received from hostapd")
791    hwsim_utils.test_connectivity(dev[0], hapd, multicast_to_unicast=convert)
792    dev[0].request("DISCONNECT")
793    ev = hapd.wait_event(["AP-STA-DISCONNECTED"], timeout=5)
794    if ev is None:
795        raise Exception("No disconnection event received from hostapd")
796
797def test_ap_open_multicast_to_unicast(dev, apdev):
798    """Multicast-to-unicast conversion enabled"""
799    run_multicast_to_unicast(dev, apdev, True)
800
801def test_ap_open_multicast_to_unicast_disabled(dev, apdev):
802    """Multicast-to-unicast conversion disabled"""
803    run_multicast_to_unicast(dev, apdev, False)
804
805def test_ap_open_drop_duplicate(dev, apdev, params):
806    """AP dropping duplicate management frames"""
807    hapd = hostapd.add_ap(apdev[0], {"ssid": "open",
808                                     "interworking": "1"})
809    hapd.set("ext_mgmt_frame_handling", "1")
810    bssid = hapd.own_addr().replace(':', '')
811    addr = "020304050607"
812    auth = "b0003a01" + bssid + addr + bssid + '1000000001000000'
813    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % auth):
814        raise Exception("MGMT_RX_PROCESS failed")
815    auth = "b0083a01" + bssid + addr + bssid + '1000000001000000'
816    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % auth):
817        raise Exception("MGMT_RX_PROCESS failed")
818
819    ies = "00046f70656e010802040b160c12182432043048606c2d1a3c101bffff0000000000000000000001000000000000000000007f0a04000a020140004000013b155151525354737475767778797a7b7c7d7e7f808182dd070050f202000100"
820    assoc_req = "00003a01" + bssid + addr + bssid + "2000" + "21040500" + ies
821    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % assoc_req):
822        raise Exception("MGMT_RX_PROCESS failed")
823    assoc_req = "00083a01" + bssid + addr + bssid + "2000" + "21040500" + ies
824    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % assoc_req):
825        raise Exception("MGMT_RX_PROCESS failed")
826    reassoc_req = "20083a01" + bssid + addr + bssid + "2000" + "21040500" + ies
827    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % reassoc_req):
828        raise Exception("MGMT_RX_PROCESS failed")
829    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % reassoc_req):
830        raise Exception("MGMT_RX_PROCESS failed")
831
832    action = "d0003a01" + bssid + addr + bssid + "1000" + "040a006c0200000600000102000101"
833    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % action):
834        raise Exception("MGMT_RX_PROCESS failed")
835
836    action = "d0083a01" + bssid + addr + bssid + "1000" + "040a006c0200000600000102000101"
837    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % action):
838        raise Exception("MGMT_RX_PROCESS failed")
839
840    out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
841                     "wlan.fc.type == 0", ["wlan.fc.subtype"])
842    num_auth = 0
843    num_assoc = 0
844    num_reassoc = 0
845    num_action = 0
846    for subtype in out.splitlines():
847        val = int(subtype)
848        if val == 11:
849            num_auth += 1
850        elif val == 1:
851            num_assoc += 1
852        elif val == 3:
853            num_reassoc += 1
854        elif val == 13:
855            num_action += 1
856    if num_auth != 1:
857        raise Exception("Unexpected number of Authentication frames: %d" % num_auth)
858    if num_assoc != 1:
859        raise Exception("Unexpected number of association frames: %d" % num_assoc)
860    if num_reassoc != 1:
861        raise Exception("Unexpected number of reassociation frames: %d" % num_reassoc)
862    if num_action != 1:
863        raise Exception("Unexpected number of Action frames: %d" % num_action)
864
865def test_ap_open_select_network_freq(dev, apdev):
866    """AP with open mode and use for SELECT_NETWORK freq parameter"""
867    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
868    id = dev[0].connect("open", key_mgmt="NONE", only_add_network=True)
869    dev[0].select_network(id, freq=2412)
870    start = os.times()[4]
871    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5)
872    if ev is None:
873        raise Exception("Scan not started")
874    ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=15)
875    if ev is None:
876        raise Exception("Scan not completed")
877    end = os.times()[4]
878    logger.info("Scan duration: {} seconds".format(end - start))
879    if end - start > 3:
880        raise Exception("Scan took unexpectedly long time")
881    dev[0].wait_connected()
882
883def test_ap_open_noncountry(dev, apdev):
884    """AP with open mode and noncountry entity as Country String"""
885    _test_ap_open_country(dev, apdev, "XX", "0x58")
886
887def test_ap_open_country_table_e4(dev, apdev):
888    """AP with open mode and Table E-4 Country String"""
889    _test_ap_open_country(dev, apdev, "DE", "0x04")
890
891def test_ap_open_country_indoor(dev, apdev):
892    """AP with open mode and indoor country code"""
893    _test_ap_open_country(dev, apdev, "DE", "0x49")
894
895def test_ap_open_country_outdoor(dev, apdev):
896    """AP with open mode and outdoor country code"""
897    _test_ap_open_country(dev, apdev, "DE", "0x4f")
898
899def _test_ap_open_country(dev, apdev, country_code, country3):
900    try:
901        hapd = None
902        hapd = run_ap_open_country(dev, apdev, country_code, country3)
903    finally:
904        clear_regdom(hapd, dev)
905
906def run_ap_open_country(dev, apdev, country_code, country3):
907    hapd = hostapd.add_ap(apdev[0], {"ssid": "open",
908                                     "country_code": country_code,
909                                     "country3": country3,
910                                     "ieee80211d": "1"})
911    dev[0].scan_for_bss(hapd.own_addr(), freq=2412)
912    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
913    dev[0].wait_regdom(country_ie=True)
914    return hapd
915
916def test_ap_open_disable_select(dev, apdev):
917    """DISABLE_NETWORK for connected AP followed by SELECT_NETWORK"""
918    hapd1 = hostapd.add_ap(apdev[0], {"ssid": "open"})
919    hapd2 = hostapd.add_ap(apdev[1], {"ssid": "open"})
920    id = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
921
922    dev[0].request("DISABLE_NETWORK %d" % id)
923    dev[0].wait_disconnected()
924    res = dev[0].request("BSSID_IGNORE")
925    if hapd1.own_addr() in res or hapd2.own_addr() in res:
926        raise Exception("Unexpected BSSID ignore list entry added")
927    dev[0].request("SELECT_NETWORK %d" % id)
928    dev[0].wait_connected()
929
930def test_ap_open_reassoc_same(dev, apdev):
931    """AP with open mode and STA reassociating back to same AP without auth exchange"""
932    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
933    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
934    try:
935        dev[0].request("SET reassoc_same_bss_optim 1")
936        dev[0].request("REATTACH")
937        dev[0].wait_connected()
938        hwsim_utils.test_connectivity(dev[0], hapd)
939    finally:
940        dev[0].request("SET reassoc_same_bss_optim 0")
941
942def test_ap_open_no_reflection(dev, apdev):
943    """AP with open mode, STA sending packets to itself"""
944    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
945    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
946
947    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=5)
948    if ev is None:
949        raise Exception("No connection event received from hostapd")
950    # test normal connectivity is OK
951    hwsim_utils.test_connectivity(dev[0], hapd)
952
953    # test that we can't talk to ourselves
954    addr = dev[0].own_addr()
955    res = dev[0].request('DATA_TEST_CONFIG 1')
956    try:
957        assert 'OK' in res
958
959        cmd = "DATA_TEST_TX {} {} {}".format(addr, addr, 0)
960        dev[0].request(cmd)
961
962        ev = dev[0].wait_event(["DATA-TEST-RX"], timeout=1)
963
964        if ev is not None and "DATA-TEST-RX {} {}".format(addr, addr) in ev:
965            raise Exception("STA can unexpectedly talk to itself")
966    finally:
967        dev[0].request('DATA_TEST_CONFIG 0')
968
969def test_ap_no_auth_ack(dev, apdev):
970    """AP not receiving Authentication frame ACK"""
971    hapd = hostapd.add_ap(apdev[0], {"ssid": "open",
972                                     "ap_max_inactivity": "1"})
973    hapd.set("ext_mgmt_frame_handling", "1")
974
975    # Avoid race condition with TX status reporting for the broadcast
976    # Deauthentication frame.
977    hapd.wait_event(["MGMT-TX-STATUS"], timeout=0.1)
978
979    bssid = hapd.own_addr()
980    addr = "02:01:02:03:04:05"
981    frame = "b0003a01" + bssid.replace(':', '') + addr.replace(':', '') + bssid.replace(':', '') + "1000" + "000001000000"
982    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + frame):
983        raise Exception("MGMT_RX_PROCESS failed")
984    ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
985    if ev is None:
986        raise Exception("TX status for Authentication frame not reported")
987    if "ok=0 buf=b0" not in ev:
988        raise Exception("Unexpected TX status contents: " + ev)
989
990    # wait for STA to be removed due to timeout
991    ev = hapd.wait_event(["MGMT-TX-STATUS"], timeout=5)
992    if ev is None:
993        raise Exception("TX status for Deauthentication frame not reported")
994    if "ok=0 buf=c0" not in ev:
995        raise Exception("Unexpected TX status contents (disconnect): " + ev)
996
997def test_ap_open_layer_2_update(dev, apdev, params):
998    """AP with open mode (no security) and Layer 2 Update frame"""
999    prefix = "ap_open_layer_2_update"
1000    ifname = apdev[0]["ifname"]
1001    cap = os.path.join(params['logdir'], prefix + "." + ifname + ".pcap")
1002
1003    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
1004    with WlantestCapture(ifname, cap):
1005        dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
1006        hapd.wait_sta()
1007        hwsim_utils.test_connectivity(dev[0], hapd)
1008        time.sleep(1)
1009        hwsim_utils.test_connectivity(dev[0], hapd)
1010
1011    # Check for Layer 2 Update frame and unexpected frames from the station
1012    # that did not fully complete authentication.
1013    res = run_tshark(cap, "basicxid.llc.xid.format == 0x81",
1014                     ["eth.src"], wait=False)
1015    real_sta_seen = False
1016    unexpected_sta_seen = False
1017    real_addr = dev[0].own_addr()
1018    for l in res.splitlines():
1019        if l == real_addr:
1020            real_sta_seen = True
1021        else:
1022            unexpected_sta_seen = True
1023    if unexpected_sta_seen:
1024        raise Exception("Layer 2 Update frame from unexpected STA seen")
1025    if not real_sta_seen:
1026        raise Exception("Layer 2 Update frame from real STA not seen")
1027