示例#1
0
def test_ap_pmf_ap_dropping_sa(dev, apdev):
    """WPA2-PSK PMF AP dropping SA"""
    ssid = "pmf"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    hapd = hostapd.add_ap(apdev[0], params)
    bssid = hapd.own_addr()
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    dev[0].connect(ssid, psk="12345678", ieee80211w="2",
                   key_mgmt="WPA-PSK-SHA256", proto="WPA2", scan_freq="2412")
    addr0 = dev[0].own_addr()
    dev[0].dump_monitor()
    hapd.wait_sta()
    # Drop SA and association at the AP locally without notifying the STA. This
    # results in the STA getting unprotected Deauthentication frames when trying
    # to transmit the next Class 3 frame.
    if "OK" not in hapd.request("DEAUTHENTICATE " + addr0 + " tx=0"):
        raise Exception("DEAUTHENTICATE command failed")
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection event after DEAUTHENTICATE tx=0: " + ev)
    dev[0].request("DATA_TEST_CONFIG 1")
    dev[0].request("DATA_TEST_TX " + bssid + " " + addr0)
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=5)
    dev[0].request("DATA_TEST_CONFIG 0")
    if ev is None or "locally_generated=1" not in ev:
        raise Exception("Locally generated disconnection not reported")
示例#2
0
def test_ap_pmf_negative(dev, apdev):
    """WPA2-PSK AP without PMF (negative test)"""
    ssid = "test-pmf-negative"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    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")
    hwsim_utils.test_connectivity(dev[0], hapd)
    try:
        dev[1].connect(ssid,
                       psk="12345678",
                       ieee80211w="2",
                       key_mgmt="WPA-PSK WPA-PSK-SHA256",
                       proto="WPA2",
                       scan_freq="2412")
        hwsim_utils.test_connectivity(dev[1], hapd)
        raise Exception("PMF required STA connected to no PMF AP")
    except Exception as e:
        logger.debug("Ignore expected exception: " + str(e))
    wt.require_ap_no_pmf(apdev[0]['bssid'])
示例#3
0
def run_ap_wpa2_gtk_initial_rsc(dev, apdev, cipher):
    if cipher not in dev[0].get_capability("pairwise") or \
       cipher not in dev[0].get_capability("group"):
        raise HwsimSkip("Cipher %s not supported" % cipher)

    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
    params["rsn_pairwise"] = cipher
    params["group_cipher"] = cipher
    params["gtk_rsc_override"] = "341200000000"
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect("test-wpa2-psk",
                   psk="12345678",
                   proto="WPA2",
                   pairwise=cipher,
                   group=cipher,
                   scan_freq="2412")
    hapd.wait_sta()
    # Verify that unicast traffic works, but broadcast traffic does not.
    hwsim_utils.test_connectivity(dev[0], hapd, broadcast=False)
    hwsim_utils.test_connectivity(dev[0], hapd, success_expected=False)
    hwsim_utils.test_connectivity(dev[0], hapd, success_expected=False)
示例#4
0
def test_ap_pmf_assoc_comeback(dev, apdev):
    """WPA2-PSK AP with PMF association comeback"""
    ssid = "assoc-comeback"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    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")
    hapd.set("ext_mgmt_frame_handling", "1")
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected(timeout=10)
    hapd.set("ext_mgmt_frame_handling", "0")
    dev[0].request("REASSOCIATE")
    dev[0].wait_connected(timeout=10, error="Timeout on re-connection")
    if wt.get_sta_counter("assocresp_comeback", apdev[0]['bssid'],
                          dev[0].p2p_interface_addr()) < 1:
        raise Exception("AP did not use association comeback request")
示例#5
0
def test_ap_pmf_optional_2akm(dev, apdev):
    """WPA2-PSK AP with PMF optional (2 AKMs)"""
    ssid = "test-pmf-optional-2akm"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK WPA-PSK-SHA256"
    params["ieee80211w"] = "1"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    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")
    hwsim_utils.test_connectivity(dev[0], hapd)
    dev[1].connect(ssid,
                   psk="12345678",
                   ieee80211w="2",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")
    hwsim_utils.test_connectivity(dev[1], hapd)
    wt.require_ap_pmf_optional(apdev[0]['bssid'])
    wt.require_sta_pmf(apdev[0]['bssid'], dev[0].p2p_interface_addr())
    wt.require_sta_key_mgmt(apdev[0]['bssid'], dev[0].p2p_interface_addr(),
                            "PSK-SHA256")
    wt.require_sta_pmf_mandatory(apdev[0]['bssid'],
                                 dev[1].p2p_interface_addr())
    wt.require_sta_key_mgmt(apdev[0]['bssid'], dev[1].p2p_interface_addr(),
                            "PSK-SHA256")
示例#6
0
def run_ap_pmf_valid(dev, apdev, disassociate, broadcast):
    ssid = "pmf"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    hapd = hostapd.add_ap(apdev[0], params)
    bssid = hapd.own_addr()
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    dev[0].connect(ssid, psk="12345678", ieee80211w="2",
                   key_mgmt="WPA-PSK-SHA256", proto="WPA2", scan_freq="2412")
    addr0 = dev[0].own_addr()
    dev[0].dump_monitor()
    hapd.wait_sta()
    cmd = "DISASSOCIATE " if disassociate else "DEAUTHENTICATE "
    cmd += "ff:ff:ff:ff:ff:ff" if broadcast else addr0
    cmd += " test=1"
    if "OK" not in hapd.request(cmd):
        raise Exception("hostapd command failed")
    sta = hapd.get_sta(addr0)
    if not sta:
        raise Exception("STA entry lost")
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=5)
    if ev is None:
        raise Exception("Disconnection not reported")
    if "locally_generated=1" in ev:
        raise Exception("Unexpected locally generated disconnection")

    # Wait for SA Query procedure to fail and association comeback to succeed
    dev[0].wait_connected()
示例#7
0
def test_ocv_sa_query_csa(dev, apdev):
    """Test SA Query with OCV after channel switch"""
    ssid = "test-pmf-required"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    params["ocv"] = "1"
    try:
        hapd = hostapd.add_ap(apdev[0], params)
    except Exception as e:
        if "Failed to set hostapd parameter ocv" in str(e):
            raise HwsimSkip("OCV not supported")
        raise
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    dev[0].connect(ssid, psk="12345678", ieee80211w="1", ocv="1",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256", proto="WPA2",
                   scan_freq="2412")

    hapd.request("CHAN_SWITCH 5 2437")
    time.sleep(1)
    if wt.get_sta_counter("valid_saqueryreq_tx", apdev[0]['bssid'],
                          dev[0].own_addr()) < 1:
        raise Exception("STA did not start SA Query after channel switch")
示例#8
0
def test_peerkey_pairwise_mismatch(dev, apdev):
    """RSN TKIP+CCMP AP and PeerKey between two STAs using different ciphers"""
    skip_with_fips(dev[0])
    ssid = "test-peerkey"
    passphrase = "12345678"
    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
    params['peerkey'] = "1"
    params['rsn_pairwise'] = "TKIP CCMP"
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True,
                   pairwise="CCMP")
    dev[1].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True,
                   pairwise="TKIP")
    hwsim_utils.test_connectivity_sta(dev[0], dev[1])

    dev[0].request("STKSTART " + dev[1].p2p_interface_addr())
    time.sleep(0.5)
    dev[1].request("STKSTART " + dev[0].p2p_interface_addr())
    time.sleep(0.5)
