def test_p2p_delay_go_csa(dev, apdev, params): """P2P GO CSA delayed when inviting a P2P Device to an active P2P Group""" with HWSimRadio(n_channels=2) as (radio, iface): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add(iface) wpas.global_request("SET p2p_no_group_iface 0") if wpas.get_mcc() < 2: raise Exception("New radio does not support MCC") addr0 = wpas.p2p_dev_addr() addr1 = dev[1].p2p_dev_addr() try: dev[1].p2p_listen() if not wpas.discover_peer(addr1, social=True): raise Exception("Peer " + addr1 + " not found") wpas.p2p_stop_find() hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": 'bss-2.4ghz', "channel": '1' }) wpas.connect("bss-2.4ghz", key_mgmt="NONE", scan_freq="2412") wpas.global_request("SET p2p_go_freq_change_policy 0") wpas.dump_monitor() logger.info("Start GO on channel 6") res = autogo(wpas, freq=2437) if res['freq'] != "2437": raise Exception("GO set on a freq=%s instead of 2437" % res['freq']) # Start find on dev[1] to run scans with dev[2] in parallel dev[1].p2p_find(social=True) # Use another client device to stop the initial client connection # timeout on the GO if not dev[2].discover_peer(addr0, social=True): raise Exception("Peer2 did not find the GO") dev[2].p2p_stop_find() pin = dev[2].wps_read_pin() wpas.p2p_go_authorize_client(pin) dev[2].global_request("P2P_CONNECT " + addr0 + " " + pin + " join freq=2437") ev = dev[2].wait_global_event(["P2P-GROUP-STARTED"], timeout=10) if ev is None: raise Exception("Peer2 did not get connected") if not dev[1].discover_peer(addr0, social=True): raise Exception("Peer did not find the GO") pin = dev[1].wps_read_pin() dev[1].global_request("P2P_CONNECT " + addr0 + " " + pin + " join auth") dev[1].p2p_listen() # Force P2P GO channel switch on successful invitation signaling wpas.group_request("SET p2p_go_csa_on_inv 1") logger.info("Starting invitation") wpas.p2p_go_authorize_client(pin) wpas.global_request("P2P_INVITE group=" + wpas.group_ifname + " peer=" + addr1) ev = dev[1].wait_global_event( ["P2P-INVITATION-RECEIVED", "P2P-GROUP-STARTED"], timeout=10) if ev is None: raise Exception("Timeout on invitation on peer") if "P2P-INVITATION-RECEIVED" in ev: raise Exception( "Unexpected request to accept pre-authorized invitation") # A P2P GO move is not expected at this stage, as during the # invitation signaling, the P2P GO includes only its current # operating channel in the channel list, and as the invitation # response can only include channels that were also in the # invitation request channel list, the group common channels # includes only the current P2P GO operating channel. ev = wpas.wait_group_event( ["P2P-REMOVE-AND-REFORM-GROUP", "AP-CSA-FINISHED"], timeout=1) if ev is not None: raise Exception("Unexpected + " + ev + " event") finally: wpas.global_request("SET p2p_go_freq_change_policy 2")
def test_pmksa_cache_multiple_sta(dev, apdev): """PMKSA cache with multiple stations""" params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") hostapd.add_ap(apdev[0], params) bssid = apdev[0]['bssid'] for d in dev: d.flush_scan_cache() dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", eap="GPSK", identity="gpsk-user-session-timeout", password="******", scan_freq="2412") dev[1].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", eap="GPSK", identity="gpsk user", password="******", scan_freq="2412") dev[2].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", eap="GPSK", identity="gpsk-user-session-timeout", password="******", scan_freq="2412") wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5") wpas.flush_scan_cache() wpas.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", eap="GPSK", identity="gpsk user", password="******", scan_freq="2412") hostapd.add_ap(apdev[1], params) bssid2 = apdev[1]['bssid'] logger.info("Roam to AP2") for sta in [dev[1], dev[0], dev[2], wpas]: sta.dump_monitor() sta.scan_for_bss(bssid2, freq="2412") if "OK" not in sta.request("ROAM " + bssid2): raise Exception("ROAM command failed (" + sta.ifname + ")") ev = sta.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10) if ev is None: raise Exception("EAP success timed out") sta.wait_connected(timeout=10, error="Roaming timed out") sta.dump_monitor() logger.info("Roam back to AP1") for sta in [dev[1], wpas, dev[0], dev[2]]: sta.dump_monitor() sta.scan(freq="2412") sta.dump_monitor() sta.request("ROAM " + bssid) sta.wait_connected(timeout=10, error="Roaming timed out") sta.dump_monitor() time.sleep(4) logger.info("Roam back to AP2") for sta in [dev[1], wpas, dev[0], dev[2]]: sta.dump_monitor() sta.scan(freq="2412") sta.dump_monitor() sta.request("ROAM " + bssid2) sta.wait_connected(timeout=10, error="Roaming timed out") sta.dump_monitor()
def test_wpas_config_file_key_mgmt(dev, apdev, params): """wpa_supplicant config file writing and key_mgmt values""" config = os.path.join(params['logdir'], 'wpas_config_file_key_mgmt.conf') if os.path.exists(config): os.remove(config) wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') with open(config, "w") as f: f.write("update_config=1\n") wpas.interface_add("wlan5", config=config) from test_dpp import params1_csign, params1_sta_connector, params1_sta_netaccesskey, check_dpp_capab check_dpp_capab(wpas) id = wpas.add_network() wpas.set_network_quoted(id, "ssid", "foo") wpas.set_network(id, "key_mgmt", "DPP") wpas.set_network(id, "ieee80211w", "2") wpas.set_network_quoted(id, "dpp_csign", params1_csign) wpas.set_network_quoted(id, "dpp_connector", params1_sta_connector) wpas.set_network_quoted(id, "dpp_netaccesskey", params1_sta_netaccesskey) if "OK" not in wpas.request("SAVE_CONFIG"): raise Exception("Failed to save configuration file") with open(config, "r") as f: data = f.read() logger.info("Configuration file contents: " + data) if "key_mgmt=DPP" not in data: raise Exception("Missing key_mgmt") if 'dpp_connector="' + params1_sta_connector + '"' not in data: raise Exception("Missing dpp_connector") if 'dpp_netaccesskey="' + params1_sta_netaccesskey + '"' not in data: raise Exception("Missing dpp_netaccesskey") if 'dpp_csign="' + params1_csign + '"' not in data: raise Exception("Missing dpp_csign") wpas.set_network(id, "dpp_csign", "NULL") wpas.set_network(id, "dpp_connector", "NULL") wpas.set_network(id, "dpp_netaccesskey", "NULL") wpas.set_network_quoted(id, "psk", "12345678") wpas.set_network(id, "ieee80211w", "0") tests = [ "WPA-PSK", "WPA-EAP", "IEEE8021X", "NONE", "WPA-NONE", "FT-PSK", "FT-EAP", "FT-EAP-SHA384", "WPA-PSK-SHA256", "WPA-EAP-SHA256", "SAE", "FT-SAE", "OSEN", "WPA-EAP-SUITE-B", "WPA-EAP-SUITE-B-192", "FILS-SHA256", "FILS-SHA384", "FT-FILS-SHA256", "FT-FILS-SHA384", "OWE", "DPP" ] supported_key_mgmts = dev[0].get_capability("key_mgmt") for key_mgmt in tests: if key_mgmt == "WPA-EAP-SUITE-B-192" and key_mgmt not in supported_key_mgmts: logger.info("Skip unsupported " + key_mgmt) continue wpas.set_network(id, "key_mgmt", key_mgmt) if "OK" not in wpas.request("SAVE_CONFIG"): raise Exception("Failed to save configuration file") with open(config, "r") as f: data = f.read() logger.info("Configuration file contents: " + data) if "key_mgmt=" + key_mgmt not in data: raise Exception("Missing key_mgmt " + key_mgmt) wpas.interface_remove("wlan5") wpas.interface_add("wlan5", config=config)
def test_wpas_config_file(dev): """wpa_supplicant config file parsing/writing""" config = "/tmp/test_wpas_config_file.conf" if os.path.exists(config): os.remove(config) wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') try: wpas.interface_add("wlan5", config=config) initialized = True except: initialized = False if initialized: raise Exception("Missing config file did not result in an error") try: with open(config, "w") as f: f.write("update_config=1 \t\r\n") f.write("# foo\n") f.write("\n") f.write(" \t\reapol_version=2") for i in range(0, 100): f.write(" ") f.write("foo\n") f.write("device_name=name#foo\n") wpas.interface_add("wlan5", config=config) wpas.request("SET wps_priority 5") id = wpas.add_network() wpas.set_network_quoted(id, "ssid", "foo") wpas.set_network_quoted(id, "psk", "12345678") wpas.set_network(id, "bssid", "00:11:22:33:44:55") wpas.set_network(id, "proto", "RSN") wpas.set_network(id, "key_mgmt", "WPA-PSK-SHA256") wpas.set_network(id, "pairwise", "CCMP") wpas.set_network(id, "group", "CCMP") wpas.set_network(id, "auth_alg", "OPEN") id = wpas.add_cred() wpas.set_cred(id, "priority", "3") wpas.set_cred(id, "sp_priority", "6") wpas.set_cred(id, "update_identifier", "4") wpas.set_cred(id, "ocsp", "1") wpas.set_cred(id, "eap", "TTLS") wpas.set_cred(id, "req_conn_capab", "6:1234") wpas.set_cred_quoted(id, "realm", "example.com") wpas.set_cred_quoted(id, "provisioning_sp", "example.com") wpas.set_cred_quoted(id, "domain", "example.com") wpas.set_cred_quoted(id, "domain_suffix_match", "example.com") wpas.set_cred(id, "roaming_consortium", "112233") wpas.set_cred(id, "required_roaming_consortium", "112233") wpas.set_cred_quoted(id, "roaming_partner", "roaming.example.net,1,127,*") wpas.set_cred_quoted(id, "ca_cert", "/tmp/ca.pem") wpas.set_cred_quoted(id, "username", "user") wpas.set_cred_quoted(id, "password", "secret") ev = wpas.wait_event(["CRED-MODIFIED 0 password"]) wpas.request("SET blob foo 12345678") if "OK" not in wpas.request("SAVE_CONFIG"): raise Exception("Failed to save configuration file") if "OK" not in wpas.global_request("SAVE_CONFIG"): raise Exception("Failed to save configuration file") wpas.interface_remove("wlan5") data1 = check_config(config) wpas.interface_add("wlan5", config=config) if len(wpas.list_networks()) != 1: raise Exception("Unexpected number of networks") if len(wpas.request("LIST_CREDS").splitlines()) != 2: raise Exception("Unexpected number of credentials") if "OK" not in wpas.request("SAVE_CONFIG"): raise Exception("Failed to save configuration file") data2 = check_config(config) if data1 != data2: logger.debug(data1) logger.debug(data2) raise Exception("Unexpected configuration change") wpas.request("SET update_config 0") if "OK" in wpas.request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG succeeded unexpectedly") if "OK" in wpas.global_request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG (global) succeeded unexpectedly") # replace the config file with a directory to break writing/renaming os.remove(config) os.mkdir(config) wpas.request("SET update_config 1") if "OK" in wpas.request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG succeeded unexpectedly") if "OK" in wpas.global_request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG (global) succeeded unexpectedly") finally: try: os.remove(config) except: pass try: os.remove(config + ".tmp") except: pass try: os.rmdir(config) except: pass
def test_example(devices, setup_params, refs, duts, monitors): """TC example - simple connect and ping test""" try: sta = None ap = None hapd = None wpas = None mon = None # get hosts based on name sta = rutils.get_host(devices, duts[0]) ap = rutils.get_host(devices, refs[0]) # setup log dir local_log_dir = setup_params['local_log_dir'] # setup hw before test rutils.setup_hw([sta, ap], setup_params) # run traces if requested rutils.trace_start([sta], setup_params) # run perf if requested rutils.perf_start([sta], setup_params) # run hostapd/wpa_supplicant rutils.run_wpasupplicant(sta, setup_params) rutils.run_hostapd(ap, setup_params) # get ap_params ap_params = rutils.get_ap_params(channel="1", bw="HT20", country="US", security="open") # Add monitors if requested monitor_hosts = monitor.create(devices, setup_params, refs, duts, monitors) if len(monitor_hosts) > 0: mon = monitor_hosts[0] monitor.add(sta, monitors) monitor.add(ap, monitors) # connect to hostapd/wpa_supplicant UDP CTRL iface hapd = hostapd.add_ap(ap.dev, ap_params) freq = hapd.get_status_field("freq") wpas = WpaSupplicant(hostname=sta.host, global_iface="udp", global_port=sta.port) wpas.interface_add(sta.ifname) # setup standalone monitor based on hapd; could be multi interface # monitor monitor_param = monitor.get_monitor_params(hapd) monitor.setup(mon, [monitor_param]) # run monitors monitor.run(sta, setup_params) monitor.run(ap, setup_params) monitor.run(mon, setup_params) # connect wpa_supplicant to hostapd wpas.connect(ap_params['ssid'], key_mgmt="NONE", scan_freq=freq) # run ping test ap_sta, sta_ap = rutils.check_connectivity(ap, sta, "ipv6") # remove/destroy monitors monitor.remove(sta) monitor.remove(ap) monitor.destroy(devices, monitor_hosts) # hostapd/wpa_supplicant cleanup wpas.interface_remove(sta.ifname) wpas.terminate() hapd.close_ctrl() hostapd.remove_bss(ap.dev) hostapd.terminate(ap.dev) # stop perf rutils.perf_stop([sta], setup_params) # stop traces rutils.trace_stop([sta], setup_params) # get wpa_supplicant/hostapd/tshark logs sta.get_logs(local_log_dir) ap.get_logs(local_log_dir) if mon: mon.get_logs(local_log_dir) return "packet_loss: " + ap_sta + ", " + sta_ap except: rutils.perf_stop([sta], setup_params) rutils.trace_stop([sta], setup_params) if wpas: try: wpas.interface_remove(sta.ifname) wpas.terminate() except: pass if hapd: try: hapd.close_ctrl() hostapd.remove_bss(ap.dev) hostapd.terminate(ap.dev) except: pass if mon: monitor.destroy(devices, monitor_hosts) mon.get_logs(local_log_dir) if sta: monitor.remove(sta) dmesg = setup_params['log_dir'] + setup_params[ 'tc_name'] + "_" + sta.name + "_" + sta.ifname + ".dmesg" sta.execute(["dmesg", "-c", ">", dmesg]) sta.add_log(dmesg) sta.get_logs(local_log_dir) sta.execute(["ifconfig", sta.ifname, "down"]) if ap: monitor.remove(ap) dmesg = setup_params['log_dir'] + setup_params[ 'tc_name'] + "_" + ap.name + "_" + ap.ifname + ".dmesg" ap.execute(["dmesg", "-c", ">", dmesg]) ap.add_log(dmesg) ap.get_logs(local_log_dir) ap.execute(["ifconfig", ap.ifname, " down"]) raise
def test_wpas_mesh_dynamic_interface(dev): """wpa_supplicant mesh with dynamic interface""" check_mesh_support(dev[0]) mesh0 = None mesh1 = None try: mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0") if "FAIL" in mesh0: raise Exception("MESH_INTERFACE_ADD failed") mesh1 = dev[1].request("MESH_INTERFACE_ADD") if "FAIL" in mesh1: raise Exception("MESH_INTERFACE_ADD failed") wpas0 = WpaSupplicant(ifname=mesh0) wpas1 = WpaSupplicant(ifname=mesh1) logger.info(mesh0 + " address " + wpas0.get_status_field("address")) logger.info(mesh1 + " address " + wpas1.get_status_field("address")) add_open_mesh_network(wpas0) add_open_mesh_network(wpas1) check_mesh_group_added(wpas0) check_mesh_group_added(wpas1) check_mesh_peer_connected(wpas0) check_mesh_peer_connected(wpas1) hwsim_utils.test_connectivity(wpas0, wpas1) # Must not allow MESH_GROUP_REMOVE on dynamic interface if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh0): raise Exception("Invalid MESH_GROUP_REMOVE accepted") if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh1): raise Exception("Invalid MESH_GROUP_REMOVE accepted") # Must not allow MESH_GROUP_REMOVE on another radio interface if "FAIL" not in wpas0.request("MESH_GROUP_REMOVE " + mesh1): raise Exception("Invalid MESH_GROUP_REMOVE accepted") if "FAIL" not in wpas1.request("MESH_GROUP_REMOVE " + mesh0): raise Exception("Invalid MESH_GROUP_REMOVE accepted") wpas0.remove_ifname() wpas1.remove_ifname() if "OK" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0): raise Exception("MESH_GROUP_REMOVE failed") if "OK" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1): raise Exception("MESH_GROUP_REMOVE failed") if "FAIL" not in dev[0].request("MESH_GROUP_REMOVE " + mesh0): raise Exception("Invalid MESH_GROUP_REMOVE accepted") if "FAIL" not in dev[1].request("MESH_GROUP_REMOVE " + mesh1): raise Exception("Invalid MESH_GROUP_REMOVE accepted") logger.info("Make sure another dynamic group can be added") mesh0 = dev[0].request("MESH_INTERFACE_ADD ifname=mesh0") if "FAIL" in mesh0: raise Exception("MESH_INTERFACE_ADD failed") mesh1 = dev[1].request("MESH_INTERFACE_ADD") if "FAIL" in mesh1: raise Exception("MESH_INTERFACE_ADD failed") wpas0 = WpaSupplicant(ifname=mesh0) wpas1 = WpaSupplicant(ifname=mesh1) logger.info(mesh0 + " address " + wpas0.get_status_field("address")) logger.info(mesh1 + " address " + wpas1.get_status_field("address")) add_open_mesh_network(wpas0) add_open_mesh_network(wpas1) check_mesh_group_added(wpas0) check_mesh_group_added(wpas1) check_mesh_peer_connected(wpas0) check_mesh_peer_connected(wpas1) hwsim_utils.test_connectivity(wpas0, wpas1) finally: if mesh0: dev[0].request("MESH_GROUP_REMOVE " + mesh0) if mesh1: dev[1].request("MESH_GROUP_REMOVE " + mesh1)
def test_scan_and_bss_entry_removed(dev, apdev): """Last scan result and connect work processing on BSS entry update""" hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open", "eap_server": "1", "wps_state": "2" }) bssid = apdev[0]['bssid'] wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") # Add a BSS entry dev[0].scan_for_bss(bssid, freq="2412") wpas.scan_for_bss(bssid, freq="2412") # Start a connect radio work with a blocking entry preventing this from # proceeding; this stores a pointer to the selected BSS entry. id = dev[0].request("RADIO_WORK add block-work") w_id = wpas.request("RADIO_WORK add block-work") dev[0].wait_event(["EXT-RADIO-WORK-START"], timeout=1) wpas.wait_event(["EXT-RADIO-WORK-START"], timeout=1) nid = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412", wait_connect=False) w_nid = wpas.connect("open", key_mgmt="NONE", scan_freq="2412", wait_connect=False) time.sleep(0.1) # Remove the BSS entry dev[0].request("BSS_FLUSH 0") wpas.request("BSS_FLUSH 0") # Allow the connect radio work to continue. The bss entry stored in the # pending connect work is now stale. This will result in the connection # attempt failing since the BSS entry does not exist. dev[0].request("RADIO_WORK done " + id) wpas.request("RADIO_WORK done " + w_id) ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=1) if ev is not None: raise Exception("Unexpected connection") dev[0].remove_network(nid) ev = wpas.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1) if ev is not None: raise Exception("Unexpected connection") wpas.remove_network(w_nid) time.sleep(0.5) dev[0].request("BSS_FLUSH 0") wpas.request("BSS_FLUSH 0") # Add a BSS entry dev[0].scan_for_bss(bssid, freq="2412") wpas.scan_for_bss(bssid, freq="2412") # Start a connect radio work with a blocking entry preventing this from # proceeding; this stores a pointer to the selected BSS entry. id = dev[0].request("RADIO_WORK add block-work") w_id = wpas.request("RADIO_WORK add block-work") dev[0].wait_event(["EXT-RADIO-WORK-START"], timeout=1) wpas.wait_event(["EXT-RADIO-WORK-START"], timeout=1) # Schedule a connection based on the current BSS entry. dev[0].connect("open", key_mgmt="NONE", scan_freq="2412", wait_connect=False) wpas.connect("open", key_mgmt="NONE", scan_freq="2412", wait_connect=False) # Update scan results with results that have longer set of IEs so that new # memory needs to be allocated for the BSS entry. hapd.request("WPS_PBC") time.sleep(0.1) subprocess.call(['iw', dev[0].ifname, 'scan', 'trigger', 'freq', '2412']) subprocess.call(['iw', wpas.ifname, 'scan', 'trigger', 'freq', '2412']) time.sleep(0.1) # Allow the connect radio work to continue. The bss entry stored in the # pending connect work becomes stale during the scan and it must have been # updated for the connection to work. dev[0].request("RADIO_WORK done " + id) wpas.request("RADIO_WORK done " + w_id) dev[0].wait_connected(timeout=15, error="No connection (sme-connect)") wpas.wait_connected(timeout=15, error="No connection (connect)")
def test_p2p_listen_chan_optimize(dev, apdev): """P2P listen channel optimization""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5") addr5 = wpas.p2p_dev_addr() try: if "OK" not in wpas.request("SET p2p_optimize_listen_chan 1"): raise Exception("Failed to set p2p_optimize_listen_chan") wpas.p2p_listen() if not dev[0].discover_peer(addr5): raise Exception("Could not discover peer") peer = dev[0].get_peer(addr5) lfreq = peer['listen_freq'] wpas.p2p_stop_find() dev[0].p2p_stop_find() channel = "1" if lfreq != '2412' else "6" freq = "2412" if lfreq != '2412' else "2437" params = { "ssid": "test-open", "channel": channel } hapd = hostapd.add_ap(apdev[0]['ifname'], params) id = wpas.connect("test-open", key_mgmt="NONE", scan_freq=freq) wpas.p2p_listen() if "OK" not in dev[0].request("P2P_FLUSH"): raise Exception("P2P_FLUSH failed") if not dev[0].discover_peer(addr5): raise Exception("Could not discover peer") peer = dev[0].get_peer(addr5) lfreq2 = peer['listen_freq'] if lfreq == lfreq2: raise Exception("Listen channel did not change") if lfreq2 != freq: raise Exception("Listen channel not on AP's operating channel") wpas.p2p_stop_find() dev[0].p2p_stop_find() wpas.request("DISCONNECT") wpas.wait_disconnected() # for larger coverage, cover case of current channel matching wpas.select_network(id) wpas.wait_connected() wpas.request("DISCONNECT") wpas.wait_disconnected() lchannel = "1" if channel != "1" else "6" lfreq3 = "2412" if channel != "1" else "2437" if "OK" not in wpas.request("P2P_SET listen_channel " + lchannel): raise Exception("Failed to set listen channel") wpas.select_network(id) wpas.wait_connected() wpas.p2p_listen() if "OK" not in dev[0].request("P2P_FLUSH"): raise Exception("P2P_FLUSH failed") if not dev[0].discover_peer(addr5): raise Exception("Could not discover peer") peer = dev[0].get_peer(addr5) lfreq4 = peer['listen_freq'] if lfreq4 != lfreq3: raise Exception("Unexpected Listen channel after configuration") wpas.p2p_stop_find() dev[0].p2p_stop_find() finally: wpas.request("SET p2p_optimize_listen_chan 0")
def test_gas_fragment_mcc(dev, apdev): """GAS fragmentation with mac80211_hwsim MCC enabled""" with HWSimRadio(n_channels=2) as (radio, iface): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add(iface) gas_fragment_and_comeback(wpas, apdev[0], frag_limit=50)
def test_discovery_while_cli(dev, apdev, params): """P2P provision discovery from CLI""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5") run_discovery_while_cli(wpas, dev, params)
def test_discovery_while_cli_p2p_dev(dev, apdev, params): """P2P provision discovery from CLI (using P2P Device interface)""" with HWSimRadio(use_p2p_device=True) as (radio, iface): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add(iface) run_discovery_while_cli(wpas, dev, params)
def test_wpas_ctrl_global(dev): """wpa_supplicant global control interface""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5") if "PONG" not in wpas.global_request("PING"): raise Exception("PING failed") if "wlan5" not in wpas.global_request("INTERFACES"): raise Exception("Interface not found") if "UNKNOWN COMMAND" not in wpas.global_request("FOO"): raise Exception("Unexpected response to unknown command") if "PONG" not in wpas.global_request("IFNAME=wlan5 PING"): raise Exception("Per-interface PING failed") if "FAIL-NO-IFNAME-MATCH" not in wpas.global_request( "IFNAME=notfound PING"): raise Exception("Unknown interface not reported correctly") if "FAIL" not in wpas.global_request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG succeeded unexpectedly") if "OK" not in wpas.global_request("SET wifi_display 0"): raise Exception("SET failed") if "wifi_display=0" not in wpas.global_request("STATUS"): raise Exception("wifi_display not disabled") if "OK" not in wpas.global_request("SET wifi_display 1"): raise Exception("SET failed") if "wifi_display=1" not in wpas.global_request("STATUS"): raise Exception("wifi_display not enabled") if "FAIL" not in wpas.global_request("SET foo 1"): raise Exception("SET succeeded unexpectedly") if "p2p_state=IDLE" not in wpas.global_request("STATUS"): raise Exception("P2P was disabled") wpas.request("P2P_SET disabled 1") if "p2p_state=DISABLED" not in wpas.global_request("STATUS"): raise Exception("P2P was not disabled") wpas.request("P2P_SET disabled 0") if "p2p_state=IDLE" not in wpas.global_request("STATUS"): raise Exception("P2P was not enabled") # driver_nl80211.c does not support interface list, so do not fail because # of that logger.debug(wpas.global_request("INTERFACE_LIST")) if "FAIL" not in wpas.global_request("INTERFACE_ADD "): raise Exception("INTERFACE_ADD succeeded unexpectedly") if "FAIL" not in wpas.global_request("INTERFACE_ADD FOO"): raise Exception("INTERFACE_ADD succeeded unexpectedly") if "FAIL" not in wpas.global_request("INTERFACE_ADD FOO conf"): raise Exception("INTERFACE_ADD succeeded unexpectedly") if "FAIL" not in wpas.global_request("INTERFACE_ADD FOO conf driver"): raise Exception("INTERFACE_ADD succeeded unexpectedly") if "FAIL" not in wpas.global_request( "INTERFACE_ADD FOO conf driver ctrliface"): raise Exception("INTERFACE_ADD succeeded unexpectedly") if "FAIL" not in wpas.global_request( "INTERFACE_ADD FOO conf driver ctrliface driverparam"): raise Exception("INTERFACE_ADD succeeded unexpectedly") if "FAIL" not in wpas.global_request( "INTERFACE_ADD FOO conf driver ctrliface driverparam bridge"): raise Exception("INTERFACE_ADD succeeded unexpectedly") if "FAIL" not in wpas.global_request( "INTERFACE_ADD FOO conf driver ctrliface driverparam bridge foo"): raise Exception("INTERFACE_ADD succeeded unexpectedly") if "FAIL" not in wpas.global_request("INTERFACE_ADD FOO "): raise Exception("INTERFACE_ADD succeeded unexpectedly")
def cleanup_macsec(): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_remove("veth0") wpas.interface_remove("veth1") subprocess.call(["ip", "link", "del", "veth0"], stderr=open('/dev/null', 'w'))
def main(): test_file = None idx = 1 if len(sys.argv) > 1 and sys.argv[1] == '-d': logging.basicConfig(level=logging.DEBUG) idx = idx + 1 elif len(sys.argv) > 1 and sys.argv[1] == '-q': logging.basicConfig(level=logging.WARNING) idx = idx + 1 else: logging.basicConfig(level=logging.INFO) if len(sys.argv) > idx + 1 and sys.argv[idx] == '-f': test_file = sys.argv[idx + 1] idx = idx + 2 if len(sys.argv) > idx: test_filter = sys.argv[idx] else: test_filter = None dev0 = WpaSupplicant('wlan0') dev1 = WpaSupplicant('wlan1') dev2 = WpaSupplicant('wlan2') dev = [ dev0, dev1, dev2 ] apdev = [ ] apdev.append({"ifname": 'wlan3', "bssid": "02:00:00:00:03:00"}) apdev.append({"ifname": 'wlan4', "bssid": "02:00:00:00:04:00"}) for d in dev: if not d.ping(): print d.ifname + ": No response from wpa_supplicant" return print "DEV: " + d.ifname + ": " + d.p2p_dev_addr() for ap in apdev: print "APDEV: " + ap['ifname'] tests = [] for t in os.listdir("."): m = re.match(r'(test_.*)\.py$', t) if m: if test_file and test_file not in t: continue print "Import test cases from " + t mod = __import__(m.group(1)) for s in dir(mod): if s.startswith("test_"): func = mod.__dict__.get(s) tests.append(func) passed = [] failed = [] for t in tests: if test_filter: if test_filter != t.__name__: continue reset_devs(dev, apdev) print "START " + t.__name__ if t.__doc__: print "Test: " + t.__doc__ for d in dev: d.request("NOTE TEST-START " + t.__name__) try: if t.func_code.co_argcount > 1: t(dev, apdev) else: t(dev) passed.append(t.__name__) print "PASS " + t.__name__ except Exception, e: print e failed.append(t.__name__) print "FAIL " + t.__name__ for d in dev: d.request("NOTE TEST-STOP " + t.__name__)
def run_macsec_psk_ns(dev, apdev, params): try: subprocess.check_call([ "ip", "link", "add", "veth0", "type", "veth", "peer", "name", "veth1" ]) except subprocess.CalledProcessError: raise HwsimSkip("veth not supported (kernel CONFIG_VETH)") prefix = "macsec_psk_ns" conffile = os.path.join(params['logdir'], prefix + ".conf") pidfile = os.path.join(params['logdir'], prefix + ".pid") logfile0 = os.path.join(params['logdir'], prefix + ".veth0.log") logfile1 = os.path.join(params['logdir'], prefix + ".veth1.log") cap_veth0 = os.path.join(params['logdir'], prefix + ".veth0.pcap") cap_veth1 = os.path.join(params['logdir'], prefix + ".veth1.pcap") cap_macsec0 = os.path.join(params['logdir'], prefix + ".macsec0.pcap") cap_macsec1 = os.path.join(params['logdir'], prefix + ".macsec1.pcap") for i in range(2): try: subprocess.check_call(["ip", "netns", "add", "ns%d" % i]) except subprocess.CalledProcessError: raise HwsimSkip( "network namespace not supported (kernel CONFIG_NAMESPACES, CONFIG_NET_NS)" ) subprocess.check_call( ["ip", "link", "set", "veth%d" % i, "netns", "ns%d" % i]) subprocess.check_call([ "ip", "netns", "exec", "ns%d" % i, "ip", "link", "set", "dev", "veth%d" % i, "up" ]) cmd = {} cmd[0] = WlantestCapture('veth0', cap_veth0, netns='ns0') cmd[1] = WlantestCapture('veth1', cap_veth1, netns='ns1') write_conf(conffile + '0') write_conf(conffile + '1', mka_priority=100) prg = os.path.join(params['logdir'], 'alt-wpa_supplicant/wpa_supplicant/wpa_supplicant') if not os.path.exists(prg): prg = '../../wpa_supplicant/wpa_supplicant' arg = [ "ip", "netns", "exec", "ns0", prg, '-BdddtKW', '-P', pidfile + '0', '-f', logfile0, '-g', '/tmp/wpas-veth0', '-Dmacsec_linux', '-c', conffile + '0', '-i', "veth0" ] logger.info("Start wpa_supplicant: " + str(arg)) try: subprocess.check_call(arg) except subprocess.CalledProcessError: raise HwsimSkip( "macsec supported (wpa_supplicant CONFIG_MACSEC, CONFIG_DRIVER_MACSEC_LINUX; kernel CONFIG_MACSEC)" ) if os.path.exists("wpa_supplicant-macsec2"): logger.info( "Use alternative wpa_supplicant binary for one of the macsec devices" ) prg = "wpa_supplicant-macsec2" arg = [ "ip", "netns", "exec", "ns1", prg, '-BdddtKW', '-P', pidfile + '1', '-f', logfile1, '-g', '/tmp/wpas-veth1', '-Dmacsec_linux', '-c', conffile + '1', '-i', "veth1" ] logger.info("Start wpa_supplicant: " + str(arg)) subprocess.check_call(arg) wpas0 = WpaSupplicant('veth0', '/tmp/wpas-veth0') wpas1 = WpaSupplicant('veth1', '/tmp/wpas-veth1') log_ip_macsec_ns() log_ip_link_ns() logger.info("wpas0 STATUS:\n" + wpas0.request("STATUS")) logger.info("wpas1 STATUS:\n" + wpas1.request("STATUS")) logger.info("wpas0 STATUS-DRIVER:\n" + wpas0.request("STATUS-DRIVER")) logger.info("wpas1 STATUS-DRIVER:\n" + wpas1.request("STATUS-DRIVER")) for i in range(10): macsec_ifname0 = wpas0.get_driver_status_field("parent_ifname") macsec_ifname1 = wpas1.get_driver_status_field("parent_ifname") if "Number of Keys" in wpas0.request("STATUS"): key_tx0 = int(wpas0.get_status_field("Number of Keys Distributed")) key_rx0 = int(wpas0.get_status_field("Number of Keys Received")) else: key_tx0 = 0 key_rx0 = 0 if "Number of Keys" in wpas1.request("STATUS"): key_tx1 = int(wpas1.get_status_field("Number of Keys Distributed")) key_rx1 = int(wpas1.get_status_field("Number of Keys Received")) else: key_tx1 = 0 key_rx1 = 0 if key_rx0 > 0 and key_tx1 > 0: break time.sleep(1) cmd[2] = WlantestCapture(macsec_ifname0, cap_macsec0, netns='ns0') cmd[3] = WlantestCapture(macsec_ifname1, cap_macsec1, netns='ns0') time.sleep(0.5) logger.info("wpas0 STATUS:\n" + wpas0.request("STATUS")) logger.info("wpas1 STATUS:\n" + wpas1.request("STATUS")) log_ip_macsec_ns() hwsim_utils.test_connectivity(wpas0, wpas1, ifname1=macsec_ifname0, ifname2=macsec_ifname1, send_len=1400) log_ip_macsec_ns() subprocess.check_call([ 'ip', 'netns', 'exec', 'ns0', 'ip', 'addr', 'add', '192.168.248.17/30', 'dev', macsec_ifname0 ]) subprocess.check_call([ 'ip', 'netns', 'exec', 'ns1', 'ip', 'addr', 'add', '192.168.248.18/30', 'dev', macsec_ifname1 ]) c = subprocess.Popen( ['ip', 'netns', 'exec', 'ns0', 'ping', '-c', '2', '192.168.248.18'], stdout=subprocess.PIPE) res = c.stdout.read().decode() c.stdout.close() logger.info("ping:\n" + res) if "2 packets transmitted, 2 received" not in res: raise Exception("ping did not work") wpas0.close_monitor() wpas0.request("TERMINATE") wpas0.close_control() del wpas0 wpas1.close_monitor() wpas1.request("TERMINATE") wpas1.close_control() del wpas1 time.sleep(1) for i in range(len(cmd)): cmd[i].close()
def test_p2p_device_misuses(dev, apdev): """cfg80211 P2P Device misuses""" hapd = hostapd.add_ap(apdev[0]['ifname'], {"ssid": "open"}) with HWSimRadio(use_p2p_device=True) as (radio, iface): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add(iface) # Add a normal network profile to the P2P Device management only # interface to verify that it does not get used. id = int( wpas.global_request('IFNAME=p2p-dev-%s ADD_NETWORK' % iface).strip()) wpas.global_request('IFNAME=p2p-dev-%s SET_NETWORK %d ssid "open"' % (iface, id)) wpas.global_request('IFNAME=p2p-dev-%s SET_NETWORK %d key_mgmt NONE' % (iface, id)) wpas.global_request('IFNAME=p2p-dev-%s ENABLE_NETWORK %d' % (iface, id)) # Scan requests get ignored on p2p-dev wpas.global_request('IFNAME=p2p-dev-%s SCAN' % iface) dev[0].p2p_start_go(freq=2412) addr = dev[0].p2p_interface_addr() wpas.scan_for_bss(addr, freq=2412) wpas.connect("open", key_mgmt="NONE", scan_freq="2412") hwsim_utils.test_connectivity(wpas, hapd) pin = wpas.wps_read_pin() dev[0].p2p_go_authorize_client(pin) res = wpas.p2p_connect_group(dev[0].p2p_dev_addr(), pin, timeout=60, social=True, freq=2412) hwsim_utils.test_connectivity_p2p(dev[0], wpas) # Optimize scan-after-disconnect wpas.group_request("SET_NETWORK 0 scan_freq 2412") dev[0].group_request("DISASSOCIATE " + wpas.p2p_interface_addr()) ev = wpas.wait_group_event(["CTRL-EVENT-DISCONNECT"]) if ev is None: raise Exception( "Did not see disconnect event on P2P group interface") dev[0].remove_group() ev = wpas.wait_group_event(["CTRL-EVENT-SCAN-STARTED"], timeout=5) if ev is None: raise Exception("Scan not started") ev = wpas.wait_group_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=15) if ev is None: raise Exception("Scan not completed") time.sleep(1) hwsim_utils.test_connectivity(wpas, hapd) ev = hapd.wait_event(["AP-STA-DISCONNECTED"], timeout=0.1) if ev is not None: raise Exception( "Unexpected disconnection event received from hostapd") ev = wpas.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.1) if ev is not None: raise Exception( "Unexpected disconnection event received from wpa_supplicant") wpas.request("DISCONNECT") wpas.wait_disconnected()
name = t.__name__.replace('test_', '', 1) print name + " - " + t.__doc__ if conn: sql = 'INSERT OR REPLACE INTO tests(test,description) VALUES (?, ?)' params = (name, t.__doc__) try: conn.execute(sql, params) except Exception, e: print "sqlite: " + str(e) print "sql: %r" % (params, ) if conn: conn.commit() conn.close() sys.exit(0) dev0 = WpaSupplicant('wlan0', '/tmp/wpas-wlan0') dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1') dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2') dev = [dev0, dev1, dev2] apdev = [] apdev.append({"ifname": 'wlan3', "bssid": "02:00:00:00:03:00"}) apdev.append({"ifname": 'wlan4', "bssid": "02:00:00:00:04:00"}) for d in dev: if not d.ping(): logger.info(d.ifname + ": No response from wpa_supplicant") return logger.info("DEV: " + d.ifname + ": " + d.p2p_dev_addr()) for ap in apdev: logger.info("APDEV: " + ap['ifname'])
def test_owe_transition_mode_connect_cmd(dev, apdev): """Opportunistic Wireless Encryption transition mode using cfg80211 connect command""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_transition_mode([wpas], apdev)
def get_instance(self): """Return the Hostapd/WpaSupplicant instance""" if self.instance is None: self.instance = WpaSupplicant(global_iface='/tmp/wpas-wlan5') return self.instance
def test_owe_group_negotiation_connect_cmd(dev, apdev): """Opportunistic Wireless Encryption and group negotiation (connect command)""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_group_negotiation(wpas, apdev)
def test_wpas_ap_oom(dev): """wpa_supplicant AP mode - OOM""" id = dev[0].add_network() dev[0].set_network(id, "mode", "2") dev[0].set_network_quoted(id, "ssid", "wpas-ap") dev[0].set_network_quoted(id, "psk", "1234567890") dev[0].set_network(id, "frequency", "2412") dev[0].set_network(id, "scan_freq", "2412") with alloc_fail(dev[0], 1, "=wpa_supplicant_conf_ap"): dev[0].select_network(id) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") id = dev[0].add_network() dev[0].set_network(id, "mode", "2") dev[0].set_network_quoted(id, "ssid", "wpas-ap") dev[0].set_network( id, "psk", "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef") dev[0].set_network(id, "frequency", "2412") dev[0].set_network(id, "scan_freq", "2412") with alloc_fail(dev[0], 1, "=wpa_supplicant_conf_ap"): dev[0].select_network(id) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") id = dev[0].add_network() dev[0].set_network(id, "mode", "2") dev[0].set_network_quoted(id, "ssid", "wpas-ap") dev[0].set_network(id, "key_mgmt", "NONE") dev[0].set_network_quoted(id, "wep_key0", "hello") dev[0].set_network(id, "frequency", "2412") dev[0].set_network(id, "scan_freq", "2412") with alloc_fail(dev[0], 1, "=wpa_supplicant_conf_ap"): dev[0].select_network(id) dev[0].wait_disconnected() dev[0].request("REMOVE_NETWORK all") wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5") wpas.request("SET manufacturer test") wpas.request("SET model_name test") wpas.request("SET model_number test") wpas.request("SET serial_number test") wpas.request("SET serial_number test") wpas.request("SET serial_number test") wpas.request("SET ap_vendor_elements dd0411223301") id = wpas.add_network() wpas.set_network(id, "mode", "2") wpas.set_network_quoted(id, "ssid", "wpas-ap") wpas.set_network(id, "key_mgmt", "NONE") wpas.set_network(id, "frequency", "2412") wpas.set_network(id, "scan_freq", "2412") for i in range(5): with alloc_fail(wpas, i, "=wpa_supplicant_conf_ap"): wpas.select_network(id) ev = dev[0].wait_event( ["CTRL-EVENT-CONNECTED", "CTRL-EVENT-DISCONNECTED"], timeout=1) wpas.request("DISCONNECT") wpas.wait_disconnected()
def test_owe_pmksa_caching_connect_cmd(dev, apdev): """Opportunistic Wireless Encryption and PMKSA caching using cfg80211 connect command""" wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") run_owe_pmksa_caching([wpas], apdev)
def main(): tests = [] test_modules = [] files = os.listdir(scriptsdir) for t in files: m = re.match(r'(test_.*)\.py$', t) if m: logger.debug("Import test cases from " + t) mod = __import__(m.group(1)) test_modules.append(mod.__name__.replace('test_', '', 1)) for key, val in mod.__dict__.items(): if key.startswith("test_"): tests.append(val) test_names = list(set([t.__name__.replace('test_', '', 1) for t in tests])) run = None parser = argparse.ArgumentParser(description='hwsim test runner') parser.add_argument('--logdir', metavar='<directory>', help='log output directory for all other options, ' + 'must be given if other log options are used') group = parser.add_mutually_exclusive_group() group.add_argument('-d', const=logging.DEBUG, action='store_const', dest='loglevel', default=logging.INFO, help="verbose debug output") group.add_argument('-q', const=logging.WARNING, action='store_const', dest='loglevel', help="be quiet") parser.add_argument('-S', metavar='<sqlite3 db>', dest='database', help='database to write results to') parser.add_argument( '--prefill-tests', action='store_true', dest='prefill', help='prefill test database with NOTRUN before all tests') parser.add_argument('--commit', metavar='<commit id>', help='commit ID, only for database') parser.add_argument('-b', metavar='<build>', dest='build', help='build ID') parser.add_argument('-L', action='store_true', dest='update_tests_db', help='List tests (and update descriptions in DB)') parser.add_argument( '-T', action='store_true', dest='tracing', help='collect tracing per test case (in log directory)') parser.add_argument('-D', action='store_true', dest='dmesg', help='collect dmesg per test case (in log directory)') parser.add_argument('--dbus', action='store_true', dest='dbus', help='collect dbus per test case (in log directory)') parser.add_argument('--shuffle-tests', action='store_true', dest='shuffle_tests', help='Shuffle test cases to randomize order') parser.add_argument( '--split', help= 'split tests for parallel execution (<server number>/<total servers>)') parser.add_argument('--no-reset', action='store_true', dest='no_reset', help='Do not reset devices at the end of the test') parser.add_argument('--long', action='store_true', help='Include test cases that take long time') parser.add_argument('-f', dest='testmodules', metavar='<test module>', help='execute only tests from these test modules', type=str, choices=[[]] + test_modules, nargs='+') parser.add_argument('-l', metavar='<modules file>', dest='mfile', help='test modules file name') parser.add_argument('-i', action='store_true', dest='stdin_ctrl', help='stdin-controlled test case execution') parser.add_argument('tests', metavar='<test>', nargs='*', type=str, help='tests to run (only valid without -f)') args = parser.parse_args() if (args.tests and args.testmodules) or (args.tests and args.mfile) or ( args.testmodules and args.mfile): print( 'Invalid arguments - only one of (test, test modules, modules file) can be given.' ) sys.exit(2) if args.tests: fail = False for t in args.tests: if t.endswith('*'): prefix = t.rstrip('*') found = False for tn in test_names: if tn.startswith(prefix): found = True break if not found: print( 'Invalid arguments - test "%s" wildcard did not match' % t) fail = True elif t not in test_names: print('Invalid arguments - test "%s" not known' % t) fail = True if fail: sys.exit(2) if args.database: if not sqlite3_imported: print("No sqlite3 module found") sys.exit(2) conn = sqlite3.connect(args.database) conn.execute( 'CREATE TABLE IF NOT EXISTS results (test,result,run,time,duration,build,commitid)' ) conn.execute('CREATE TABLE IF NOT EXISTS tests (test,description)') conn.execute( 'CREATE TABLE IF NOT EXISTS logs (test,run,type,contents)') else: conn = None if conn: run = int(time.time()) # read the modules from the modules file if args.mfile: args.testmodules = [] with open(args.mfile) as f: for line in f.readlines(): line = line.strip() if not line or line.startswith('#'): continue args.testmodules.append(line) tests_to_run = [] if args.tests: for selected in args.tests: for t in tests: name = t.__name__.replace('test_', '', 1) if selected.endswith('*'): prefix = selected.rstrip('*') if name.startswith(prefix): tests_to_run.append(t) elif name == selected: tests_to_run.append(t) else: for t in tests: name = t.__name__.replace('test_', '', 1) if args.testmodules: if t.__module__.replace('test_', '', 1) not in args.testmodules: continue tests_to_run.append(t) if args.update_tests_db: for t in tests_to_run: name = t.__name__.replace('test_', '', 1) if t.__doc__ is None: print(name + " - MISSING DESCRIPTION") else: print(name + " - " + t.__doc__) if conn: sql = 'INSERT OR REPLACE INTO tests(test,description) VALUES (?, ?)' params = (name, t.__doc__) try: conn.execute(sql, params) except Exception as e: print("sqlite: " + str(e)) print("sql: %r" % (params, )) if conn: conn.commit() conn.close() sys.exit(0) if not args.logdir: if os.path.exists('logs/current'): args.logdir = 'logs/current' else: args.logdir = 'logs' # Write debug level log to a file and configurable verbosity to stdout logger.setLevel(logging.DEBUG) stdout_handler = logging.StreamHandler() stdout_handler.setLevel(args.loglevel) logger.addHandler(stdout_handler) file_name = os.path.join(args.logdir, 'run-tests.log') log_handler = logging.FileHandler(file_name, encoding='utf-8') log_handler.setLevel(logging.DEBUG) fmt = "%(asctime)s %(levelname)s %(message)s" log_formatter = logging.Formatter(fmt) log_handler.setFormatter(log_formatter) logger.addHandler(log_handler) dev0 = WpaSupplicant('wlan0', '/tmp/wpas-wlan0') dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1') dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2') dev = [dev0, dev1, dev2] apdev = [] apdev.append({"ifname": 'wlan3', "bssid": "02:00:00:00:03:00"}) apdev.append({"ifname": 'wlan4', "bssid": "02:00:00:00:04:00"}) for d in dev: if not d.ping(): logger.info(d.ifname + ": No response from wpa_supplicant") return logger.info("DEV: " + d.ifname + ": " + d.p2p_dev_addr()) for ap in apdev: logger.info("APDEV: " + ap['ifname']) passed = [] skipped = [] failed = [] # make sure nothing is left over from previous runs # (if there were any other manual runs or we crashed) if not reset_devs(dev, apdev): if conn: conn.close() conn = None sys.exit(1) if args.dmesg: subprocess.call(['dmesg', '-c'], stdout=open('/dev/null', 'w')) if conn and args.prefill: for t in tests_to_run: name = t.__name__.replace('test_', '', 1) report(conn, False, args.build, args.commit, run, name, 'NOTRUN', 0, args.logdir, sql_commit=False) conn.commit() if args.split: vals = args.split.split('/') split_server = int(vals[0]) split_total = int(vals[1]) logger.info("Parallel execution - %d/%d" % (split_server, split_total)) split_server -= 1 tests_to_run.sort(key=lambda t: t.__name__) tests_to_run = [ x for i, x in enumerate(tests_to_run) if i % split_total == split_server ] if args.shuffle_tests: from random import shuffle shuffle(tests_to_run) count = 0 if args.stdin_ctrl: print("READY") sys.stdout.flush() num_tests = 0 else: num_tests = len(tests_to_run) if args.stdin_ctrl: set_term_echo(sys.stdin.fileno(), False) check_country_00 = True for d in dev: if d.get_driver_status_field("country") != "00": check_country_00 = False while True: if args.stdin_ctrl: test = sys.stdin.readline() if not test: break test = test.splitlines()[0] if test == '': break t = None for tt in tests: name = tt.__name__.replace('test_', '', 1) if name == test: t = tt break if not t: print("NOT-FOUND") sys.stdout.flush() continue else: if len(tests_to_run) == 0: break t = tests_to_run.pop(0) if dev[0].get_driver_status_field("country") == "98": # Work around cfg80211 regulatory issues in clearing intersected # country code 98. Need to make station disconnect without any # other wiphy being active in the system. logger.info("country=98 workaround - try to clear state") id = dev[1].add_network() dev[1].set_network(id, "mode", "2") dev[1].set_network_quoted(id, "ssid", "country98") dev[1].set_network(id, "key_mgmt", "NONE") dev[1].set_network(id, "frequency", "2412") dev[1].set_network(id, "scan_freq", "2412") dev[1].select_network(id) ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"]) if ev: dev[0].connect("country98", key_mgmt="NONE", scan_freq="2412") dev[1].request("DISCONNECT") dev[0].wait_disconnected() dev[0].disconnect_and_stop_scan() dev[0].reset() dev[1].reset() dev[0].dump_monitor() dev[1].dump_monitor() name = t.__name__.replace('test_', '', 1) open('/dev/kmsg', 'w').write('running hwsim test case %s\n' % name) if log_handler: log_handler.stream.close() logger.removeHandler(log_handler) file_name = os.path.join(args.logdir, name + '.log') log_handler = logging.FileHandler(file_name, encoding='utf-8') log_handler.setLevel(logging.DEBUG) log_handler.setFormatter(log_formatter) logger.addHandler(log_handler) reset_ok = True with DataCollector(args.logdir, name, args): count = count + 1 msg = "START {} {}/{}".format(name, count, num_tests) logger.info(msg) if args.loglevel == logging.WARNING: print(msg) sys.stdout.flush() if t.__doc__: logger.info("Test: " + t.__doc__) start = datetime.now() open('/dev/kmsg', 'w').write('TEST-START %s @%.6f\n' % (name, time.time())) for d in dev: try: d.dump_monitor() if not d.ping(): raise Exception("PING failed for {}".format(d.ifname)) if not d.global_ping(): raise Exception("Global PING failed for {}".format( d.ifname)) d.request("NOTE TEST-START " + name) except Exception as e: logger.info("Failed to issue TEST-START before " + name + " for " + d.ifname) logger.info(e) print("FAIL " + name + " - could not start test") if conn: conn.close() conn = None if args.stdin_ctrl: set_term_echo(sys.stdin.fileno(), True) sys.exit(1) skip_reason = None try: if t.__code__.co_argcount > 2: params = {} params['logdir'] = args.logdir params['long'] = args.long params['name'] = name params['prefix'] = os.path.join(args.logdir, name) t(dev, apdev, params) elif t.__code__.co_argcount > 1: t(dev, apdev) else: t(dev) result = "PASS" if check_country_00: for d in dev: country = d.get_driver_status_field("country") if country != "00": d.dump_monitor() logger.info( d.ifname + ": Country code not reset back to 00: is " + country) print(d.ifname + ": Country code not reset back to 00: is " + country) result = "FAIL" # Try to wait for cfg80211 regulatory state to # clear. d.cmd_execute(['iw', 'reg', 'set', '00']) for i in range(5): time.sleep(1) country = d.get_driver_status_field("country") if country == "00": break if country == "00": print(d.ifname + ": Country code cleared back to 00") logger.info( d.ifname + ": Country code cleared back to 00") else: print( "Country code remains set - expect following test cases to fail" ) logger.info( "Country code remains set - expect following test cases to fail" ) break except HwsimSkip as e: logger.info("Skip test case: %s" % e) skip_reason = e result = "SKIP" except NameError as e: import traceback logger.info(e) traceback.print_exc() result = "FAIL" except Exception as e: import traceback logger.info(e) traceback.print_exc() if args.loglevel == logging.WARNING: print("Exception: " + str(e)) result = "FAIL" open('/dev/kmsg', 'w').write('TEST-STOP %s @%.6f\n' % (name, time.time())) for d in dev: try: d.dump_monitor() d.request("NOTE TEST-STOP " + name) except Exception as e: logger.info( "Failed to issue TEST-STOP after {} for {}".format( name, d.ifname)) logger.info(e) result = "FAIL" if args.no_reset: print("Leaving devices in current state") else: reset_ok = reset_devs(dev, apdev) wpas = None try: wpas = WpaSupplicant(global_iface="/tmp/wpas-wlan5", monitor=False) rename_log(args.logdir, 'log5', name, wpas) if not args.no_reset: wpas.remove_ifname() except Exception as e: pass if wpas: wpas.close_ctrl() del wpas for i in range(0, 3): rename_log(args.logdir, 'log' + str(i), name, dev[i]) try: hapd = HostapdGlobal() except Exception as e: print("Failed to connect to hostapd interface") print(str(e)) reset_ok = False result = "FAIL" hapd = None rename_log(args.logdir, 'hostapd', name, hapd) if hapd: del hapd hapd = None # Use None here since this instance of Wlantest() will never be # used for remote host hwsim tests on real hardware. Wlantest.setup(None) wt = Wlantest() rename_log(args.logdir, 'hwsim0.pcapng', name, wt) rename_log(args.logdir, 'hwsim0', name, wt) if os.path.exists(os.path.join(args.logdir, 'fst-wpa_supplicant')): rename_log(args.logdir, 'fst-wpa_supplicant', name, None) if os.path.exists(os.path.join(args.logdir, 'fst-hostapd')): rename_log(args.logdir, 'fst-hostapd', name, None) if os.path.exists(os.path.join(args.logdir, 'wmediumd.log')): rename_log(args.logdir, 'wmediumd.log', name, None) end = datetime.now() diff = end - start if result == 'PASS' and args.dmesg: if not check_kernel(os.path.join(args.logdir, name + '.dmesg')): logger.info("Kernel issue found in dmesg - mark test failed") result = 'FAIL' if result == 'PASS': passed.append(name) elif result == 'SKIP': skipped.append(name) else: failed.append(name) report(conn, args.prefill, args.build, args.commit, run, name, result, diff.total_seconds(), args.logdir) result = "{} {} {} {}".format(result, name, diff.total_seconds(), end) logger.info(result) if args.loglevel == logging.WARNING: print(result) if skip_reason: print("REASON", skip_reason) sys.stdout.flush() if not reset_ok: print("Terminating early due to device reset failure") break if args.stdin_ctrl: set_term_echo(sys.stdin.fileno(), True) if log_handler: log_handler.stream.close() logger.removeHandler(log_handler) file_name = os.path.join(args.logdir, 'run-tests.log') log_handler = logging.FileHandler(file_name, encoding='utf-8') log_handler.setLevel(logging.DEBUG) log_handler.setFormatter(log_formatter) logger.addHandler(log_handler) if conn: conn.close() if len(failed): logger.info("passed {} test case(s)".format(len(passed))) logger.info("skipped {} test case(s)".format(len(skipped))) logger.info("failed tests: " + ' '.join(failed)) if args.loglevel == logging.WARNING: print("failed tests: " + ' '.join(failed)) sys.exit(1) logger.info("passed all {} test case(s)".format(len(passed))) if len(skipped): logger.info("skipped {} test case(s)".format(len(skipped))) if args.loglevel == logging.WARNING: print("passed all {} test case(s)".format(len(passed))) if len(skipped): print("skipped {} test case(s)".format(len(skipped)))
def run_hwsim_test(devices, setup_params, refs, duts, monitors, hwsim_test): try: ref_hosts = [] dut_hosts = [] dev = [] apdev = [] # get hosts for ref in refs: ref_host = rutils.get_host(devices, ref) ref_hosts.append(ref_host) for dut in duts: dut_host = rutils.get_host(devices, dut) dut_hosts.append(dut_host) # setup log dir local_log_dir = setup_params['local_log_dir'] # setup hw before test rutils.setup_hw(ref_hosts, setup_params) rutils.setup_hw(dut_hosts, setup_params) # run monitors if requested/possible for ref_host in ref_hosts: monitor.add(ref_host, monitors) monitor.run(ref_host, setup_params) for dut_host in dut_hosts: monitor.add(dut_host, monitors) monitor.run(dut_host, setup_params) monitor_hosts = monitor.create(devices, setup_params, refs, duts, monitors) mon = None if len(monitor_hosts) > 0: mon = monitor_hosts[0] wlantest.Wlantest.reset_remote_wlantest() wlantest.Wlantest.register_remote_wlantest(mon, setup_params, monitor) # run hostapd/wpa_supplicant for ref_host in ref_hosts: rutils.run_wpasupplicant(ref_host, setup_params) wpas = WpaSupplicant(hostname=ref_host.host, global_iface="udp", global_port=ref_host.port) wpas.interface_add(ref_host.ifname) dev.append(wpas) for dut_host in dut_hosts: rutils.run_hostapd(dut_host, setup_params) dut_host.dev['bssid'] = rutils.get_mac_addr(dut_host) apdev.append(dut_host.dev) if hwsim_test.__code__.co_argcount == 1: hwsim_test(dev) elif hwsim_test.__code__.co_argcount == 2: hwsim_test(dev, apdev) else: params = {} params['long'] = 1 params['logdir'] = local_log_dir hwsim_test(dev, apdev, params) # hostapd/wpa_supplicant cleanup for wpas in dev: wpas.interface_remove(wpas.host.ifname) wpas.terminate() dev = [] # remove monitors for ref_host in ref_hosts: monitor.remove(ref_host) for dut_host in dut_hosts: monitor.remove(dut_host) for ref_host in ref_hosts: rutils.kill_wpasupplicant(ref_host, setup_params) ref_host.get_logs(local_log_dir) for dut_host in dut_hosts: rutils.kill_hostapd(dut_host, setup_params) dut_host.get_logs(local_log_dir) if mon is not None: wlantest.Wlantest.reset_remote_wlantest() mon.get_logs(local_log_dir) return "" except: logger.info(traceback.format_exc()) for wpas in dev: try: wpas.interface_remove(wpas.host.ifname) wpas.terminate() except: pass for ref_host in ref_hosts: monitor.remove(ref_host) for dut_host in dut_hosts: monitor.remove(dut_host) for ref_host in ref_hosts: rutils.kill_wpasupplicant(ref_host, setup_params) ref_host.get_logs(local_log_dir) for dut_host in dut_hosts: rutils.kill_hostapd(dut_host, setup_params) dut_host.get_logs(local_log_dir) if mon is not None: wlantest.Wlantest.reset_remote_wlantest() mon.get_logs(local_log_dir) raise
[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) def reset_devs(dev, apdev): ok = True for d in dev: try: d.reset() except Exception, e: logger.info("Failed to reset device " + d.ifname) print str(e) ok = False wpas = None try: wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') ifaces = wpas.global_request("INTERFACES").splitlines() for iface in ifaces: if iface.startswith("wlan"): wpas.interface_remove(iface) except Exception, e: pass if wpas: wpas.close_ctrl() try: hapd = HostapdGlobal() hapd.flush() hapd.remove('wlan3-3') hapd.remove('wlan3-2') for ap in apdev:
def _test_ap_track_taxonomy(dev, apdev): params = {"ssid": "track", "country_code": "US", "hw_mode": "g", "channel": "6", "track_sta_max_num": "2"} hapd = hostapd.add_ap(apdev[0], params) bssid = apdev[0]['bssid'] dev[0].scan_for_bss(bssid, freq=2437, force_scan=True) addr0 = dev[0].own_addr() dev[0].connect("track", key_mgmt="NONE", scan_freq="2437") dev[1].request("SET p2p_disabled 1") dev[1].scan_for_bss(bssid, freq=2437, force_scan=True) addr1 = dev[1].own_addr() dev[1].connect("track", key_mgmt="NONE", scan_freq="2437") wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5") wpas.request("SET model_name track test") wpas.scan_for_bss(bssid, freq=2437, force_scan=True) addr = wpas.own_addr() wpas.connect("track", key_mgmt="NONE", scan_freq="2437") if "FAIL" not in hapd.request("SIGNATURE abc"): raise Exception("SIGNATURE failure not reported (1)") if "FAIL" not in hapd.request("SIGNATURE 22:33:44:55:66:77"): raise Exception("SIGNATURE failure not reported (2)") res = hapd.request("SIGNATURE " + addr0) logger.info("sta0: " + res) if not res.startswith("wifi4|probe:"): raise Exception("Unexpected SIGNATURE prefix") if "|assoc:" not in res: raise Exception("Missing assoc info in SIGNATURE") if "wps:track_test" in res: raise Exception("Unexpected WPS model name") res = hapd.request("SIGNATURE " + addr1) logger.info("sta1: " + res) if not res.startswith("wifi4|probe:"): raise Exception("Unexpected SIGNATURE prefix") if "|assoc:" not in res: raise Exception("Missing assoc info in SIGNATURE") if "wps:" in res: raise Exception("Unexpected WPS info") if ",221(0050f2,4)," in res: raise Exception("Unexpected WPS IE info") if ",221(506f9a,9)," in res: raise Exception("Unexpected P2P IE info") res = hapd.request("SIGNATURE " + addr) logger.info("sta: " + res) if not res.startswith("wifi4|probe:"): raise Exception("Unexpected SIGNATURE prefix") if "|assoc:" not in res: raise Exception("Missing assoc info in SIGNATURE") if "wps:track_test" not in res: raise Exception("Missing WPS model name") if ",221(0050f2,4)," not in res: raise Exception("Missing WPS IE info") if ",221(506f9a,9)," not in res: raise Exception("Missing P2P IE info") addr2 = dev[2].own_addr() res = hapd.request("SIGNATURE " + addr2) if "FAIL" not in res: raise Exception("Unexpected SIGNATURE success for sta2 (1)") for i in range(10): dev[2].request("SCAN freq=2437 passive=1") ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10) if ev is None: raise Exception("Scan did not complete") if dev[2].get_bss(bssid): break res = hapd.request("SIGNATURE " + addr2) if "FAIL" not in res: raise Exception("Unexpected SIGNATURE success for sta2 (2)") dev[2].connect("track", key_mgmt="NONE", scan_freq="2437") res = hapd.request("SIGNATURE " + addr2) if "FAIL" not in res and len(res) > 0: raise Exception("Unexpected SIGNATURE success for sta2 (3)") dev[2].scan_for_bss(bssid, freq=2437, force_scan=True) res = hapd.request("SIGNATURE " + addr2) logger.info("sta2: " + res) if not res.startswith("wifi4|probe:"): raise Exception("Unexpected SIGNATURE prefix") if "|assoc:" not in res: raise Exception("Missing assoc info in SIGNATURE")
def test_wpas_config_file(dev, apdev, params): """wpa_supplicant config file parsing/writing""" config = os.path.join(params['logdir'], 'wpas_config_file.conf') if os.path.exists(config): try: os.remove(config) except: pass try: os.rmdir(config) except: pass wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') try: wpas.interface_add("wlan5", config=config) initialized = True except: initialized = False if initialized: raise Exception("Missing config file did not result in an error") try: with open(config, "w") as f: f.write("update_config=1 \t\r\n") f.write("# foo\n") f.write("\n") f.write(" \t\reapol_version=2") for i in range(0, 100): f.write(" ") f.write("foo\n") f.write("device_name=name#foo\n") wpas.interface_add("wlan5", config=config) capa = {} capa['mesh'] = "MESH" in wpas.get_capability("modes") capa['sae'] = "SAE" in wpas.get_capability("auth_alg") id = wpas.add_network() wpas.set_network_quoted(id, "ssid", "foo") wpas.set_network_quoted(id, "psk", "12345678") wpas.set_network(id, "bssid", "00:11:22:33:44:55") wpas.set_network(id, "proto", "RSN") wpas.set_network(id, "key_mgmt", "WPA-PSK-SHA256") wpas.set_network(id, "pairwise", "CCMP") wpas.set_network(id, "group", "CCMP") wpas.set_network(id, "auth_alg", "OPEN") id = wpas.add_cred() wpas.set_cred(id, "priority", "3") wpas.set_cred(id, "sp_priority", "6") wpas.set_cred(id, "update_identifier", "4") wpas.set_cred(id, "ocsp", "1") wpas.set_cred(id, "eap", "TTLS") wpas.set_cred(id, "req_conn_capab", "6:1234") wpas.set_cred_quoted(id, "realm", "example.com") wpas.set_cred_quoted(id, "provisioning_sp", "example.com") wpas.set_cred_quoted(id, "domain", "example.com") wpas.set_cred_quoted(id, "domain_suffix_match", "example.com") wpas.set_cred(id, "roaming_consortium", "112233") wpas.set_cred(id, "required_roaming_consortium", "112233") wpas.set_cred_quoted(id, "roaming_consortiums", "112233,aabbccddee,445566") wpas.set_cred_quoted(id, "roaming_partner", "roaming.example.net,1,127,*") wpas.set_cred_quoted(id, "ca_cert", "/tmp/ca.pem") wpas.set_cred_quoted(id, "username", "user") wpas.set_cred_quoted(id, "password", "secret") ev = wpas.wait_event(["CRED-MODIFIED 0 password"]) wpas.request("SET blob foo 12345678") for field, value in config_checks: if supported_param(capa, field): wpas.set(field, value) if "OK" not in wpas.request("SAVE_CONFIG"): raise Exception("Failed to save configuration file") if "OK" not in wpas.global_request("SAVE_CONFIG"): raise Exception("Failed to save configuration file") wpas.interface_remove("wlan5") data1 = check_config(capa, config) wpas.interface_add("wlan5", config=config) if len(wpas.list_networks()) != 1: raise Exception("Unexpected number of networks") if len(wpas.request("LIST_CREDS").splitlines()) != 2: raise Exception("Unexpected number of credentials") val = wpas.get_cred(0, "roaming_consortiums") if val != "112233,aabbccddee,445566": raise Exception("Unexpected roaming_consortiums value: " + val) if "OK" not in wpas.request("SAVE_CONFIG"): raise Exception("Failed to save configuration file") data2 = check_config(capa, config) if data1 != data2: logger.debug(data1) logger.debug(data2) raise Exception("Unexpected configuration change") wpas.request("SET update_config 0") wpas.global_request("SET update_config 0") if "OK" in wpas.request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG succeeded unexpectedly") if "OK" in wpas.global_request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG (global) succeeded unexpectedly") # replace the config file with a directory to break writing/renaming os.remove(config) os.mkdir(config) wpas.request("SET update_config 1") wpas.global_request("SET update_config 1") if "OK" in wpas.request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG succeeded unexpectedly") if "OK" in wpas.global_request("SAVE_CONFIG"): raise Exception("SAVE_CONFIG (global) succeeded unexpectedly") finally: try: os.rmdir(config) except: pass wpas.dump_monitor() wpas.request("SET country 00") wpas.wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
def test_grpform_cred_ready_timeout(dev, apdev, params): """P2P GO Negotiation wait for credentials to become ready [long]""" if not params['long']: raise HwsimSkip("Skip test case with long duration due to --long not specified") dev[1].p2p_listen() addr1 = dev[1].p2p_dev_addr() if not dev[0].discover_peer(addr1): raise Exception("Peer " + addr1 + " not found") if not dev[2].discover_peer(addr1): raise Exception("Peer " + addr1 + " not found(2)") start = os.times()[4] cmd = "P2P_CONNECT " + addr1 + " 12345670 display" if "OK" not in dev[0].global_request(cmd): raise Exception("Failed to initiate GO Neg") if "OK" not in dev[2].global_request(cmd): raise Exception("Failed to initiate GO Neg(2)") # First, check with p2p_find ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=30) if ev is not None: raise Exception("Too early GO Negotiation timeout reported(2)") dev[2].dump_monitor() logger.info("Starting p2p_find to change state") dev[2].p2p_find() for i in range(10): ev = dev[2].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=10) if ev: break dev[2].dump_monitor(global_mon=False) if ev is None: raise Exception("GO Negotiation failure timed out(2)") dev[2].dump_monitor() end = os.times()[4] logger.info("GO Negotiation wait time: {} seconds(2)".format(end - start)) if end - start < 120: raise Exception("Too short GO Negotiation wait time(2): {}".format(end - start)) wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5") wpas.p2p_listen() ev = dev[2].wait_global_event(["P2P-DEVICE-FOUND"], timeout=10) if ev is None: raise Exception("Did not discover new device after GO Negotiation failure") if wpas.p2p_dev_addr() not in ev: raise Exception("Unexpected device found: " + ev) dev[2].p2p_stop_find() dev[2].dump_monitor() wpas.p2p_stop_find() wpas.close_monitor() del wpas # Finally, verify without p2p_find ev = dev[0].wait_global_event(["P2P-GO-NEG-FAILURE"], timeout=120) if ev is None: raise Exception("GO Negotiation failure timed out") end = os.times()[4] logger.info("GO Negotiation wait time: {} seconds".format(end - start)) if end - start < 120: raise Exception("Too short GO Negotiation wait time: {}".format(end - start))
def test_go_neg_forced_freq_diff_than_bss_freq(dev, apdev): """P2P channel selection: GO negotiation with forced freq different than station interface""" with HWSimRadio(n_channels=2) as (radio, iface): wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add(iface) if wpas.get_mcc() < 2: raise Exception("New radio does not support MCC") # Clear possible PBC session overlap from previous test case dev[1].flush_scan_cache() wpas.request("SET p2p_no_group_iface 0") hapd = hostapd.add_ap( apdev[0]['ifname'], { "country_code": 'US', "ssid": 'bss-5ghz', "hw_mode": 'a', "channel": '40' }) wpas.connect("bss-5ghz", key_mgmt="NONE", scan_freq="5200") # GO and peer force the same freq, different than BSS freq, # wpas to become GO [i_res, r_res] = go_neg_pbc(i_dev=dev[1], i_intent=1, i_freq=5180, r_dev=wpas, r_intent=14, r_freq=5180) check_grpform_results(i_res, r_res) if i_res['freq'] != "5180": raise Exception("P2P group formed on unexpected frequency: " + i_res['freq']) if r_res['role'] != "GO": raise Exception("GO not selected according to go_intent") hwsim_utils.test_connectivity(wpas, hapd) wpas.remove_group(r_res['ifname']) dev[1].wait_go_ending_session() dev[1].flush_scan_cache() # GO and peer force the same freq, different than BSS freq, wpas to # become client [i_res2, r_res2] = go_neg_pbc(i_dev=dev[1], i_intent=14, i_freq=2422, r_dev=wpas, r_intent=1, r_freq=2422) check_grpform_results(i_res2, r_res2) if i_res2['freq'] != "2422": raise Exception("P2P group formed on unexpected frequency: " + i_res2['freq']) if r_res2['role'] != "client": raise Exception("GO not selected according to go_intent") hwsim_utils.test_connectivity(wpas, hapd) wpas.request("DISCONNECT") hapd.request("DISABLE") subprocess.call(['iw', 'reg', 'set', '00']) wpas.flush_scan_cache()
def test_ap_pmf_sta_unprot_deauth_burst(dev, apdev): """WPA2-PSK AP with station receiving burst of unprotected Deauthentication frames""" ssid = "deauth-attack" addr = dev[0].own_addr() wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') wpas.interface_add("wlan5", drv_params="use_monitor=1") id = wpas.add_network() wpas.set_network(id, "mode", "2") wpas.set_network_quoted(id, "ssid", ssid) wpas.set_network(id, "proto", "WPA2") wpas.set_network(id, "key_mgmt", "WPA-PSK-SHA256") wpas.set_network(id, "ieee80211w", "2") wpas.set_network_quoted(id, "psk", "12345678") wpas.set_network(id, "pairwise", "CCMP") wpas.set_network(id, "group", "CCMP") wpas.set_network(id, "frequency", "2412") wpas.connect_network(id) bssid = wpas.own_addr() Wlantest.setup(wpas) wt = Wlantest() wt.flush() wt.add_passphrase("12345678") dev[0].connect(ssid, psk="12345678", ieee80211w="1", key_mgmt="WPA-PSK WPA-PSK-SHA256", proto="WPA2", scan_freq="2412") for i in range(0, 10): wpas.request("DEAUTHENTICATE " + addr + " reason=6 test=0") wpas.request("DISASSOCIATE " + addr + " reason=7 test=0") ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1) if ev is not None: raise Exception("Unexpected disconnection") num_req = wt.get_sta_counter("valid_saqueryreq_tx", bssid, addr) num_resp = wt.get_sta_counter("valid_saqueryresp_rx", bssid, addr) if num_req < 1: raise Exception("STA did not send SA Query") if num_resp < 1: raise Exception("AP did not reply to SA Query") if num_req > 1: raise Exception("STA initiated too many SA Query procedures (%d)" % num_req) time.sleep(10) for i in range(0, 5): wpas.request("DEAUTHENTICATE " + addr + " reason=6 test=0") wpas.request("DISASSOCIATE " + addr + " reason=7 test=0") ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1) if ev is not None: raise Exception("Unexpected disconnection") num_req = wt.get_sta_counter("valid_saqueryreq_tx", bssid, addr) num_resp = wt.get_sta_counter("valid_saqueryresp_rx", bssid, addr) if num_req != 2 or num_resp != 2: raise Exception( "Unexpected number of SA Query procedures (req=%d resp=%d)" % (num_req, num_resp))