示例#9
0
def test_ap_wpa2_delayed_m1_m3_zero_tk(dev, apdev):
    """Delayed M1+M3 retransmission and zero TK"""
    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")

    hwsim_utils.test_connectivity(dev[0], hapd)
    addr = dev[0].own_addr()
    if "OK" not in hapd.request("RESEND_M1 " + addr + " change-anonce"):
        raise Exception("RESEND_M1 failed")
    if "OK" not in hapd.request("RESEND_M1 " + addr):
        raise Exception("RESEND_M1 failed")
    if "OK" not in hapd.request("RESEND_M3 " + addr):
        raise Exception("RESEND_M3 failed")

    if "OK" not in hapd.request("SET_KEY 3 %s %d %d %s %s" % (addr, 0, 1, 6*"00", 16*"00")):
        raise Exception("SET_KEY failed")
    time.sleep(0.1)
    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1, broadcast=False,
                                  success_expected=False)
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()
示例#10
0
def test_ap_pmf_sta_sa_query_no_response_hostapd(dev, apdev):
    """WPA2-PSK AP with station using SA Query and getting no response (hostapd)"""
    ssid = "assoc-comeback"
    passphrase = "12345678"
    addr = dev[0].own_addr()

    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase,
                                 wpa_key_mgmt="WPA-PSK-SHA256",
                                 ieee80211w="2")
    hapd = hostapd.add_ap(apdev[0], params)
    bssid = hapd.own_addr()

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect(ssid, psk=passphrase, ieee80211w="2",
                   key_mgmt="WPA-PSK-SHA256", proto="WPA2",
                   scan_freq="2412")
    hapd.wait_sta()
    hapd.set("ext_mgmt_frame_handling", "1")
    if "OK" not in hapd.request("DEAUTHENTICATE " + addr + " reason=6 test=0") or \
       "OK" not in hapd.request("DISASSOCIATE " + addr + " reason=7 test=0"):
        raise Exception("Failed to send unprotected disconnection messages")
    dev[0].wait_disconnected()
    hapd.set("ext_mgmt_frame_handling", "0")
    if wt.get_sta_counter("valid_saqueryreq_tx", bssid, addr) < 1:
        raise Exception("STA did not send SA Query")
    if wt.get_sta_counter("valid_saqueryresp_rx", bssid, addr) > 0:
        raise Exception("AP replied to SA Query")
    dev[0].wait_connected()
示例#11
0
def run_ap_pmf_beacon_protection_mismatch(dev, apdev, clear):
    ssid = "test-beacon-prot"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    params["beacon_prot"] = "1"
    params["group_mgmt_cipher"] = "AES-128-CMAC"
    try:
        hapd = hostapd.add_ap(apdev[0], params)
    except Exception as e:
        if "Failed to enable hostapd interface" in str(e):
            raise HwsimSkip("Beacon protection not supported")
        raise

    bssid = hapd.own_addr()

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect(ssid,
                   psk="12345678",
                   ieee80211w="2",
                   beacon_prot="1",
                   key_mgmt="WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")

    WPA_ALG_NONE = 0
    WPA_ALG_IGTK = 4
    KEY_FLAG_DEFAULT = 0x02
    KEY_FLAG_TX = 0x08
    KEY_FLAG_GROUP = 0x10
    KEY_FLAG_GROUP_TX_DEFAULT = KEY_FLAG_GROUP | KEY_FLAG_TX | KEY_FLAG_DEFAULT

    addr = "ff:ff:ff:ff:ff:ff"

    if clear:
        res = hapd.request(
            "SET_KEY %d %s %d %d %s %s %d" %
            (WPA_ALG_NONE, addr, 6, 1, 6 * "00", "", KEY_FLAG_GROUP))
    else:
        res = hapd.request("SET_KEY %d %s %d %d %s %s %d" %
                           (WPA_ALG_IGTK, addr, 6, 1, 6 * "00", 16 * "00",
                            KEY_FLAG_GROUP_TX_DEFAULT))
    if "OK" not in res:
        raise Exception("SET_KEY failed")

    ev = dev[0].wait_event(["CTRL-EVENT-UNPROT-BEACON"], timeout=5)
    if ev is None:
        raise Exception("Unprotected Beacon frame not reported")

    ev = dev[0].wait_event(["CTRL-EVENT-BEACON-LOSS"], timeout=5)
    if ev is None:
        raise Exception("Beacon loss not reported")

    ev = hapd.wait_event(["CTRL-EVENT-UNPROT-BEACON"], timeout=5)
    if ev is None:
        raise Exception("WNM-Notification Request frame not reported")
示例#12
0
def check_group_mgmt_cipher(dev, ap, cipher, sta_req_cipher=None):
    if cipher not in dev.get_capability("group_mgmt"):
        raise HwsimSkip("Cipher %s not supported" % cipher)
    params = { "ssid": "test-wpa2-psk-pmf",
               "wpa_passphrase": "12345678",
               "wpa": "2",
               "ieee80211w": "2",
               "wpa_key_mgmt": "WPA-PSK-SHA256",
               "rsn_pairwise": "CCMP",
               "group_mgmt_cipher": cipher }
    hapd = hostapd.add_ap(ap, params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev.connect("test-wpa2-psk-pmf", psk="12345678", ieee80211w="2",
                key_mgmt="WPA-PSK-SHA256", group_mgmt=sta_req_cipher,
                pairwise="CCMP", group="CCMP", scan_freq="2412")
    hwsim_utils.test_connectivity(dev, hapd)
    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff")
    dev.wait_disconnected()
    if wt.get_bss_counter('valid_bip_mmie', ap['bssid']) < 1:
        raise Exception("No valid BIP MMIE seen")
    if wt.get_bss_counter('bip_deauth', ap['bssid']) < 1:
        raise Exception("No valid BIP deauth seen")

    if cipher == "AES-128-CMAC":
        group_mgmt = "BIP"
    else:
        group_mgmt = cipher
    res =  wt.info_bss('group_mgmt', ap['bssid']).strip()
    if res != group_mgmt:
        raise Exception("Unexpected group mgmt cipher: " + res)
示例#13
0
def test_ap_pmf_optional_2akm(dev, apdev):
    """WPA2-PSK AP with PMF optional (2 AKMs)"""
    ssid = "test-pmf-optional-2akm"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK WPA-PSK-SHA256"
    params["ieee80211w"] = "1"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    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")
    hwsim_utils.test_connectivity(dev[0], hapd)
    dev[1].connect(ssid, psk="12345678", ieee80211w="2",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256", proto="WPA2",
                   scan_freq="2412")
    hwsim_utils.test_connectivity(dev[1], hapd)
    wt.require_ap_pmf_optional(apdev[0]['bssid'])
    wt.require_sta_pmf(apdev[0]['bssid'], dev[0].p2p_interface_addr())
    wt.require_sta_key_mgmt(apdev[0]['bssid'], dev[0].p2p_interface_addr(),
                            "PSK-SHA256")
    wt.require_sta_pmf_mandatory(apdev[0]['bssid'], dev[1].p2p_interface_addr())
    wt.require_sta_key_mgmt(apdev[0]['bssid'], dev[1].p2p_interface_addr(),
                            "PSK-SHA256")
示例#14
0
def test_peerkey_pairwise_mismatch(dev, apdev):
    """RSN TKIP+CCMP AP and PeerKey between two STAs using different ciphers"""
    skip_with_fips(dev[0])
    ssid = "test-peerkey"
    passphrase = "12345678"
    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
    params['peerkey'] = "1"
    params['rsn_pairwise'] = "TKIP CCMP"
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True,
                   pairwise="CCMP")
    dev[1].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True,
                   pairwise="TKIP")
    hwsim_utils.test_connectivity_sta(dev[0], dev[1])

    dev[0].request("STKSTART " + dev[1].p2p_interface_addr())
    time.sleep(0.5)
    dev[1].request("STKSTART " + dev[0].p2p_interface_addr())
    time.sleep(0.5)
示例#15
0
def test_ap_wpa2_delayed_m1_m3_zero_tk(dev, apdev):
    """Delayed M1+M3 retransmission and zero TK"""
    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")

    hwsim_utils.test_connectivity(dev[0], hapd)
    addr = dev[0].own_addr()
    if "OK" not in hapd.request("RESEND_M1 " + addr + " change-anonce"):
        raise Exception("RESEND_M1 failed")
    if "OK" not in hapd.request("RESEND_M1 " + addr):
        raise Exception("RESEND_M1 failed")
    if "OK" not in hapd.request("RESEND_M3 " + addr):
        raise Exception("RESEND_M3 failed")

    if "OK" not in hapd.request("SET_KEY 3 %s %d %d %s %s" % (addr, 0, 1, 6*"00", 16*"00")):
        raise Exception("SET_KEY failed")
    time.sleep(0.1)
    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1, broadcast=False,
                                  success_expected=False)
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()
示例#16
0
def test_ocv_sa_query(dev, apdev):
    """Test SA Query with OCV"""
    ssid = "test-pmf-required"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    params["ocv"] = "1"
    try:
        hapd = hostapd.add_ap(apdev[0], params)
    except Exception as e:
        if "Failed to set hostapd parameter ocv" in str(e):
            raise HwsimSkip("OCV not supported")
        raise
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    dev[0].connect(ssid, psk="12345678", ieee80211w="1", ocv="1",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256", proto="WPA2",
                   scan_freq="2412")

    # Test that client can handle SA Query with OCI element
    if "OK" not in hapd.request("SA_QUERY " + dev[0].own_addr()):
        raise Exception("SA_QUERY failed")
    time.sleep(0.1)
    if wt.get_sta_counter("valid_saqueryresp_tx", apdev[0]['bssid'],
                          dev[0].own_addr()) < 1:
        raise Exception("STA did not reply to SA Query")

    # Test that AP can handle SA Query with OCI element
    if "OK" not in dev[0].request("UNPROT_DEAUTH"):
        raise Exception("Triggering SA Query from the STA failed")
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=3)
    if ev is not None:
        raise Exception("SA Query from the STA failed")
示例#17
0
def test_ocv_sa_query_csa(dev, apdev):
    """Test SA Query with OCV after channel switch"""
    ssid = "test-pmf-required"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    params["ocv"] = "1"
    try:
        hapd = hostapd.add_ap(apdev[0], params)
    except Exception as e:
        if "Failed to set hostapd parameter ocv" in str(e):
            raise HwsimSkip("OCV not supported")
        raise
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    dev[0].connect(ssid,
                   psk="12345678",
                   ieee80211w="1",
                   ocv="1",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")

    hapd.request("CHAN_SWITCH 5 2437")
    time.sleep(1)
    if wt.get_sta_counter("valid_saqueryreq_tx", apdev[0]['bssid'],
                          dev[0].own_addr()) < 1:
        raise Exception("STA did not start SA Query after channel switch")
示例#18
0
def check_group_mgmt_cipher(dev, ap, cipher, sta_req_cipher=None):
    if cipher not in dev.get_capability("group_mgmt"):
        raise HwsimSkip("Cipher %s not supported" % cipher)
    params = { "ssid": "test-wpa2-psk-pmf",
               "wpa_passphrase": "12345678",
               "wpa": "2",
               "ieee80211w": "2",
               "wpa_key_mgmt": "WPA-PSK-SHA256",
               "rsn_pairwise": "CCMP",
               "group_mgmt_cipher": cipher }
    hapd = hostapd.add_ap(ap, params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev.connect("test-wpa2-psk-pmf", psk="12345678", ieee80211w="2",
                key_mgmt="WPA-PSK-SHA256", group_mgmt=sta_req_cipher,
                pairwise="CCMP", group="CCMP", scan_freq="2412")
    hwsim_utils.test_connectivity(dev, hapd)
    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff")
    dev.wait_disconnected()
    if wt.get_bss_counter('valid_bip_mmie', ap['bssid']) < 1:
        raise Exception("No valid BIP MMIE seen")
    if wt.get_bss_counter('bip_deauth', ap['bssid']) < 1:
        raise Exception("No valid BIP deauth seen")

    if cipher == "AES-128-CMAC":
        group_mgmt = "BIP"
    else:
        group_mgmt = cipher
    res =  wt.info_bss('group_mgmt', ap['bssid']).strip()
    if res != group_mgmt:
        raise Exception("Unexpected group mgmt cipher: " + res)
示例#19
0
def test_ap_pmf_sta_unprot_deauth_burst_hostapd(dev, apdev):
    """WPA2-PSK AP with station receiving burst of unprotected Deauthentication frames (hostapd)"""
    ssid = "deauth-attack"
    passphrase = "12345678"
    addr = dev[0].own_addr()

    params = hostapd.wpa2_params(ssid=ssid,
                                 passphrase=passphrase,
                                 wpa_key_mgmt="WPA-PSK-SHA256",
                                 ieee80211w="2")
    hapd = hostapd.add_ap(apdev[0], params)
    bssid = hapd.own_addr()

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect(ssid,
                   psk=passphrase,
                   ieee80211w="2",
                   key_mgmt="WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")
    hapd.wait_sta()
    for i in range(10):
        if "OK" not in hapd.request("DEAUTHENTICATE " + addr + " reason=6 test=0") or \
           "OK" not in hapd.request("DISASSOCIATE " + addr + " reason=7 test=0"):
            raise Exception(
                "Failed to send unprotected disconnection messages")
    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(5):
        if "OK" not in hapd.request("DEAUTHENTICATE " + addr + " reason=6 test=0") or \
           "OK" not in hapd.request("DISASSOCIATE " + addr + " reason=7 test=0"):
            raise Exception(
                "Failed to send unprotected disconnection messages")
    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))
示例#20
0
def run_ap_wpa2_delayed_m1_m3_retransmission(dev,
                                             apdev,
                                             change_m1_anonce=False):
    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    phy = dev[0].get_driver_status_field("phyname")
    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")
    hapd.wait_sta()

    for i in range(5):
        hwsim_utils.test_connectivity(dev[0], hapd)

    time.sleep(0.1)
    before_tk = get_rx_spec(phy, gtk=False).splitlines()
    before_gtk = get_rx_spec(phy, gtk=True).splitlines()
    addr = dev[0].own_addr()
    if change_m1_anonce:
        if "OK" not in hapd.request("RESEND_M1 " + addr + " change-anonce"):
            raise Exception("RESEND_M1 failed")
    if "OK" not in hapd.request("RESEND_M1 " + addr):
        raise Exception("RESEND_M1 failed")
    if "OK" not in hapd.request("RESEND_M3 " + addr):
        raise Exception("RESEND_M3 failed")
    time.sleep(0.1)
    after_tk = get_rx_spec(phy, gtk=False).splitlines()
    after_gtk = get_rx_spec(phy, gtk=True).splitlines()

    if "OK" not in hapd.request("RESET_PN " + addr):
        raise Exception("RESET_PN failed")
    time.sleep(0.1)
    hwsim_utils.test_connectivity(dev[0],
                                  hapd,
                                  timeout=1,
                                  success_expected=False)
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()

    for i in range(len(before_tk)):
        b = int(before_tk[i], 16)
        a = int(after_tk[i], 16)
        if a < b:
            raise Exception(
                "TK RX counter decreased: idx=%d before=%d after=%d" %
                (i, b, a))

    for i in range(len(before_gtk)):
        b = int(before_gtk[i], 16)
        a = int(after_gtk[i], 16)
        if a < b:
            raise Exception(
                "GTK RX counter decreased: idx=%d before=%d after=%d" %
                (i, b, a))
示例#21
0
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))
示例#22
0
def test_ap_pmf_sta_sa_query(dev, apdev):
    """WPA2-PSK AP with station using SA Query"""
    ssid = "assoc-comeback"
    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()
    wpas.dump_monitor()

    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")
    wpas.dump_monitor()
    wpas.request("DEAUTHENTICATE " + addr + " test=0")
    wpas.dump_monitor()
    wpas.request("DISASSOCIATE " + addr + " test=0")
    wpas.dump_monitor()
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    wpas.request("DEAUTHENTICATE " + addr + " reason=6 test=0")
    wpas.dump_monitor()
    wpas.request("DISASSOCIATE " + addr + " reason=7 test=0")
    wpas.dump_monitor()
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")
    if wt.get_sta_counter("valid_saqueryreq_tx", bssid, addr) < 1:
        raise Exception("STA did not send SA Query")
    if wt.get_sta_counter("valid_saqueryresp_rx", bssid, addr) < 1:
        raise Exception("AP did not reply to SA Query")
    wpas.dump_monitor()
示例#23
0
def test_autogo_tdls(dev):
    """P2P autonomous GO and two clients using TDLS"""
    go = dev[0]
    logger.info("Start autonomous GO with fixed parameters " + go.ifname)
    id = go.add_network()
    go.set_network_quoted(id, "ssid", "DIRECT-tdls")
    go.set_network_quoted(id, "psk", "12345678")
    go.set_network(id, "mode", "3")
    go.set_network(id, "disabled", "2")
    res = go.p2p_start_go(persistent=id, freq="2462")
    logger.debug("res: " + str(res))
    Wlantest.setup(go, True)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    connect_cli(go, dev[1], social=True, freq=2462)
    connect_cli(go, dev[2], social=True, freq=2462)
    hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
    bssid = dev[0].p2p_interface_addr()
    addr1 = dev[1].p2p_interface_addr()
    addr2 = dev[2].p2p_interface_addr()
    dev[1].tdls_setup(addr2)
    time.sleep(1)
    hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
    conf = wt.get_tdls_counter("setup_conf_ok", bssid, addr1, addr2)
    if conf == 0:
        raise Exception("No TDLS Setup Confirm (success) seen")
    dl = wt.get_tdls_counter("valid_direct_link", bssid, addr1, addr2)
    if dl == 0:
        raise Exception("No valid frames through direct link")
    wt.tdls_clear(bssid, addr1, addr2)
    dev[1].tdls_teardown(addr2)
    time.sleep(1)
    teardown = wt.get_tdls_counter("teardown", bssid, addr1, addr2)
    if teardown == 0:
        raise Exception("No TDLS Setup Teardown seen")
    wt.tdls_clear(bssid, addr1, addr2)
    hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
    ap_path = wt.get_tdls_counter("valid_ap_path", bssid, addr1, addr2)
    if ap_path == 0:
        raise Exception("No valid frames via AP path")
    direct_link = wt.get_tdls_counter("valid_direct_link", bssid, addr1, addr2)
    if direct_link > 0:
        raise Exception("Unexpected frames through direct link")
    idirect_link = wt.get_tdls_counter("invalid_direct_link", bssid, addr1,
                                       addr2)
    if idirect_link > 0:
        raise Exception("Unexpected frames through direct link (invalid)")
    dev[2].remove_group()
    dev[1].remove_group()
    dev[0].remove_group()
示例#24
0
def test_autogo_tdls(dev):
    """P2P autonomous GO and two clients using TDLS"""
    go = dev[0]
    logger.info("Start autonomous GO with fixed parameters " + go.ifname)
    id = go.add_network()
    go.set_network_quoted(id, "ssid", "DIRECT-tdls")
    go.set_network_quoted(id, "psk", "12345678")
    go.set_network(id, "mode", "3")
    go.set_network(id, "disabled", "2")
    res = go.p2p_start_go(persistent=id, freq="2462")
    logger.debug("res: " + str(res))
    Wlantest.setup(go, True)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    connect_cli(go, dev[1], social=True, freq=2462)
    connect_cli(go, dev[2], social=True, freq=2462)
    hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
    bssid = dev[0].p2p_interface_addr()
    addr1 = dev[1].p2p_interface_addr()
    addr2 = dev[2].p2p_interface_addr()
    dev[1].tdls_setup(addr2)
    time.sleep(1)
    hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
    conf = wt.get_tdls_counter("setup_conf_ok", bssid, addr1, addr2)
    if conf == 0:
        raise Exception("No TDLS Setup Confirm (success) seen")
    dl = wt.get_tdls_counter("valid_direct_link", bssid, addr1, addr2)
    if dl == 0:
        raise Exception("No valid frames through direct link")
    wt.tdls_clear(bssid, addr1, addr2)
    dev[1].tdls_teardown(addr2)
    time.sleep(1)
    teardown = wt.get_tdls_counter("teardown", bssid, addr1, addr2)
    if teardown == 0:
        raise Exception("No TDLS Setup Teardown seen")
    wt.tdls_clear(bssid, addr1, addr2)
    hwsim_utils.test_connectivity_p2p(dev[1], dev[2])
    ap_path = wt.get_tdls_counter("valid_ap_path", bssid, addr1, addr2)
    if ap_path == 0:
        raise Exception("No valid frames via AP path")
    direct_link = wt.get_tdls_counter("valid_direct_link", bssid, addr1, addr2)
    if direct_link > 0:
        raise Exception("Unexpected frames through direct link")
    idirect_link = wt.get_tdls_counter("invalid_direct_link", bssid, addr1,
                                       addr2)
    if idirect_link > 0:
        raise Exception("Unexpected frames through direct link (invalid)")
    dev[2].remove_group()
    dev[1].remove_group()
    dev[0].remove_group()
示例#25
0
def run_ap_pmf_beacon_protection(dev, apdev, cipher):
    ssid = "test-beacon-prot"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    params["beacon_prot"] = "1"
    params["group_mgmt_cipher"] = cipher
    try:
        hapd = hostapd.add_ap(apdev[0], params)
    except Exception as e:
        if "Failed to enable hostapd interface" in str(e):
            raise HwsimSkip("Beacon protection not supported")
        raise

    bssid = hapd.own_addr()

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    # STA with Beacon protection enabled
    dev[0].connect(ssid,
                   psk="12345678",
                   ieee80211w="2",
                   beacon_prot="1",
                   key_mgmt="WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")

    # STA with Beacon protection disabled
    dev[1].connect(ssid,
                   psk="12345678",
                   ieee80211w="2",
                   key_mgmt="WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")

    time.sleep(1)
    check_mac80211_bigtk(dev[0], hapd)

    valid_bip = wt.get_bss_counter('valid_bip_mmie', bssid)
    invalid_bip = wt.get_bss_counter('invalid_bip_mmie', bssid)
    missing_bip = wt.get_bss_counter('missing_bip_mmie', bssid)
    logger.info("wlantest BIP counters: valid=%d invalid=%d missing=%d" %
                (valid_bip, invalid_bip, missing_bip))
    if valid_bip < 0 or invalid_bip > 0 or missing_bip > 0:
        raise Exception(
            "Unexpected wlantest BIP counters: valid=%d invalid=%d missing=%d"
            % (valid_bip, invalid_bip, missing_bip))
示例#26
0
def run_ap_wpa2_delayed_m1_m3_retransmission(dev, apdev,
                                             change_m1_anonce=False):
    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    phy = dev[0].get_driver_status_field("phyname")
    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")

    for i in range(5):
        hwsim_utils.test_connectivity(dev[0], hapd)

    time.sleep(0.1)
    before_tk = get_rx_spec(phy, gtk=False).splitlines()
    before_gtk = get_rx_spec(phy, gtk=True).splitlines()
    addr = dev[0].own_addr()
    if change_m1_anonce:
        if "OK" not in hapd.request("RESEND_M1 " + addr + " change-anonce"):
            raise Exception("RESEND_M1 failed")
    if "OK" not in hapd.request("RESEND_M1 " + addr):
        raise Exception("RESEND_M1 failed")
    if "OK" not in hapd.request("RESEND_M3 " + addr):
        raise Exception("RESEND_M3 failed")
    time.sleep(0.1)
    after_tk = get_rx_spec(phy, gtk=False).splitlines()
    after_gtk = get_rx_spec(phy, gtk=True).splitlines()

    if "OK" not in hapd.request("RESET_PN " + addr):
        raise Exception("RESET_PN failed")
    time.sleep(0.1)
    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1,
                                  success_expected=False)
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()

    for i in range(len(before_tk)):
        b = int(before_tk[i], 16)
        a = int(after_tk[i], 16)
        if a < b:
            raise Exception("TK RX counter decreased: idx=%d before=%d after=%d" % (i, b, a))

    for i in range(len(before_gtk)):
        b = int(before_gtk[i], 16)
        a = int(after_gtk[i], 16)
        if a < b:
            raise Exception("GTK RX counter decreased: idx=%d before=%d after=%d" % (i, b, a))
示例#27
0
def test_ap_qosmap_default(dev, apdev):
    """QoS mapping with default values"""
    ssid = "test-qosmap-default"
    params = { "ssid": ssid }
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].p2p_interface_addr()
    dev[0].request("DATA_TEST_CONFIG 1")
    hapd.request("DATA_TEST_CONFIG 1")
    Wlantest.setup(hapd)
    for dscp in [ 0, 7, 8, 15, 16, 23, 24, 31, 32, 39, 40, 47, 48, 55, 56, 63]:
        check_qos_map(apdev[0], hapd, dev[0], addr, dscp, dscp >> 3)
    dev[0].request("DATA_TEST_CONFIG 0")
    hapd.request("DATA_TEST_CONFIG 0")
def test_ap_qosmap_default(dev, apdev):
    """QoS mapping with default values"""
    ssid = "test-qosmap-default"
    params = {"ssid": ssid}
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].p2p_interface_addr()
    dev[0].request("DATA_TEST_CONFIG 1")
    hapd.request("DATA_TEST_CONFIG 1")
    Wlantest.setup(hapd)
    for dscp in [0, 7, 8, 15, 16, 23, 24, 31, 32, 39, 40, 47, 48, 55, 56, 63]:
        check_qos_map(apdev[0], hapd, dev[0], addr, dscp, dscp >> 3)
    dev[0].request("DATA_TEST_CONFIG 0")
    hapd.request("DATA_TEST_CONFIG 0")
示例#29
0
def _test_ap_pmf_toggle(dev, apdev):
    ssid = "test-pmf-optional"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK"
    params["ieee80211w"] = "1"
    params["assoc_sa_query_max_timeout"] = "1"
    params["assoc_sa_query_retry_timeout"] = "1"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    bssid = apdev[0]['bssid']
    addr = dev[0].own_addr()
    dev[0].request("SET reassoc_same_bss_optim 1")
    id = dev[0].connect(ssid,
                        psk="12345678",
                        ieee80211w="1",
                        key_mgmt="WPA-PSK WPA-PSK-SHA256",
                        proto="WPA2",
                        scan_freq="2412")
    wt.require_ap_pmf_optional(bssid)
    wt.require_sta_pmf(bssid, addr)
    sta = hapd.get_sta(addr)
    if '[MFP]' not in sta['flags']:
        raise Exception("MFP flag not present for STA")

    dev[0].set_network(id, "ieee80211w", "0")
    dev[0].request("REASSOCIATE")
    dev[0].wait_connected()
    wt.require_sta_no_pmf(bssid, addr)
    sta = hapd.get_sta(addr)
    if '[MFP]' in sta['flags']:
        raise Exception("MFP flag unexpectedly present for STA")
    err, data = hapd.cmd_execute(
        ['iw', 'dev', apdev[0]['ifname'], 'station', 'get', addr])
    if "yes" in [l for l in data.splitlines() if "MFP" in l][0]:
        raise Exception("Kernel STA entry had MFP enabled")

    dev[0].set_network(id, "ieee80211w", "1")
    dev[0].request("REASSOCIATE")
    dev[0].wait_connected()
    wt.require_sta_pmf(bssid, addr)
    sta = hapd.get_sta(addr)
    if '[MFP]' not in sta['flags']:
        raise Exception("MFP flag not present for STA")
    err, data = hapd.cmd_execute(
        ['iw', 'dev', apdev[0]['ifname'], 'station', 'get', addr])
    if "yes" not in [l for l in data.splitlines() if "MFP" in l][0]:
        raise Exception("Kernel STA entry did not have MFP enabled")
示例#30
0
def test_ap_wpa2_delayed_group_m1_retransmission_igtk(dev, apdev):
    """Delayed group M1 retransmission (check IGTK protection)"""
    params = hostapd.wpa2_params(ssid="test-wpa2-psk",
                                 passphrase="12345678",
                                 ieee80211w="2")
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    phy = dev[0].get_driver_status_field("phyname")
    dev[0].connect("test-wpa2-psk",
                   psk="12345678",
                   scan_freq="2412",
                   ieee80211w="1")
    hapd.wait_sta()

    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1)

    # deauth once to see that works OK
    addr = dev[0].own_addr()
    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff")
    dev[0].wait_disconnected(timeout=10)

    # now to check the protection
    dev[0].request("RECONNECT")
    dev[0].wait_connected()
    hapd.wait_sta()

    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1)

    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr):
        raise Exception("RESEND_GROUP_M1 failed")
    if "OK" not in hapd.request("RESET_PN ff:ff:ff:ff:ff:ff IGTK"):
        raise Exception("RESET_PN failed")

    time.sleep(0.1)
    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff test=1")

    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1)

    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()
示例#31
0
def run_ap_cipher_replay_protection_sta(dev, apdev, cipher, gtk=False):
    params = {
        "ssid": "test-wpa2-psk",
        "wpa_passphrase": "12345678",
        "wpa": "2",
        "wpa_key_mgmt": "WPA-PSK",
        "rsn_pairwise": cipher
    }
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    phy = dev[0].get_driver_status_field("phyname")
    dev[0].connect("test-wpa2-psk",
                   psk="12345678",
                   pairwise=cipher,
                   group=cipher,
                   scan_freq="2412")
    hapd.wait_sta()

    if cipher != "TKIP":
        replays = get_tk_replay_counter(phy, gtk)
        if replays != 0:
            raise Exception("Unexpected replay reported (1)")

    for i in range(5):
        hwsim_utils.test_connectivity(dev[0], hapd)

    if cipher != "TKIP":
        replays = get_tk_replay_counter(phy, gtk)
        if replays != 0:
            raise Exception("Unexpected replay reported (2)")

    addr = "ff:ff:ff:ff:ff:ff" if gtk else dev[0].own_addr()
    if "OK" not in hapd.request("RESET_PN " + addr):
        raise Exception("RESET_PN failed")
    time.sleep(0.1)
    hwsim_utils.test_connectivity(dev[0],
                                  hapd,
                                  timeout=1,
                                  success_expected=False)

    if cipher != "TKIP":
        replays = get_tk_replay_counter(phy, gtk)
        if replays < 1:
            raise Exception("Replays not reported")
示例#32
0
def run_ap_wpa2_igtk_initial_rsc(dev, apdev, cipher):
    if cipher not in dev[0].get_capability("group_mgmt"):
        raise HwsimSkip("Cipher %s not supported" % cipher)

    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
    params["ieee80211w"] = "2"
    params["rsn_pairwise"] = "CCMP"
    params["group_cipher"] = "CCMP"
    params["group_mgmt_cipher"] = cipher
    params["igtk_rsc_override"] = "341200000000"
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect("test-wpa2-psk",
                   psk="12345678",
                   proto="WPA2",
                   ieee80211w="2",
                   pairwise="CCMP",
                   group="CCMP",
                   group_mgmt=cipher,
                   scan_freq="2412")
    hapd.wait_sta()
    # Verify that broadcast robust management frames are dropped.
    dev[0].note(
        "Sending broadcast Deauthentication and Disassociation frames with too small IPN"
    )
    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff test=1")
    hapd.request("DISASSOCIATE ff:ff:ff:ff:ff:ff test=1")
    hapd.request("DEAUTHENTICATE ff:ff:ff:ff:ff:ff test=1")
    hapd.request("DISASSOCIATE ff:ff:ff:ff:ff:ff test=1")
    dev[0].note(
        "Done sending broadcast Deauthentication and Disassociation frames with too small IPN"
    )
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    # Verify thar unicast robust management frames go through.
    hapd.request("DEAUTHENTICATE " + dev[0].own_addr() + " reason=123 test=1")
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is None:
        raise Exception("Disconnection not reported")
    if "reason=123" not in ev:
        raise Exception("Unexpected disconnection reason: " + ev)
示例#33
0
def test_ap_pmf_required(dev, apdev):
    """WPA2-PSK AP with PMF required"""
    ssid = "test-pmf-required"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    key_mgmt = hapd.get_config()['key_mgmt']
    if key_mgmt.split(' ')[0] != "WPA-PSK-SHA256":
        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
    dev[0].connect(ssid,
                   psk="12345678",
                   ieee80211w="1",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")
    if "[WPA2-PSK-SHA256-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")
    hwsim_utils.test_connectivity(dev[0], hapd)
    dev[1].connect(ssid,
                   psk="12345678",
                   ieee80211w="2",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")
    hwsim_utils.test_connectivity(dev[1], hapd)
    if "OK" not in hapd.request("SA_QUERY " + dev[0].own_addr()):
        raise Exception("SA_QUERY failed")
    if "OK" not in hapd.request("SA_QUERY " + dev[1].own_addr()):
        raise Exception("SA_QUERY failed")
    if "FAIL" not in hapd.request("SA_QUERY foo"):
        raise Exception("Invalid SA_QUERY accepted")
    wt.require_ap_pmf_mandatory(apdev[0]['bssid'])
    wt.require_sta_pmf(apdev[0]['bssid'], dev[0].p2p_interface_addr())
    wt.require_sta_pmf_mandatory(apdev[0]['bssid'],
                                 dev[1].p2p_interface_addr())
    time.sleep(0.1)
    if wt.get_sta_counter("valid_saqueryresp_tx", apdev[0]['bssid'],
                          dev[0].p2p_interface_addr()) < 1:
        raise Exception("STA did not reply to SA Query")
    if wt.get_sta_counter("valid_saqueryresp_tx", apdev[0]['bssid'],
                          dev[1].p2p_interface_addr()) < 1:
        raise Exception("STA did not reply to SA Query")
示例#34
0
def _test_ap_pmf_toggle(dev, apdev):
    ssid = "test-pmf-optional"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK"
    params["ieee80211w"] = "1"
    params["assoc_sa_query_max_timeout"] = "1"
    params["assoc_sa_query_retry_timeout"] = "1"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    bssid = apdev[0]['bssid']
    addr = dev[0].own_addr()
    dev[0].request("SET reassoc_same_bss_optim 1")
    id = dev[0].connect(ssid, psk="12345678", ieee80211w="1",
                        key_mgmt="WPA-PSK WPA-PSK-SHA256", proto="WPA2",
                        scan_freq="2412")
    wt.require_ap_pmf_optional(bssid)
    wt.require_sta_pmf(bssid, addr)
    sta = hapd.get_sta(addr)
    if '[MFP]' not in sta['flags']:
        raise Exception("MFP flag not present for STA")

    dev[0].set_network(id, "ieee80211w", "0")
    dev[0].request("REASSOCIATE")
    dev[0].wait_connected()
    wt.require_sta_no_pmf(bssid, addr)
    sta = hapd.get_sta(addr)
    if '[MFP]' in sta['flags']:
        raise Exception("MFP flag unexpectedly present for STA")
    err, data = hapd.cmd_execute(['iw', 'dev', apdev[0]['ifname'], 'station',
                                  'get', addr])
    if "yes" in [l for l in data.splitlines() if "MFP" in l][0]:
        raise Exception("Kernel STA entry had MFP enabled")

    dev[0].set_network(id, "ieee80211w", "1")
    dev[0].request("REASSOCIATE")
    dev[0].wait_connected()
    wt.require_sta_pmf(bssid, addr)
    sta = hapd.get_sta(addr)
    if '[MFP]' not in sta['flags']:
        raise Exception("MFP flag not present for STA")
    err, data = hapd.cmd_execute(['iw', 'dev', apdev[0]['ifname'], 'station',
                                  'get', addr])
    if "yes" not in [l for l in data.splitlines() if "MFP" in l][0]:
        raise Exception("Kernel STA entry did not have MFP enabled")
示例#35
0
def start_ocv_ap(apdev):
    ssid = "test-pmf-required"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    params["ocv"] = "1"
    try:
        hapd = hostapd.add_ap(apdev, params)
    except Exception as e:
        if "Failed to set hostapd parameter ocv" in str(e):
            raise HwsimSkip("OCV not supported")
        raise

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    return hapd, ssid, wt
示例#36
0
def test_peerkey_sniffer_check(dev, apdev, params):
    """RSN AP and PeerKey between two STAs with sniffer check"""
    ssid = "test-peerkey"
    passphrase = "12345678"
    hparams = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
    hparams['peerkey'] = "1"
    hapd = hostapd.add_ap(apdev[0], hparams)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True)
    dev[1].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True)
    hwsim_utils.test_connectivity_sta(dev[0], dev[1])

    dev[0].request("STKSTART " + dev[1].p2p_interface_addr())
    time.sleep(1)
    # NOTE: Actual use of the direct link (DLS) is not supported in
    # mac80211_hwsim, so this operation fails at setting the keys after
    # successfully completed 4-way handshake. This test case does allow the
    # key negotiation part to be tested for coverage, though. Use sniffer to
    # verify that all the SMK and STK handshake messages were transmitted.

    bssid = hapd.own_addr()
    addr0 = dev[0].own_addr()
    addr1 = dev[1].own_addr()

    # Wireshark renamed the EAPOL-Key key_info field, so need to try both the
    # new and the old name to work with both versions.
    try_other = False
    try:
        out = run_tshark(
            os.path.join(params['logdir'], "hwsim0.pcapng"),
            "eapol.type == 3",
            display=["wlan.sa", "wlan.da", "wlan_rsna_eapol.keydes.key_info"])
    except Exception, e:
        if "Unknown tshark field" in str(e):
            try_other = True
            pass
        else:
            raise
示例#37
0
def test_ap_pmf_sta_sa_query_hostapd(dev, apdev):
    """WPA2-PSK AP with station using SA Query (hostapd)"""
    ssid = "assoc-comeback"
    passphrase = "12345678"
    addr = dev[0].own_addr()

    params = hostapd.wpa2_params(ssid=ssid,
                                 passphrase=passphrase,
                                 wpa_key_mgmt="WPA-PSK-SHA256",
                                 ieee80211w="2")
    hapd = hostapd.add_ap(apdev[0], params)
    bssid = hapd.own_addr()

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect(ssid,
                   psk=passphrase,
                   ieee80211w="2",
                   key_mgmt="WPA-PSK-SHA256",
                   proto="WPA2",
                   scan_freq="2412")
    hapd.wait_sta()
    if "OK" not in hapd.request("DEAUTHENTICATE " + addr + " test=0") or \
       "OK" not in hapd.request("DISASSOCIATE " + addr + " test=0"):
        raise Exception("Failed to send unprotected disconnection messages")
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    if "OK" not in hapd.request("DEAUTHENTICATE " + addr + " reason=6 test=0") or \
       "OK" not in hapd.request("DISASSOCIATE " + addr + " reason=7 test=0"):
        raise Exception(
            "Failed to send unprotected disconnection messages (2)")
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")
    if wt.get_sta_counter("valid_saqueryreq_tx", bssid, addr) < 1:
        raise Exception("STA did not send SA Query")
    if wt.get_sta_counter("valid_saqueryresp_rx", bssid, addr) < 1:
        raise Exception("AP did not reply to SA Query")
示例#38
0
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 = start_wpas_ap(ssid)
    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))
示例#39
0
def test_peerkey_sniffer_check(dev, apdev, params):
    """RSN AP and PeerKey between two STAs with sniffer check"""
    ssid = "test-peerkey"
    passphrase = "12345678"
    hparams = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
    hparams['peerkey'] = "1"
    hapd = hostapd.add_ap(apdev[0], hparams)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True)
    dev[1].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True)
    hwsim_utils.test_connectivity_sta(dev[0], dev[1])

    dev[0].request("STKSTART " + dev[1].p2p_interface_addr())
    time.sleep(1)
    # NOTE: Actual use of the direct link (DLS) is not supported in
    # mac80211_hwsim, so this operation fails at setting the keys after
    # successfully completed 4-way handshake. This test case does allow the
    # key negotiation part to be tested for coverage, though. Use sniffer to
    # verify that all the SMK and STK handshake messages were transmitted.

    bssid = hapd.own_addr()
    addr0 = dev[0].own_addr()
    addr1 = dev[1].own_addr()

    # Wireshark renamed the EAPOL-Key key_info field, so need to try both the
    # new and the old name to work with both versions.
    try_other = False
    try:
        out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
                         "eapol.type == 3",
                         display=["wlan.sa", "wlan.da",
                                  "wlan_rsna_eapol.keydes.key_info"])
    except Exception, e:
        if "Unknown tshark field" in str(e):
            try_other = True
            pass
        else:
            raise
示例#40
0
def test_ap_pmf_required_sha1(dev, apdev):
    """WPA2-PSK AP with PMF required with SHA1 AKM"""
    ssid = "test-pmf-required-sha1"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK"
    params["ieee80211w"] = "2"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    key_mgmt = hapd.get_config()['key_mgmt']
    if key_mgmt.split(' ')[0] != "WPA-PSK":
        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
    dev[0].connect(ssid, psk="12345678", ieee80211w="2",
                   key_mgmt="WPA-PSK", proto="WPA2", scan_freq="2412")
    if "[WPA2-PSK-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")
    hwsim_utils.test_connectivity(dev[0], hapd)
def test_ap_qosmap(dev, apdev):
    """QoS mapping"""
    drv_flags = dev[0].get_driver_status_field("capa.flags")
    if int(drv_flags, 0) & 0x40000000 == 0:
        raise HwsimSkip("Driver does not support QoS Map")
    ssid = "test-qosmap"
    params = {"ssid": ssid}
    params[
        'qos_map_set'] = '53,2,22,6,8,15,0,7,255,255,16,31,32,39,255,255,40,47,48,55'
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, key_mgmt="NONE", scan_freq="2412")
    time.sleep(0.1)
    addr = dev[0].p2p_interface_addr()
    dev[0].request("DATA_TEST_CONFIG 1")
    hapd.request("DATA_TEST_CONFIG 1")
    Wlantest.setup(hapd)
    check_qos_map(apdev[0], hapd, dev[0], addr, 53, 2)
    check_qos_map(apdev[0], hapd, dev[0], addr, 22, 6)
    check_qos_map(apdev[0], hapd, dev[0], addr, 8, 0)
    check_qos_map(apdev[0], hapd, dev[0], addr, 15, 0)
    check_qos_map(apdev[0], hapd, dev[0], addr, 0, 1)
    check_qos_map(apdev[0], hapd, dev[0], addr, 7, 1)
    check_qos_map(apdev[0], hapd, dev[0], addr, 16, 3)
    check_qos_map(apdev[0], hapd, dev[0], addr, 31, 3)
    check_qos_map(apdev[0], hapd, dev[0], addr, 32, 4)
    check_qos_map(apdev[0], hapd, dev[0], addr, 39, 4)
    check_qos_map(apdev[0], hapd, dev[0], addr, 40, 6)
    check_qos_map(apdev[0], hapd, dev[0], addr, 47, 6)
    check_qos_map(apdev[0], hapd, dev[0], addr, 48, 7)
    check_qos_map(apdev[0], hapd, dev[0], addr, 55, 7)
    hapd.request(
        "SET_QOS_MAP_SET 22,6,8,15,0,7,255,255,16,31,32,39,255,255,40,47,48,55"
    )
    hapd.request("SEND_QOS_MAP_CONF " + dev[0].get_status_field("address"))
    check_qos_map(apdev[0], hapd, dev[0], addr, 53, 7)
    check_qos_map(apdev[0], hapd, dev[0], addr, 22, 6)
    check_qos_map(apdev[0], hapd, dev[0], addr, 48, 7)
    check_qos_map(apdev[0], hapd, dev[0], addr, 55, 7)
    check_qos_map(apdev[0], hapd, dev[0], addr, 56, 56 >> 3)
    check_qos_map(apdev[0], hapd, dev[0], addr, 63, 63 >> 3)
    dev[0].request("DATA_TEST_CONFIG 0")
    hapd.request("DATA_TEST_CONFIG 0")
示例#42
0
def test_ap_pmf_assoc_comeback2(dev, apdev):
    """WPA2-PSK AP with PMF association comeback (using DROP_SA)"""
    ssid = "assoc-comeback"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK"
    params["ieee80211w"] = "1"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    dev[0].connect(ssid, psk="12345678", ieee80211w="2",
                   key_mgmt="WPA-PSK", proto="WPA2", scan_freq="2412")
    if "OK" not in dev[0].request("DROP_SA"):
        raise Exception("DROP_SA failed")
    dev[0].request("REASSOCIATE")
    dev[0].wait_connected(timeout=10, error="Timeout on re-connection")
    if wt.get_sta_counter("reassocresp_comeback", apdev[0]['bssid'],
                          dev[0].p2p_interface_addr()) < 1:
        raise Exception("AP did not use reassociation comeback request")
示例#43
0
def test_ap_wpa2_plaintext_group_m1(dev, apdev):
    """Plaintext group M1"""
    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect("test-wpa2-psk", psk="12345678", scan_freq="2412")

    time.sleep(0.1)
    addr = dev[0].own_addr()
    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr + " plaintext"):
        raise Exception("RESEND_GROUP_M1 failed")
    time.sleep(0.2)
    if "OK" not in hapd.request("RESEND_GROUP_M1 " + addr):
        raise Exception("RESEND_GROUP_M1 failed")
    time.sleep(0.1)
示例#44
0
def run_ap_cipher_replay_protection_sta(dev, apdev, cipher, gtk=False):
    params = { "ssid": "test-wpa2-psk",
               "wpa_passphrase": "12345678",
               "wpa": "2",
               "wpa_key_mgmt": "WPA-PSK",
               "rsn_pairwise": cipher }
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    phy = dev[0].get_driver_status_field("phyname")
    dev[0].connect("test-wpa2-psk", psk="12345678",
                   pairwise=cipher, group=cipher, scan_freq="2412")

    if cipher != "TKIP":
        replays = get_tk_replay_counter(phy, gtk)
        if replays != 0:
            raise Exception("Unexpected replay reported (1)")

    for i in range(5):
        hwsim_utils.test_connectivity(dev[0], hapd)

    if cipher != "TKIP":
        replays = get_tk_replay_counter(phy, gtk)
        if replays != 0:
            raise Exception("Unexpected replay reported (2)")

    addr = "ff:ff:ff:ff:ff:ff" if gtk else dev[0].own_addr()
    if "OK" not in hapd.request("RESET_PN " + addr):
        raise Exception("RESET_PN failed")
    time.sleep(0.1)
    hwsim_utils.test_connectivity(dev[0], hapd, timeout=1,
                                  success_expected=False)

    if cipher != "TKIP":
        replays = get_tk_replay_counter(phy, gtk)
        if replays < 1:
            raise Exception("Replays not reported")
示例#45
0
def test_ap_pmf_negative(dev, apdev):
    """WPA2-PSK AP without PMF (negative test)"""
    ssid = "test-pmf-negative"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    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")
    hwsim_utils.test_connectivity(dev[0], hapd)
    try:
        dev[1].connect(ssid, psk="12345678", ieee80211w="2",
                       key_mgmt="WPA-PSK WPA-PSK-SHA256", proto="WPA2",
                       scan_freq="2412")
        hwsim_utils.test_connectivity(dev[1], hapd)
        raise Exception("PMF required STA connected to no PMF AP")
    except Exception, e:
        logger.debug("Ignore expected exception: " + str(e))
示例#46
0
文件: test_ap_pmf.py 项目: gxk/hostap
def test_ap_pmf_required(dev, apdev):
    """WPA2-PSK AP with PMF required"""
    ssid = "test-pmf-required"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    key_mgmt = hapd.get_config()['key_mgmt']
    if key_mgmt.split(' ')[0] != "WPA-PSK-SHA256":
        raise Exception("Unexpected GET_CONFIG(key_mgmt): " + key_mgmt)
    dev[0].connect(ssid, psk="12345678", ieee80211w="1",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256", proto="WPA2",
                   scan_freq="2412")
    if "[WPA2-PSK-SHA256-CCMP]" not in dev[0].request("SCAN_RESULTS"):
        raise Exception("Scan results missing RSN element info")
    hwsim_utils.test_connectivity(dev[0], hapd)
    dev[1].connect(ssid, psk="12345678", ieee80211w="2",
                   key_mgmt="WPA-PSK WPA-PSK-SHA256", proto="WPA2",
                   scan_freq="2412")
    hwsim_utils.test_connectivity(dev[1], hapd)
    if "OK" not in hapd.request("SA_QUERY " + dev[0].own_addr()):
        raise Exception("SA_QUERY failed")
    if "OK" not in hapd.request("SA_QUERY " + dev[1].own_addr()):
        raise Exception("SA_QUERY failed")
    if "FAIL" not in hapd.request("SA_QUERY foo"):
        raise Exception("Invalid SA_QUERY accepted")
    wt.require_ap_pmf_mandatory(apdev[0]['bssid'])
    wt.require_sta_pmf(apdev[0]['bssid'], dev[0].p2p_interface_addr())
    wt.require_sta_pmf_mandatory(apdev[0]['bssid'], dev[1].p2p_interface_addr())
    time.sleep(0.1)
    if wt.get_sta_counter("valid_saqueryresp_tx", apdev[0]['bssid'],
                          dev[0].p2p_interface_addr()) < 1:
        raise Exception("STA did not reply to SA Query")
    if wt.get_sta_counter("valid_saqueryresp_tx", apdev[0]['bssid'],
                          dev[1].p2p_interface_addr()) < 1:
        raise Exception("STA did not reply to SA Query")
示例#47
0
def test_ap_qosmap_default_acm(dev, apdev):
    """QoS mapping with default values and ACM=1 for VO/VI"""
    ssid = "test-qosmap-default"
    params = { "ssid": ssid,
               "wmm_ac_bk_aifs": "7",
               "wmm_ac_bk_cwmin": "4",
               "wmm_ac_bk_cwmax": "10",
               "wmm_ac_bk_txop_limit": "0",
               "wmm_ac_bk_acm": "0",
               "wmm_ac_be_aifs": "3",
               "wmm_ac_be_cwmin": "4",
               "wmm_ac_be_cwmax": "10",
               "wmm_ac_be_txop_limit": "0",
               "wmm_ac_be_acm": "0",
               "wmm_ac_vi_aifs": "2",
               "wmm_ac_vi_cwmin": "3",
               "wmm_ac_vi_cwmax": "4",
               "wmm_ac_vi_txop_limit": "94",
               "wmm_ac_vi_acm": "1",
               "wmm_ac_vo_aifs": "2",
               "wmm_ac_vo_cwmin": "2",
               "wmm_ac_vo_cwmax": "2",
               "wmm_ac_vo_txop_limit": "47",
               "wmm_ac_vo_acm": "1"  }
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].p2p_interface_addr()
    dev[0].request("DATA_TEST_CONFIG 1")
    hapd.request("DATA_TEST_CONFIG 1")
    Wlantest.setup(hapd)
    for dscp in [ 0, 7, 8, 15, 16, 23, 24, 31, 32, 39, 40, 47, 48, 55, 56, 63]:
        ap_tid = dscp >> 3
        tid = ap_tid
        # downgrade VI/VO to BE
        if tid in [ 4, 5, 6, 7 ]:
            tid = 3
        check_qos_map(apdev[0], hapd, dev[0], addr, dscp, tid, ap_tid)
    dev[0].request("DATA_TEST_CONFIG 0")
    hapd.request("DATA_TEST_CONFIG 0")
示例#48
0
def test_ap_qosmap(dev, apdev):
    """QoS mapping"""
    drv_flags = dev[0].get_driver_status_field("capa.flags")
    if int(drv_flags, 0) & 0x40000000 == 0:
        raise HwsimSkip("Driver does not support QoS Map")
    ssid = "test-qosmap"
    params = { "ssid": ssid }
    params['qos_map_set'] = '53,2,22,6,8,15,0,7,255,255,16,31,32,39,255,255,40,47,48,55'
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect(ssid, key_mgmt="NONE", scan_freq="2412")
    time.sleep(0.1)
    addr = dev[0].p2p_interface_addr()
    dev[0].request("DATA_TEST_CONFIG 1")
    hapd.request("DATA_TEST_CONFIG 1")
    Wlantest.setup(hapd)
    check_qos_map(apdev[0], hapd, dev[0], addr, 53, 2)
    check_qos_map(apdev[0], hapd, dev[0], addr, 22, 6)
    check_qos_map(apdev[0], hapd, dev[0], addr, 8, 0)
    check_qos_map(apdev[0], hapd, dev[0], addr, 15, 0)
    check_qos_map(apdev[0], hapd, dev[0], addr, 0, 1)
    check_qos_map(apdev[0], hapd, dev[0], addr, 7, 1)
    check_qos_map(apdev[0], hapd, dev[0], addr, 16, 3)
    check_qos_map(apdev[0], hapd, dev[0], addr, 31, 3)
    check_qos_map(apdev[0], hapd, dev[0], addr, 32, 4)
    check_qos_map(apdev[0], hapd, dev[0], addr, 39, 4)
    check_qos_map(apdev[0], hapd, dev[0], addr, 40, 6)
    check_qos_map(apdev[0], hapd, dev[0], addr, 47, 6)
    check_qos_map(apdev[0], hapd, dev[0], addr, 48, 7)
    check_qos_map(apdev[0], hapd, dev[0], addr, 55, 7)
    hapd.request("SET_QOS_MAP_SET 22,6,8,15,0,7,255,255,16,31,32,39,255,255,40,47,48,55")
    hapd.request("SEND_QOS_MAP_CONF " + dev[0].get_status_field("address"))
    check_qos_map(apdev[0], hapd, dev[0], addr, 53, 7)
    check_qos_map(apdev[0], hapd, dev[0], addr, 22, 6)
    check_qos_map(apdev[0], hapd, dev[0], addr, 48, 7)
    check_qos_map(apdev[0], hapd, dev[0], addr, 55, 7)
    check_qos_map(apdev[0], hapd, dev[0], addr, 56, 56 >> 3)
    check_qos_map(apdev[0], hapd, dev[0], addr, 63, 63 >> 3)
    dev[0].request("DATA_TEST_CONFIG 0")
    hapd.request("DATA_TEST_CONFIG 0")
示例#49
0
def test_ap_wpa2_plaintext_m1_m3_pmf(dev, apdev):
    """Plaintext M1/M3 during PTK rekey (PMF)"""
    params = hostapd.wpa2_params(ssid="test-wpa2-psk", passphrase="12345678")
    params["ieee80211w"] = "2"
    hapd = hostapd.add_ap(apdev[0], params)

    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")

    dev[0].connect("test-wpa2-psk", psk="12345678", ieee80211w="2",
                   scan_freq="2412")

    time.sleep(0.1)
    addr = dev[0].own_addr()
    if "OK" not in hapd.request("RESEND_M1 " + addr + " plaintext"):
        raise Exception("RESEND_M1 failed")
    time.sleep(0.1)
    if "OK" not in hapd.request("RESEND_M3 " + addr + " plaintext"):
        raise Exception("RESEND_M3 failed")
    time.sleep(0.1)
示例#50
0
def test_ap_pmf_assoc_comeback(dev, apdev):
    """WPA2-PSK AP with PMF association comeback"""
    ssid = "assoc-comeback"
    params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
    params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
    params["ieee80211w"] = "2"
    hapd = hostapd.add_ap(apdev[0], params)
    Wlantest.setup(hapd)
    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")
    hapd.set("ext_mgmt_frame_handling", "1")
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected(timeout=10)
    hapd.set("ext_mgmt_frame_handling", "0")
    dev[0].request("REASSOCIATE")
    dev[0].wait_connected(timeout=10, error="Timeout on re-connection")
    if wt.get_sta_counter("assocresp_comeback", apdev[0]['bssid'],
                          dev[0].p2p_interface_addr()) < 1:
        raise Exception("AP did not use association comeback request")
示例#51
0
def test_ap_pmf_sta_sa_query(dev, apdev):
    """WPA2-PSK AP with station using SA Query"""
    ssid = "assoc-comeback"
    addr = dev[0].own_addr()

    wpas = start_wpas_ap(ssid)
    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")
    wpas.dump_monitor()
    wpas.request("DEAUTHENTICATE " + addr + " test=0")
    wpas.dump_monitor()
    wpas.request("DISASSOCIATE " + addr + " test=0")
    wpas.dump_monitor()
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")

    wpas.request("DEAUTHENTICATE " + addr + " reason=6 test=0")
    wpas.dump_monitor()
    wpas.request("DISASSOCIATE " + addr + " reason=7 test=0")
    wpas.dump_monitor()
    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=1)
    if ev is not None:
        raise Exception("Unexpected disconnection")
    if wt.get_sta_counter("valid_saqueryreq_tx", bssid, addr) < 1:
        raise Exception("STA did not send SA Query")
    if wt.get_sta_counter("valid_saqueryresp_rx", bssid, addr) < 1:
        raise Exception("AP did not reply to SA Query")
    wpas.dump_monitor()
示例#52
0
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 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 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)
            try:
                if t.__code__.co_argcount > 2:
                    params = {}
                    params['logdir'] = args.logdir
                    params['long'] = args.long
                    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)
                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)
            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)))
示例#53
0
def wlantest_setup(hapd):
    Wlantest.setup(hapd)
    wt = Wlantest()
    wt.flush()
    wt.add_passphrase("12345678")
    wt.add_wepkey("68656c6c6f")
示例#54
0
            try:
                hapd = HostapdGlobal()
            except Exception, 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')):