]> git.ipfire.org Git - thirdparty/hostap.git/blobdiff - tests/hwsim/test_ap_psk.py
tests: Protocol testing for supplicant PMF/IGTK KDE handling
[thirdparty/hostap.git] / tests / hwsim / test_ap_psk.py
index 9cf0c00f5f1db01d27bbd3f94bd0eaf45ea981ee..211acc2cbfdc294a9f86a7b56e03262db2a83eca 100644 (file)
@@ -4,6 +4,7 @@
 # This software may be distributed under the terms of the BSD license.
 # See README for more details.
 
+from remotehost import remote_compatible
 import binascii
 from Crypto.Cipher import AES
 import hashlib
@@ -12,12 +13,13 @@ import logging
 logger = logging.getLogger()
 import os
 import re
+import socket
 import struct
 import subprocess
 import time
 
 import hostapd
-from utils import HwsimSkip, fail_test, skip_with_fips
+from utils import HwsimSkip, fail_test, skip_with_fips, start_monitor, stop_monitor, radiotap_build
 import hwsim_utils
 from wpasupplicant import WpaSupplicant
 
@@ -27,6 +29,7 @@ def check_mib(dev, vals):
         if mib[v[0]] != v[1]:
             raise Exception("Unexpected {} = {} (expected {})".format(v[0], mib[v[0]], v[1]))
 
+@remote_compatible
 def test_ap_wpa2_psk(dev, apdev):
     """WPA2-PSK AP with PSK instead of passphrase"""
     ssid = "test-wpa2-psk"
@@ -68,6 +71,102 @@ def test_ap_wpa2_psk_file(dev, apdev):
         raise Exception("Timed out while waiting for failure report")
     dev[1].request("REMOVE_NETWORK all")
 
+def check_no_keyid(hapd, dev):
+    addr = dev.own_addr()
+    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=1)
+    if ev is None:
+        raise Exception("No AP-STA-CONNECTED indicated")
+    if addr not in ev:
+        raise Exception("AP-STA-CONNECTED for unexpected STA")
+    if "keyid=" in ev:
+        raise Exception("Unexpected keyid indication")
+
+def check_keyid(hapd, dev, keyid):
+    addr = dev.own_addr()
+    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=1)
+    if ev is None:
+        raise Exception("No AP-STA-CONNECTED indicated")
+    if addr not in ev:
+        raise Exception("AP-STA-CONNECTED for unexpected STA")
+    if "keyid=" + keyid not in ev:
+        raise Exception("Incorrect keyid indication")
+    sta = hapd.get_sta(addr)
+    if 'keyid' not in sta or sta['keyid'] != keyid:
+        raise Exception("Incorrect keyid in STA output")
+    dev.request("REMOVE_NETWORK all")
+
+def check_disconnect(dev, expected):
+    for i in range(2):
+        if expected[i]:
+            dev[i].wait_disconnected()
+            dev[i].request("REMOVE_NETWORK all")
+        else:
+            ev = dev[i].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.1)
+            if ev is not None:
+                raise Exception("Unexpected disconnection")
+            dev[i].request("REMOVE_NETWORK all")
+            dev[i].wait_disconnected()
+
+def test_ap_wpa2_psk_file_keyid(dev, apdev, params):
+    """WPA2-PSK AP with PSK from a file (keyid and reload)"""
+    psk_file = os.path.join(params['logdir'], 'ap_wpa2_psk_file_keyid.wpa_psk')
+    with open(psk_file, 'w') as f:
+        f.write('00:00:00:00:00:00 secret passphrase\n')
+        f.write('02:00:00:00:00:00 very secret\n')
+        f.write('00:00:00:00:00:00 another passphrase for all STAs\n')
+    ssid = "test-wpa2-psk"
+    params = hostapd.wpa2_params(ssid=ssid, passphrase='qwertyuiop')
+    params['wpa_psk_file'] = psk_file
+    hapd = hostapd.add_ap(apdev[0], params)
+
+    dev[0].connect(ssid, psk="very secret", scan_freq="2412")
+    check_no_keyid(hapd, dev[0])
+
+    dev[1].connect(ssid, psk="another passphrase for all STAs",
+                   scan_freq="2412")
+    check_no_keyid(hapd, dev[1])
+
+    dev[2].connect(ssid, psk="qwertyuiop", scan_freq="2412")
+    check_no_keyid(hapd, dev[2])
+
+    with open(psk_file, 'w') as f:
+        f.write('00:00:00:00:00:00 secret passphrase\n')
+        f.write('02:00:00:00:00:00 very secret\n')
+        f.write('00:00:00:00:00:00 changed passphrase\n')
+    if "OK" not in hapd.request("RELOAD_WPA_PSK"):
+        raise Exception("RELOAD_WPA_PSK failed")
+
+    check_disconnect(dev, [False, True, False])
+
+    with open(psk_file, 'w') as f:
+        f.write('00:00:00:00:00:00 secret passphrase\n')
+        f.write('keyid=foo 02:00:00:00:00:00 very secret\n')
+        f.write('keyid=bar 00:00:00:00:00:00 another passphrase for all STAs\n')
+    if "OK" not in hapd.request("RELOAD_WPA_PSK"):
+        raise Exception("RELOAD_WPA_PSK failed")
+
+    dev[0].connect(ssid, psk="very secret", scan_freq="2412")
+    check_keyid(hapd, dev[0], "foo")
+
+    dev[1].connect(ssid, psk="another passphrase for all STAs",
+                   scan_freq="2412")
+    check_keyid(hapd, dev[1], "bar")
+
+    dev[2].connect(ssid, psk="qwertyuiop", scan_freq="2412")
+    check_no_keyid(hapd, dev[2])
+
+    dev[0].wait_disconnected()
+    dev[0].connect(ssid, psk="secret passphrase", scan_freq="2412")
+    check_no_keyid(hapd, dev[0])
+
+    with open(psk_file, 'w') as f:
+        f.write('# empty\n')
+    if "OK" not in hapd.request("RELOAD_WPA_PSK"):
+        raise Exception("RELOAD_WPA_PSK failed")
+
+    check_disconnect(dev, [True, True, False])
+
+@remote_compatible
 def test_ap_wpa2_psk_mem(dev, apdev):
     """WPA2-PSK AP with passphrase only in memory"""
     try:
@@ -102,6 +201,7 @@ def _test_ap_wpa2_psk_mem(dev, apdev):
     dev[1].request("CTRL-RSP-PSK_PASSPHRASE-" + id + ':' + psk)
     dev[1].wait_connected(timeout=10)
 
+@remote_compatible
 def test_ap_wpa2_ptk_rekey(dev, apdev):
     """WPA2-PSK AP and PTK rekey enforced by station"""
     ssid = "test-wpa2-psk"
@@ -114,6 +214,26 @@ def test_ap_wpa2_ptk_rekey(dev, apdev):
         raise Exception("PTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
 
+def test_ap_wpa2_ptk_rekey_anonce(dev, apdev):
+    """WPA2-PSK AP and PTK rekey enforced by station and ANonce change"""
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].connect(ssid, psk=passphrase, wpa_ptk_rekey="1", scan_freq="2412")
+    dev[0].dump_monitor()
+    anonce1 = dev[0].request("GET anonce")
+    if "OK" not in dev[0].request("KEY_REQUEST 0 1"):
+        raise Exception("KEY_REQUEST failed")
+    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
+    if ev is None:
+        raise Exception("PTK rekey timed out")
+    anonce2 = dev[0].request("GET anonce")
+    if anonce1 == anonce2:
+        raise Exception("AP did not update ANonce in requested PTK rekeying")
+    hwsim_utils.test_connectivity(dev[0], hapd)
+
+@remote_compatible
 def test_ap_wpa2_ptk_rekey_ap(dev, apdev):
     """WPA2-PSK AP and PTK rekey enforced by AP"""
     ssid = "test-wpa2-psk"
@@ -127,6 +247,7 @@ def test_ap_wpa2_ptk_rekey_ap(dev, apdev):
         raise Exception("PTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
 
+@remote_compatible
 def test_ap_wpa2_sha256_ptk_rekey(dev, apdev):
     """WPA2-PSK/SHA256 AKM AP and PTK rekey enforced by station"""
     ssid = "test-wpa2-psk"
@@ -140,9 +261,10 @@ def test_ap_wpa2_sha256_ptk_rekey(dev, apdev):
     if ev is None:
         raise Exception("PTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
-    check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-6"),
-                        ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-6") ])
+    check_mib(dev[0], [("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-6"),
+                       ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-6")])
 
+@remote_compatible
 def test_ap_wpa2_sha256_ptk_rekey_ap(dev, apdev):
     """WPA2-PSK/SHA256 AKM AP and PTK rekey enforced by AP"""
     ssid = "test-wpa2-psk"
@@ -157,9 +279,10 @@ def test_ap_wpa2_sha256_ptk_rekey_ap(dev, apdev):
     if ev is None:
         raise Exception("PTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
-    check_mib(dev[0], [ ("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-6"),
-                        ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-6") ])
+    check_mib(dev[0], [("dot11RSNAAuthenticationSuiteRequested", "00-0f-ac-6"),
+                       ("dot11RSNAAuthenticationSuiteSelected", "00-0f-ac-6")])
 
+@remote_compatible
 def test_ap_wpa_ptk_rekey(dev, apdev):
     """WPA-PSK/TKIP AP and PTK rekey enforced by station"""
     skip_with_fips(dev[0])
@@ -175,6 +298,7 @@ def test_ap_wpa_ptk_rekey(dev, apdev):
         raise Exception("PTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
 
+@remote_compatible
 def test_ap_wpa_ptk_rekey_ap(dev, apdev):
     """WPA-PSK/TKIP AP and PTK rekey enforced by AP"""
     skip_with_fips(dev[0])
@@ -189,6 +313,7 @@ def test_ap_wpa_ptk_rekey_ap(dev, apdev):
         raise Exception("PTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
 
+@remote_compatible
 def test_ap_wpa_ccmp(dev, apdev):
     """WPA-PSK/CCMP"""
     ssid = "test-wpa-psk"
@@ -198,16 +323,16 @@ def test_ap_wpa_ccmp(dev, apdev):
     hapd = hostapd.add_ap(apdev[0], params)
     dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
     hwsim_utils.test_connectivity(dev[0], hapd)
-    check_mib(dev[0], [ ("dot11RSNAConfigGroupCipherSize", "128"),
-                        ("dot11RSNAGroupCipherRequested", "00-50-f2-4"),
-                        ("dot11RSNAPairwiseCipherRequested", "00-50-f2-4"),
-                        ("dot11RSNAAuthenticationSuiteRequested", "00-50-f2-2"),
-                        ("dot11RSNAGroupCipherSelected", "00-50-f2-4"),
-                        ("dot11RSNAPairwiseCipherSelected", "00-50-f2-4"),
-                        ("dot11RSNAAuthenticationSuiteSelected", "00-50-f2-2"),
-                        ("dot1xSuppSuppControlledPortStatus", "Authorized") ])
-
-def test_ap_wpa2_psk_file(dev, apdev):
+    check_mib(dev[0], [("dot11RSNAConfigGroupCipherSize", "128"),
+                       ("dot11RSNAGroupCipherRequested", "00-50-f2-4"),
+                       ("dot11RSNAPairwiseCipherRequested", "00-50-f2-4"),
+                       ("dot11RSNAAuthenticationSuiteRequested", "00-50-f2-2"),
+                       ("dot11RSNAGroupCipherSelected", "00-50-f2-4"),
+                       ("dot11RSNAPairwiseCipherSelected", "00-50-f2-4"),
+                       ("dot11RSNAAuthenticationSuiteSelected", "00-50-f2-2"),
+                       ("dot1xSuppSuppControlledPortStatus", "Authorized")])
+
+def test_ap_wpa2_psk_file_errors(dev, apdev):
     """WPA2-PSK AP with various PSK file error and success cases"""
     addr0 = dev[0].own_addr()
     addr1 = dev[1].own_addr()
@@ -219,8 +344,8 @@ def test_ap_wpa2_psk_file(dev, apdev):
     except:
         pass
 
-    params = { "ssid": ssid, "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
-               "rsn_pairwise": "CCMP", "wpa_psk_file": pskfile }
+    params = {"ssid": ssid, "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
+              "rsn_pairwise": "CCMP", "wpa_psk_file": pskfile}
 
     try:
         # missing PSK file
@@ -251,6 +376,13 @@ def test_ap_wpa2_psk_file(dev, apdev):
             raise Exception("Unexpected ENABLE success")
         hapd.request("DISABLE")
 
+        # empty token at the end of the line
+        with open(pskfile, "w") as f:
+            f.write("=\n")
+        if "FAIL" not in hapd.request("ENABLE"):
+            raise Exception("Unexpected ENABLE success")
+        hapd.request("DISABLE")
+
         # valid PSK file
         with open(pskfile, "w") as f:
             f.write("00:11:22:33:44:55 12345678\n")
@@ -270,6 +402,7 @@ def test_ap_wpa2_psk_file(dev, apdev):
         except:
             pass
 
+@remote_compatible
 def test_ap_wpa2_psk_wildcard_ssid(dev, apdev):
     """WPA2-PSK AP and wildcard SSID configuration"""
     ssid = "test-wpa2-psk"
@@ -281,6 +414,7 @@ def test_ap_wpa2_psk_wildcard_ssid(dev, apdev):
                    scan_freq="2412")
     dev[1].connect("", bssid=apdev[0]['bssid'], raw_psk=psk, scan_freq="2412")
 
+@remote_compatible
 def test_ap_wpa2_gtk_rekey(dev, apdev):
     """WPA2-PSK AP and GTK rekey enforced by AP"""
     ssid = "test-wpa2-psk"
@@ -294,6 +428,21 @@ def test_ap_wpa2_gtk_rekey(dev, apdev):
         raise Exception("GTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
 
+def test_ap_wpa2_gtk_rekey_request(dev, apdev):
+    """WPA2-PSK AP and GTK rekey by AP request"""
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
+    if "OK" not in hapd.request("REKEY_GTK"):
+        raise Exception("REKEY_GTK failed")
+    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
+    if ev is None:
+        raise Exception("GTK rekey timed out")
+    hwsim_utils.test_connectivity(dev[0], hapd)
+
+@remote_compatible
 def test_ap_wpa_gtk_rekey(dev, apdev):
     """WPA-PSK/TKIP AP and GTK rekey enforced by AP"""
     skip_with_fips(dev[0])
@@ -308,6 +457,7 @@ def test_ap_wpa_gtk_rekey(dev, apdev):
         raise Exception("GTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
 
+@remote_compatible
 def test_ap_wpa2_gmk_rekey(dev, apdev):
     """WPA2-PSK AP and GMK and GTK rekey enforced by AP"""
     ssid = "test-wpa2-psk"
@@ -323,6 +473,7 @@ def test_ap_wpa2_gmk_rekey(dev, apdev):
             raise Exception("GTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
 
+@remote_compatible
 def test_ap_wpa2_strict_rekey(dev, apdev):
     """WPA2-PSK AP and strict GTK rekey enforced by AP"""
     ssid = "test-wpa2-psk"
@@ -338,32 +489,30 @@ def test_ap_wpa2_strict_rekey(dev, apdev):
         raise Exception("GTK rekey timed out")
     hwsim_utils.test_connectivity(dev[0], hapd)
 
+@remote_compatible
 def test_ap_wpa2_bridge_fdb(dev, apdev):
     """Bridge FDB entry removal"""
+    hapd = None
     try:
         ssid = "test-wpa2-psk"
         passphrase = "12345678"
         params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
         params['bridge'] = 'ap-br0'
-        hostapd.add_ap(apdev[0], params)
-        subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
-        subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
+        hapd = hostapd.add_ap(apdev[0], params)
+        hapd.cmd_execute(['brctl', 'setfd', 'ap-br0', '0'])
+        hapd.cmd_execute(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
         dev[0].connect(ssid, psk=passphrase, scan_freq="2412",
                        bssid=apdev[0]['bssid'])
         dev[1].connect(ssid, psk=passphrase, scan_freq="2412",
                        bssid=apdev[0]['bssid'])
         addr0 = dev[0].p2p_interface_addr()
         hwsim_utils.test_connectivity_sta(dev[0], dev[1])
-        cmd = subprocess.Popen(['brctl', 'showmacs', 'ap-br0'],
-                               stdout=subprocess.PIPE)
-        macs1 = cmd.stdout.read()
-        cmd = subprocess.call(['brctl', 'setageing', 'ap-br0', '1'])
+        err, macs1 = hapd.cmd_execute(['brctl', 'showmacs', 'ap-br0'])
+        hapd.cmd_execute(['brctl', 'setageing', 'ap-br0', '1'])
         dev[0].request("DISCONNECT")
         dev[1].request("DISCONNECT")
         time.sleep(1)
-        cmd = subprocess.Popen(['brctl', 'showmacs', 'ap-br0'],
-                               stdout=subprocess.PIPE)
-        macs2 = cmd.stdout.read()
+        err, macs2 = hapd.cmd_execute(['brctl', 'showmacs', 'ap-br0'])
 
         addr1 = dev[1].p2p_interface_addr()
         if addr0 not in macs1 or addr1 not in macs1:
@@ -371,9 +520,11 @@ def test_ap_wpa2_bridge_fdb(dev, apdev):
         if addr0 in macs2 or addr1 in macs2:
             raise Exception("Bridge FDB entry was not removed")
     finally:
-        subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'down'])
-        subprocess.call(['brctl', 'delbr', 'ap-br0'])
+        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', 'ap-br0',
+                                       'down'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', 'ap-br0'])
 
+@remote_compatible
 def test_ap_wpa2_already_in_bridge(dev, apdev):
     """hostapd behavior with interface already in bridge"""
     ifname = apdev[0]['ifname']
@@ -381,22 +532,25 @@ def test_ap_wpa2_already_in_bridge(dev, apdev):
     try:
         ssid = "test-wpa2-psk"
         passphrase = "12345678"
-        subprocess.call(['brctl', 'addbr', br_ifname])
-        subprocess.call(['brctl', 'setfd', br_ifname, '0'])
-        subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
-        subprocess.call(['iw', ifname, 'set', 'type', '__ap'])
-        subprocess.call(['brctl', 'addif', br_ifname, ifname])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'addbr', br_ifname])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', br_ifname, '0'])
+        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
+                                       'up'])
+        hostapd.cmd_execute(apdev[0], ['iw', ifname, 'set', 'type', '__ap'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'addif', br_ifname, ifname])
         params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
         hapd = hostapd.add_ap(apdev[0], params)
         if hapd.get_driver_status_field('brname') != br_ifname:
             raise Exception("Bridge name not identified correctly")
         dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
     finally:
-        subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
-        subprocess.call(['brctl', 'delif', br_ifname, ifname])
-        subprocess.call(['iw', ifname, 'set', 'type', 'station'])
-        subprocess.call(['brctl', 'delbr', br_ifname])
+        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
+                                       'down'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'delif', br_ifname, ifname])
+        hostapd.cmd_execute(apdev[0], ['iw', ifname, 'set', 'type', 'station'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', br_ifname])
 
+@remote_compatible
 def test_ap_wpa2_in_different_bridge(dev, apdev):
     """hostapd behavior with interface in different bridge"""
     ifname = apdev[0]['ifname']
@@ -404,17 +558,19 @@ def test_ap_wpa2_in_different_bridge(dev, apdev):
     try:
         ssid = "test-wpa2-psk"
         passphrase = "12345678"
-        subprocess.call(['brctl', 'addbr', br_ifname])
-        subprocess.call(['brctl', 'setfd', br_ifname, '0'])
-        subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
-        subprocess.call(['iw', ifname, 'set', 'type', '__ap'])
-        subprocess.call(['brctl', 'addif', br_ifname, ifname])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'addbr', br_ifname])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', br_ifname, '0'])
+        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
+                                       'up'])
+        hostapd.cmd_execute(apdev[0], ['iw', ifname, 'set', 'type', '__ap'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'addif', br_ifname, ifname])
         time.sleep(0.5)
         params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
         params['bridge'] = 'ap-br0'
         hapd = hostapd.add_ap(apdev[0], params)
-        subprocess.call(['brctl', 'setfd', 'ap-br0', '0'])
-        subprocess.call(['ip', 'link', 'set', 'dev', 'ap-br0', 'up'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', 'ap-br0', '0'])
+        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', 'ap-br0',
+                                       'up'])
         brname = hapd.get_driver_status_field('brname')
         if brname != 'ap-br0':
             raise Exception("Incorrect bridge: " + brname)
@@ -427,11 +583,13 @@ def test_ap_wpa2_in_different_bridge(dev, apdev):
         dev[0].request("DISCONNECT")
         hapd.disable()
     finally:
-        subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
-        subprocess.call(['brctl', 'delif', br_ifname, ifname],
-                        stderr=open('/dev/null', 'w'))
-        subprocess.call(['brctl', 'delbr', br_ifname])
+        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
+                                       'down'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'delif', br_ifname, ifname,
+                                       "2>", "/dev/null"], shell=True)
+        hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', br_ifname])
 
+@remote_compatible
 def test_ap_wpa2_ext_add_to_bridge(dev, apdev):
     """hostapd behavior with interface added to bridge externally"""
     ifname = apdev[0]['ifname']
@@ -442,58 +600,496 @@ def test_ap_wpa2_ext_add_to_bridge(dev, apdev):
         params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
         hapd = hostapd.add_ap(apdev[0], params)
 
-        subprocess.call(['brctl', 'addbr', br_ifname])
-        subprocess.call(['brctl', 'setfd', br_ifname, '0'])
-        subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'up'])
-        subprocess.call(['brctl', 'addif', br_ifname, ifname])
-        dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
-        if hapd.get_driver_status_field('brname') != br_ifname:
-            raise Exception("Bridge name not identified correctly")
-    finally:
-        subprocess.call(['ip', 'link', 'set', 'dev', br_ifname, 'down'])
-        subprocess.call(['brctl', 'delif', br_ifname, ifname])
-        subprocess.call(['brctl', 'delbr', br_ifname])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'addbr', br_ifname])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'setfd', br_ifname, '0'])
+        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
+                                       'up'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'addif', br_ifname, ifname])
+        dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
+        if hapd.get_driver_status_field('brname') != br_ifname:
+            raise Exception("Bridge name not identified correctly")
+    finally:
+        hostapd.cmd_execute(apdev[0], ['ip', 'link', 'set', 'dev', br_ifname,
+                                       'down'])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'delif', br_ifname, ifname])
+        hostapd.cmd_execute(apdev[0], ['brctl', 'delbr', br_ifname])
+
+def test_ap_wpa2_psk_ext(dev, apdev):
+    """WPA2-PSK AP using external EAPOL I/O"""
+    bssid = apdev[0]['bssid']
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
+    params = hostapd.wpa2_params(ssid=ssid)
+    params['wpa_psk'] = psk
+    hapd = hostapd.add_ap(apdev[0], params)
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
+    addr = dev[0].p2p_interface_addr()
+    while True:
+        ev = hapd.wait_event(["EAPOL-TX", "AP-STA-CONNECTED"], timeout=15)
+        if ev is None:
+            raise Exception("Timeout on EAPOL-TX from hostapd")
+        if "AP-STA-CONNECTED" in ev:
+            dev[0].wait_connected(timeout=15)
+            break
+        res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+        if "OK" not in res:
+            raise Exception("EAPOL_RX to wpa_supplicant failed")
+        ev = dev[0].wait_event(["EAPOL-TX", "CTRL-EVENT-CONNECTED"], timeout=15)
+        if ev is None:
+            raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+        if "CTRL-EVENT-CONNECTED" in ev:
+            break
+        res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+        if "OK" not in res:
+            raise Exception("EAPOL_RX to hostapd failed")
+
+def test_ap_wpa2_psk_ext_retry_msg_3(dev, apdev):
+    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4"""
+    bssid = apdev[0]['bssid']
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
+    params = hostapd.wpa2_params(ssid=ssid)
+    params['wpa_psk'] = psk
+    hapd = hostapd.add_ap(apdev[0], params)
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
+    addr = dev[0].p2p_interface_addr()
+
+    # EAPOL-Key msg 1/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    # EAPOL-Key msg 3/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    # Do not send to the AP
+    dev[0].wait_connected(timeout=15)
+
+    # EAPOL-Key msg 3/4 (retry)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
+
+    hwsim_utils.test_connectivity(dev[0], hapd)
+
+def test_ap_wpa2_psk_ext_retry_msg_3b(dev, apdev):
+    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4 (b)"""
+    bssid = apdev[0]['bssid']
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
+    params = hostapd.wpa2_params(ssid=ssid)
+    params['wpa_psk'] = psk
+    hapd = hostapd.add_ap(apdev[0], params)
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
+    addr = dev[0].p2p_interface_addr()
+
+    # EAPOL-Key msg 1/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    # EAPOL-Key msg 3/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    # Do not send the first msg 3/4 to the STA yet; wait for retransmission
+    # from AP.
+    msg3_1 = ev
+
+    # EAPOL-Key msg 3/4 (retry)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg3_2 = ev
+
+    # Send the first msg 3/4 to STA
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3_1.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+    dev[0].wait_connected(timeout=15)
+    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
+
+    hwsim_utils.test_connectivity(dev[0], hapd)
+
+    # Send the second msg 3/4 to STA
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3_2.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    # Do not send the second msg 4/4 to the AP
+
+    hwsim_utils.test_connectivity(dev[0], hapd)
+
+def test_ap_wpa2_psk_ext_retry_msg_3c(dev, apdev):
+    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4 (c)"""
+    bssid = apdev[0]['bssid']
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
+    params = hostapd.wpa2_params(ssid=ssid)
+    params['wpa_psk'] = psk
+    hapd = hostapd.add_ap(apdev[0], params)
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
+    addr = dev[0].p2p_interface_addr()
+
+    # EAPOL-Key msg 1/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg1 = ev.split(' ')[2]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    # EAPOL-Key msg 3/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    msg4 = ev.split(' ')[2]
+    # Do not send msg 4/4 to hostapd to trigger retry
+
+    # STA believes everything is ready
+    dev[0].wait_connected()
+
+    # EAPOL-Key msg 3/4 (retry)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg3 = ev.split(' ')[2]
+
+    # Send a forged msg 1/4 to STA (update replay counter)
+    msg1b = msg1[0:18] + msg3[18:34] + msg1[34:]
+    # and replace nonce (this results in "WPA: ANonce from message 1 of
+    # 4-Way Handshake differs from 3 of 4-Way Handshake - drop packet" when
+    # wpa_supplicant processed msg 3/4 afterwards)
+    #msg1b = msg1[0:18] + msg3[18:34] + 32*"ff" + msg1[98:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1b)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=1)
+    if ev is None:
+        # wpa_supplicant seems to have ignored the forged message. This means
+        # the attack would fail.
+        logger.info("wpa_supplicant ignored forged EAPOL-Key msg 1/4")
+        return
+    # Do not send msg 2/4 to hostapd
+
+    # Send previously received msg 3/4 to STA
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
+
+    hwsim_utils.test_connectivity(dev[0], hapd)
+
+def test_ap_wpa2_psk_ext_retry_msg_3d(dev, apdev):
+    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4 (d)"""
+    bssid = apdev[0]['bssid']
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
+    params = hostapd.wpa2_params(ssid=ssid)
+    params['wpa_psk'] = psk
+    hapd = hostapd.add_ap(apdev[0], params)
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
+    addr = dev[0].p2p_interface_addr()
+
+    # EAPOL-Key msg 1/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg1 = ev.split(' ')[2]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    # EAPOL-Key msg 3/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    msg4 = ev.split(' ')[2]
+    # Do not send msg 4/4 to hostapd to trigger retry
+
+    # STA believes everything is ready
+    dev[0].wait_connected()
+
+    # EAPOL-Key msg 3/4 (retry)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg3 = ev.split(' ')[2]
+
+    # Send a forged msg 1/4 to STA (update replay counter)
+    msg1b = msg1[0:18] + msg3[18:34] + msg1[34:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1b)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=1)
+    if ev is None:
+        # wpa_supplicant seems to have ignored the forged message. This means
+        # the attack would fail.
+        logger.info("wpa_supplicant ignored forged EAPOL-Key msg 1/4")
+        return
+    # Do not send msg 2/4 to hostapd
+
+    # EAPOL-Key msg 3/4 (retry 2)
+    # New one needed to get the correct Replay Counter value
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg3 = ev.split(' ')[2]
+
+    # Send msg 3/4 to STA
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
+
+    hwsim_utils.test_connectivity(dev[0], hapd)
+
+def test_ap_wpa2_psk_ext_retry_msg_3e(dev, apdev):
+    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4 (e)"""
+    bssid = apdev[0]['bssid']
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
+    params = hostapd.wpa2_params(ssid=ssid)
+    params['wpa_psk'] = psk
+    hapd = hostapd.add_ap(apdev[0], params)
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
+    addr = dev[0].p2p_interface_addr()
+
+    # EAPOL-Key msg 1/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg1 = ev.split(' ')[2]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    # EAPOL-Key msg 3/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    msg4 = ev.split(' ')[2]
+    # Do not send msg 4/4 to hostapd to trigger retry
+
+    # STA believes everything is ready
+    dev[0].wait_connected()
+
+    # EAPOL-Key msg 3/4 (retry)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg3 = ev.split(' ')[2]
+
+    # Send a forged msg 1/4 to STA (update replay counter and replace ANonce)
+    msg1b = msg1[0:18] + msg3[18:34] + 32*"ff" + msg1[98:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1b)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=1)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    # Do not send msg 2/4 to hostapd
+
+    # Send a forged msg 1/4 to STA (back to previously used ANonce)
+    msg1b = msg1[0:18] + msg3[18:34] + msg1[34:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg1b)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=1)
+    if ev is None:
+        # wpa_supplicant seems to have ignored the forged message. This means
+        # the attack would fail.
+        logger.info("wpa_supplicant ignored forged EAPOL-Key msg 1/4")
+        return
+    # Do not send msg 2/4 to hostapd
+
+    # EAPOL-Key msg 3/4 (retry 2)
+    # New one needed to get the correct Replay Counter value
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg3 = ev.split(' ')[2]
+
+    # Send msg 3/4 to STA
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
 
-def test_ap_wpa2_psk_ext(dev, apdev):
-    """WPA2-PSK AP using external EAPOL I/O"""
-    bssid = apdev[0]['bssid']
-    ssid = "test-wpa2-psk"
-    passphrase = 'qwertyuiop'
-    psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
-    params = hostapd.wpa2_params(ssid=ssid)
-    params['wpa_psk'] = psk
-    hapd = hostapd.add_ap(apdev[0], params)
-    hapd.request("SET ext_eapol_frame_io 1")
-    dev[0].request("SET ext_eapol_frame_io 1")
-    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
-    addr = dev[0].p2p_interface_addr()
-    while True:
-        ev = hapd.wait_event(["EAPOL-TX", "AP-STA-CONNECTED"], timeout=15)
-        if ev is None:
-            raise Exception("Timeout on EAPOL-TX from hostapd")
-        if "AP-STA-CONNECTED" in ev:
-            dev[0].wait_connected(timeout=15)
-            break
-        res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
-        if "OK" not in res:
-            raise Exception("EAPOL_RX to wpa_supplicant failed")
-        ev = dev[0].wait_event(["EAPOL-TX", "CTRL-EVENT-CONNECTED"], timeout=15)
-        if ev is None:
-            raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
-        if "CTRL-EVENT-CONNECTED" in ev:
-            break
-        res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
-        if "OK" not in res:
-            raise Exception("EAPOL_RX to hostapd failed")
+    hwsim_utils.test_connectivity(dev[0], hapd)
 
-def test_ap_wpa2_psk_ext_retry_msg_3(dev, apdev):
-    """WPA2-PSK AP using external EAPOL I/O and retry for EAPOL-Key msg 3/4"""
+def test_ap_wpa2_psk_ext_delayed_ptk_rekey(dev, apdev):
+    """WPA2-PSK AP using external EAPOL I/O and delayed PTK rekey exchange"""
     bssid = apdev[0]['bssid']
     ssid = "test-wpa2-psk"
     passphrase = 'qwertyuiop'
     psk = '602e323e077bc63bd80307ef4745b754b0ae0a925c2638ecd13a794b9527b9e6'
     params = hostapd.wpa2_params(ssid=ssid)
     params['wpa_psk'] = psk
+    params['wpa_ptk_rekey'] = '3'
     hapd = hostapd.add_ap(apdev[0], params)
     hapd.request("SET ext_eapol_frame_io 1")
     dev[0].request("SET ext_eapol_frame_io 1")
@@ -508,6 +1104,21 @@ def test_ap_wpa2_psk_ext_retry_msg_3(dev, apdev):
     if "OK" not in res:
         raise Exception("EAPOL_RX to wpa_supplicant failed")
 
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    msg2 = ev.split(' ')[2]
+    # Do not send this to the AP
+
+    # EAPOL-Key msg 1/4 (retry)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
     # EAPOL-Key msg 2/4
     ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
     if ev is None:
@@ -528,8 +1139,8 @@ def test_ap_wpa2_psk_ext_retry_msg_3(dev, apdev):
     ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
     if ev is None:
         raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
-    # Do not send to the AP
-    dev[0].wait_connected(timeout=15)
+    msg4 = ev.split(' ')[2]
+    # Do not send msg 4/4 to AP
 
     # EAPOL-Key msg 3/4 (retry)
     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
@@ -543,7 +1154,11 @@ def test_ap_wpa2_psk_ext_retry_msg_3(dev, apdev):
     ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
     if ev is None:
         raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
-    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    msg4b = ev.split(' ')[2]
+    # Do not send msg 4/4 to AP
+
+    # Send the previous EAPOL-Key msg 4/4 to AP
+    res = hapd.request("EAPOL_RX " + addr + " " + msg4)
     if "OK" not in res:
         raise Exception("EAPOL_RX to hostapd failed")
 
@@ -551,7 +1166,41 @@ def test_ap_wpa2_psk_ext_retry_msg_3(dev, apdev):
     if ev is None:
         raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
 
-    hwsim_utils.test_connectivity(dev[0], hapd)
+    # Wait for PTK rekeying to be initialized
+    # EAPOL-Key msg 1/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+
+    # EAPOL-Key msg 2/4 from the previous 4-way handshake
+    # hostapd is expected to ignore this due to unexpected Replay Counter
+    res = hapd.request("EAPOL_RX " + addr + " " + msg2)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    # EAPOL-Key msg 3/4 (actually, this ends up being retransmitted 1/4)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    keyinfo = ev.split(' ')[2][10:14]
+    if keyinfo != "008a":
+        raise Exception("Unexpected key info when expected msg 1/4:" + keyinfo)
+
+    # EAPOL-Key msg 4/4 from the previous 4-way handshake
+    # hostapd is expected to ignore this due to unexpected Replay Counter
+    res = hapd.request("EAPOL_RX " + addr + " " + msg4b)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+
+    # Check if any more EAPOL-Key frames are seen. If the second 4-way handshake
+    # was accepted, there would be no more EAPOL-Key frames. If the Replay
+    # Counters were rejected, there would be a retransmitted msg 1/4 here.
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=1)
+    if ev is None:
+        raise Exception("Did not see EAPOL-TX from hostapd in the end (expected msg 1/4)")
+    keyinfo = ev.split(' ')[2][10:14]
+    if keyinfo != "008a":
+        raise Exception("Unexpected key info when expected msg 1/4:" + keyinfo)
 
 def parse_eapol(data):
     (version, type, length) = struct.unpack('>BBH', data[0:4])
@@ -604,10 +1253,10 @@ def build_eapol(msg):
     return data
 
 def sha1_prf(key, label, data, outlen):
-    res = ''
+    res = b''
     counter = 0
     while outlen > 0:
-        m = hmac.new(key, label, hashlib.sha1)
+        m = hmac.new(key, label.encode(), hashlib.sha1)
         m.update(struct.pack('B', 0))
         m.update(data)
         m.update(struct.pack('B', counter))
@@ -623,9 +1272,9 @@ def sha1_prf(key, label, data, outlen):
 
 def pmk_to_ptk(pmk, addr1, addr2, nonce1, nonce2):
     if addr1 < addr2:
-        data = binascii.unhexlify(addr1.replace(':','')) + binascii.unhexlify(addr2.replace(':',''))
+        data = binascii.unhexlify(addr1.replace(':', '')) + binascii.unhexlify(addr2.replace(':', ''))
     else:
-        data = binascii.unhexlify(addr2.replace(':','')) + binascii.unhexlify(addr1.replace(':',''))
+        data = binascii.unhexlify(addr2.replace(':', '')) + binascii.unhexlify(addr1.replace(':', ''))
     if nonce1 < nonce2:
         data += nonce1 + nonce2
     else:
@@ -655,7 +1304,7 @@ def rsn_eapol_key_set(msg, key_info, key_len, nonce, data):
         msg['length'] = 95 + len(data)
     else:
         msg['rsn_key_data_len'] = 0
-        msg['rsn_key_data'] = ''
+        msg['rsn_key_data'] = b''
         msg['length'] = 95
 
 def recv_eapol(hapd):
@@ -666,7 +1315,7 @@ def recv_eapol(hapd):
     return parse_eapol(eapol)
 
 def send_eapol(hapd, addr, data):
-    res = hapd.request("EAPOL_RX " + addr + " " + binascii.hexlify(data))
+    res = hapd.request("EAPOL_RX " + addr + " " + binascii.hexlify(data).decode())
     if "OK" not in res:
         raise Exception("EAPOL_RX to hostapd failed")
 
@@ -681,7 +1330,7 @@ def hapd_connected(hapd):
     if ev is None:
         raise Exception("Timeout on AP-STA-CONNECTED from hostapd")
 
-def eapol_test(apdev, dev, wpa2=True):
+def eapol_test(apdev, dev, wpa2=True, ieee80211w=0):
     bssid = apdev['bssid']
     if wpa2:
         ssid = "test-wpa2-psk"
@@ -694,21 +1343,27 @@ def eapol_test(apdev, dev, wpa2=True):
     else:
         params = hostapd.wpa_params(ssid=ssid)
     params['wpa_psk'] = psk
+    params['ieee80211w'] = str(ieee80211w)
     hapd = hostapd.add_ap(apdev, params)
     hapd.request("SET ext_eapol_frame_io 1")
     dev.request("SET ext_eapol_frame_io 1")
-    dev.connect(ssid, raw_psk=psk, scan_freq="2412", wait_connect=False)
+    dev.connect(ssid, raw_psk=psk, scan_freq="2412", wait_connect=False,
+                ieee80211w=str(ieee80211w))
     addr = dev.p2p_interface_addr()
     if wpa2:
-        rsne = binascii.unhexlify('30140100000fac040100000fac040100000fac020000')
+        if ieee80211w == 2:
+            rsne = binascii.unhexlify('30140100000fac040100000fac040100000fac02cc00')
+        else:
+            rsne = binascii.unhexlify('30140100000fac040100000fac040100000fac020000')
     else:
         rsne = binascii.unhexlify('dd160050f20101000050f20201000050f20201000050f202')
     snonce = binascii.unhexlify('1111111111111111111111111111111111111111111111111111111111111111')
-    return (bssid,ssid,hapd,snonce,pmk,addr,rsne)
+    return (bssid, ssid, hapd, snonce, pmk, addr, rsne)
 
+@remote_compatible
 def test_ap_wpa2_psk_ext_eapol(dev, apdev):
     """WPA2-PSK AP using external EAPOL supplicant"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     msg = recv_eapol(hapd)
     anonce = msg['rsn_key_nonce']
@@ -733,9 +1388,10 @@ def test_ap_wpa2_psk_ext_eapol(dev, apdev):
     reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
     hapd_connected(hapd)
 
+@remote_compatible
 def test_ap_wpa2_psk_ext_eapol_retry1(dev, apdev):
     """WPA2 4-way handshake with EAPOL-Key 1/4 retransmitted"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     msg1 = recv_eapol(hapd)
     anonce = msg1['rsn_key_nonce']
@@ -759,9 +1415,10 @@ def test_ap_wpa2_psk_ext_eapol_retry1(dev, apdev):
     reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
     hapd_connected(hapd)
 
+@remote_compatible
 def test_ap_wpa2_psk_ext_eapol_retry1b(dev, apdev):
     """WPA2 4-way handshake with EAPOL-Key 1/4 and 2/4 retransmitted"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     msg1 = recv_eapol(hapd)
     anonce = msg1['rsn_key_nonce']
@@ -780,9 +1437,10 @@ def test_ap_wpa2_psk_ext_eapol_retry1b(dev, apdev):
     reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
     hapd_connected(hapd)
 
+@remote_compatible
 def test_ap_wpa2_psk_ext_eapol_retry1c(dev, apdev):
     """WPA2 4-way handshake with EAPOL-Key 1/4 and 2/4 retransmitted and SNonce changing"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     msg1 = recv_eapol(hapd)
     anonce = msg1['rsn_key_nonce']
@@ -803,9 +1461,10 @@ def test_ap_wpa2_psk_ext_eapol_retry1c(dev, apdev):
     reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
     hapd_connected(hapd)
 
+@remote_compatible
 def test_ap_wpa2_psk_ext_eapol_retry1d(dev, apdev):
     """WPA2 4-way handshake with EAPOL-Key 1/4 and 2/4 retransmitted and SNonce changing and older used"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     msg1 = recv_eapol(hapd)
     anonce = msg1['rsn_key_nonce']
@@ -826,9 +1485,10 @@ def test_ap_wpa2_psk_ext_eapol_retry1d(dev, apdev):
     reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
     hapd_connected(hapd)
 
+@remote_compatible
 def test_ap_wpa2_psk_ext_eapol_type_diff(dev, apdev):
     """WPA2 4-way handshake using external EAPOL supplicant"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     msg = recv_eapol(hapd)
     anonce = msg['rsn_key_nonce']
@@ -856,10 +1516,11 @@ def test_ap_wpa2_psk_ext_eapol_type_diff(dev, apdev):
     reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
     hapd_connected(hapd)
 
+@remote_compatible
 def test_ap_wpa_psk_ext_eapol(dev, apdev):
     """WPA2-PSK AP using external EAPOL supplicant"""
-    (bssid,ssid,hapd,snonce,pmk,addr,wpae) = eapol_test(apdev[0], dev[0],
-                                                        wpa2=False)
+    (bssid, ssid, hapd, snonce, pmk, addr, wpae) = eapol_test(apdev[0], dev[0],
+                                                              wpa2=False)
 
     msg = recv_eapol(hapd)
     anonce = msg['rsn_key_nonce']
@@ -883,9 +1544,10 @@ def test_ap_wpa_psk_ext_eapol(dev, apdev):
     reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
     hapd_connected(hapd)
 
+@remote_compatible
 def test_ap_wpa2_psk_ext_eapol_key_info(dev, apdev):
     """WPA2-PSK 4-way handshake with strange key info values"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     msg = recv_eapol(hapd)
     anonce = msg['rsn_key_nonce']
@@ -928,7 +1590,7 @@ def test_ap_wpa2_psk_ext_eapol_key_info(dev, apdev):
     reply_eapol("4/4", hapd, addr, msg, 0x030a, None, None, kck)
     hapd_connected(hapd)
 
-def build_eapol_key_1_4(anonce, replay_counter=1, key_data='', key_len=16):
+def build_eapol_key_1_4(anonce, replay_counter=1, key_data=b'', key_len=16):
     msg = {}
     msg['version'] = 2
     msg['type'] = 3
@@ -968,7 +1630,7 @@ def build_eapol_key_3_4(anonce, kck, key_data, replay_counter=2,
     return msg
 
 def aes_wrap(kek, plain):
-    n = len(plain) / 8
+    n = len(plain) // 8
     a = 0xa6a6a6a6a6a6a6a6
     enc = AES.new(kek).encrypt
     r = [plain[i * 8:(i + 1) * 8] for i in range(0, n)]
@@ -976,21 +1638,21 @@ def aes_wrap(kek, plain):
         for i in range(1, n + 1):
             b = enc(struct.pack('>Q', a) + r[i - 1])
             a = struct.unpack('>Q', b[:8])[0] ^ (n * j + i)
-            r[i - 1] =b[8:]
-    return struct.pack('>Q', a) + ''.join(r)
+            r[i - 1] = b[8:]
+    return struct.pack('>Q', a) + b''.join(r)
 
 def pad_key_data(plain):
     pad_len = len(plain) % 8
     if pad_len:
         pad_len = 8 - pad_len
-        plain += '\xdd'
+        plain += b'\xdd'
         pad_len -= 1
-        plain += pad_len * '\0'
+        plain += pad_len * b'\x00'
     return plain
 
 def test_ap_wpa2_psk_supp_proto(dev, apdev):
     """WPA2-PSK 4-way handshake protocol testing for supplicant"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1001,7 +1663,7 @@ def test_ap_wpa2_psk_supp_proto(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1009,105 +1671,105 @@ def test_ap_wpa2_psk_supp_proto(dev, apdev):
 
     logger.debug("Invalid AES wrap data length 0")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '', replay_counter=counter)
+    msg = build_eapol_key_3_4(anonce, kck, b'', replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Unsupported AES-WRAP len 0"])
     if ev is None:
         raise Exception("Unsupported AES-WRAP len 0 not reported")
 
     logger.debug("Invalid AES wrap data length 1")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '1', replay_counter=counter)
+    msg = build_eapol_key_3_4(anonce, kck, b'1', replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Unsupported AES-WRAP len 1"])
     if ev is None:
         raise Exception("Unsupported AES-WRAP len 1 not reported")
 
     logger.debug("Invalid AES wrap data length 9")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '123456789', replay_counter=counter)
+    msg = build_eapol_key_3_4(anonce, kck, b'123456789', replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Unsupported AES-WRAP len 9"])
     if ev is None:
         raise Exception("Unsupported AES-WRAP len 9 not reported")
 
     logger.debug("Invalid AES wrap data payload")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '12345678', replay_counter=counter)
+    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter)
     # do not increment counter to test replay protection
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: AES unwrap failed"])
     if ev is None:
         raise Exception("AES unwrap failure not reported")
 
     logger.debug("Replay Count not increasing")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '12345678', replay_counter=counter)
+    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: EAPOL-Key Replay Counter did not increase"])
     if ev is None:
         raise Exception("Replay Counter replay not reported")
 
     logger.debug("Missing Ack bit in key info")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '12345678', replay_counter=counter,
+    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
                               key_info=0x134a)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: No Ack bit in key_info"])
     if ev is None:
         raise Exception("Missing Ack bit not reported")
 
     logger.debug("Unexpected Request bit in key info")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '12345678', replay_counter=counter,
+    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
                               key_info=0x1bca)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: EAPOL-Key with Request bit"])
     if ev is None:
         raise Exception("Request bit not reported")
 
     logger.debug("Unsupported key descriptor version 0")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '0123456789abcdef',
+    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
                               replay_counter=counter, key_info=0x13c8)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Unsupported EAPOL-Key descriptor version 0"])
     if ev is None:
         raise Exception("Unsupported EAPOL-Key descriptor version 0 not reported")
 
     logger.debug("Key descriptor version 1 not allowed with CCMP")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '0123456789abcdef',
+    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
                               replay_counter=counter, key_info=0x13c9)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: CCMP is used, but EAPOL-Key descriptor version (1) is not 2"])
     if ev is None:
         raise Exception("Not allowed EAPOL-Key descriptor version not reported")
 
     logger.debug("Invalid AES wrap payload with key descriptor version 2")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '0123456789abcdef',
+    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
                               replay_counter=counter, key_info=0x13ca)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: AES unwrap failed"])
     if ev is None:
         raise Exception("AES unwrap failure not reported")
 
     logger.debug("Key descriptor version 3 workaround")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '0123456789abcdef',
+    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
                               replay_counter=counter, key_info=0x13cb)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: CCMP is used, but EAPOL-Key descriptor version (3) is not 2"])
     if ev is None:
         raise Exception("CCMP key descriptor mismatch not reported")
@@ -1120,74 +1782,74 @@ def test_ap_wpa2_psk_supp_proto(dev, apdev):
 
     logger.debug("Unsupported key descriptor version 4")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '0123456789abcdef',
+    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
                               replay_counter=counter, key_info=0x13cc)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Unsupported EAPOL-Key descriptor version 4"])
     if ev is None:
         raise Exception("Unsupported EAPOL-Key descriptor version 4 not reported")
 
     logger.debug("Unsupported key descriptor version 7")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '0123456789abcdef',
+    msg = build_eapol_key_3_4(anonce, kck, b'0123456789abcdef',
                               replay_counter=counter, key_info=0x13cf)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Unsupported EAPOL-Key descriptor version 7"])
     if ev is None:
         raise Exception("Unsupported EAPOL-Key descriptor version 7 not reported")
 
     logger.debug("Too short EAPOL header length")
     dev[0].dump_monitor()
-    msg = build_eapol_key_3_4(anonce, kck, '12345678', replay_counter=counter,
+    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
                               extra_len=-1)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Invalid EAPOL-Key frame - key_data overflow (8 > 7)"])
     if ev is None:
         raise Exception("Key data overflow not reported")
 
     logger.debug("Too long EAPOL header length")
-    msg = build_eapol_key_3_4(anonce, kck, '12345678', replay_counter=counter,
+    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
                               extra_len=1)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
 
     logger.debug("Unsupported descriptor type 0")
-    msg = build_eapol_key_3_4(anonce, kck, '12345678', replay_counter=counter,
+    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
                               descr_type=0)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
 
     logger.debug("WPA descriptor type 0")
-    msg = build_eapol_key_3_4(anonce, kck, '12345678', replay_counter=counter,
+    msg = build_eapol_key_3_4(anonce, kck, b'12345678', replay_counter=counter,
                               descr_type=254)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
 
     logger.debug("Non-zero key index for pairwise key")
     dev[0].dump_monitor()
-    wrapped = aes_wrap(kek, 16*'z')
+    wrapped = aes_wrap(kek, 16*b'z')
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
                               key_info=0x13ea)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Ignored EAPOL-Key (Pairwise) with non-zero key index"])
     if ev is None:
         raise Exception("Non-zero key index not reported")
 
     logger.debug("Invalid Key Data plaintext payload --> disconnect")
     dev[0].dump_monitor()
-    wrapped = aes_wrap(kek, 16*'z')
+    wrapped = aes_wrap(kek, 16*b'z')
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_disconnected(timeout=1)
 
 def test_ap_wpa2_psk_supp_proto_no_ie(dev, apdev):
     """WPA2-PSK supplicant protocol testing: IE not included"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1198,7 +1860,7 @@ def test_ap_wpa2_psk_supp_proto_no_ie(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1206,15 +1868,15 @@ def test_ap_wpa2_psk_supp_proto_no_ie(dev, apdev):
 
     logger.debug("No IEs in msg 3/4 --> disconnect")
     dev[0].dump_monitor()
-    wrapped = aes_wrap(kek, 16*'\0')
+    wrapped = aes_wrap(kek, 16*b'\x00')
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_disconnected(timeout=1)
 
 def test_ap_wpa2_psk_supp_proto_ie_mismatch(dev, apdev):
     """WPA2-PSK supplicant protocol testing: IE mismatch"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1225,7 +1887,7 @@ def test_ap_wpa2_psk_supp_proto_ie_mismatch(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1236,12 +1898,12 @@ def test_ap_wpa2_psk_supp_proto_ie_mismatch(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(binascii.unhexlify('30060100000fac04dd16000fac010100dc11188831bf4aa4a8678d2b41498618')))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_disconnected(timeout=1)
 
 def test_ap_wpa2_psk_supp_proto_ok(dev, apdev):
     """WPA2-PSK supplicant protocol testing: success"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1252,7 +1914,7 @@ def test_ap_wpa2_psk_supp_proto_ok(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1264,12 +1926,12 @@ def test_ap_wpa2_psk_supp_proto_ok(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_connected(timeout=1)
 
 def test_ap_wpa2_psk_supp_proto_no_gtk(dev, apdev):
     """WPA2-PSK supplicant protocol testing: no GTK"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1280,7 +1942,7 @@ def test_ap_wpa2_psk_supp_proto_no_gtk(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1292,14 +1954,14 @@ def test_ap_wpa2_psk_supp_proto_no_gtk(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
     if ev is not None:
         raise Exception("Unexpected connection completion reported")
 
 def test_ap_wpa2_psk_supp_proto_anonce_change(dev, apdev):
     """WPA2-PSK supplicant protocol testing: ANonce change"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1310,7 +1972,7 @@ def test_ap_wpa2_psk_supp_proto_anonce_change(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1323,14 +1985,14 @@ def test_ap_wpa2_psk_supp_proto_anonce_change(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce2, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: ANonce from message 1 of 4-Way Handshake differs from 3 of 4-Way Handshake"])
     if ev is None:
         raise Exception("ANonce change not reported")
 
 def test_ap_wpa2_psk_supp_proto_unexpected_group_msg(dev, apdev):
     """WPA2-PSK supplicant protocol testing: unexpected group message"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1341,7 +2003,7 @@ def test_ap_wpa2_psk_supp_proto_unexpected_group_msg(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1353,15 +2015,16 @@ def test_ap_wpa2_psk_supp_proto_unexpected_group_msg(dev, apdev):
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
                               key_info=0x13c2)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Group Key Handshake started prior to completion of 4-way handshake"])
     if ev is None:
         raise Exception("Unexpected group key message not reported")
     dev[0].wait_disconnected(timeout=1)
 
+@remote_compatible
 def test_ap_wpa2_psk_supp_proto_msg_1_invalid_kde(dev, apdev):
     """WPA2-PSK supplicant protocol testing: invalid KDE in msg 1/4"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1373,12 +2036,12 @@ def test_ap_wpa2_psk_supp_proto_msg_1_invalid_kde(dev, apdev):
     msg = build_eapol_key_1_4(anonce, replay_counter=counter,
                               key_data=binascii.unhexlify('5555'))
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_disconnected(timeout=1)
 
 def test_ap_wpa2_psk_supp_proto_wrong_pairwise_key_len(dev, apdev):
     """WPA2-PSK supplicant protocol testing: wrong pairwise key length"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1389,7 +2052,7 @@ def test_ap_wpa2_psk_supp_proto_wrong_pairwise_key_len(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1402,7 +2065,7 @@ def test_ap_wpa2_psk_supp_proto_wrong_pairwise_key_len(dev, apdev):
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
                               key_len=15)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Invalid CCMP key length 15"])
     if ev is None:
         raise Exception("Invalid CCMP key length not reported")
@@ -1410,7 +2073,7 @@ def test_ap_wpa2_psk_supp_proto_wrong_pairwise_key_len(dev, apdev):
 
 def test_ap_wpa2_psk_supp_proto_wrong_group_key_len(dev, apdev):
     """WPA2-PSK supplicant protocol testing: wrong group key length"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1421,7 +2084,7 @@ def test_ap_wpa2_psk_supp_proto_wrong_group_key_len(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1433,7 +2096,7 @@ def test_ap_wpa2_psk_supp_proto_wrong_group_key_len(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Unsupported CCMP Group Cipher key length 15"])
     if ev is None:
         raise Exception("Invalid CCMP key length not reported")
@@ -1441,7 +2104,7 @@ def test_ap_wpa2_psk_supp_proto_wrong_group_key_len(dev, apdev):
 
 def test_ap_wpa2_psk_supp_proto_gtk_tx_bit_workaround(dev, apdev):
     """WPA2-PSK supplicant protocol testing: GTK TX bit workaround"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1452,7 +2115,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_tx_bit_workaround(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1464,7 +2127,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_tx_bit_workaround(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Tx bit set for GTK, but pairwise keys are used - ignore Tx bit"])
     if ev is None:
         raise Exception("GTK Tx bit workaround not reported")
@@ -1472,7 +2135,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_tx_bit_workaround(dev, apdev):
 
 def test_ap_wpa2_psk_supp_proto_gtk_keyidx_0_and_3(dev, apdev):
     """WPA2-PSK supplicant protocol testing: GTK key index 0 and 3"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1483,7 +2146,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_keyidx_0_and_3(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1495,7 +2158,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_keyidx_0_and_3(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_connected(timeout=1)
 
     logger.debug("Valid EAPOL-Key group msg 1/2 (GTK keyidx 3)")
@@ -1505,7 +2168,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_keyidx_0_and_3(dev, apdev):
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
                               key_info=0x13c2)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     ev = dev[0].wait_event(["WPA: Group rekeying completed"])
     if ev is None:
@@ -1517,7 +2180,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_keyidx_0_and_3(dev, apdev):
     msg = build_eapol_key_3_4(anonce, kck, plain, replay_counter=counter,
                               key_info=0x03c2)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: GTK IE in unencrypted key data"])
     if ev is None:
         raise Exception("Unencrypted GTK KDE not reported")
@@ -1525,7 +2188,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_keyidx_0_and_3(dev, apdev):
 
 def test_ap_wpa2_psk_supp_proto_no_gtk_in_group_msg(dev, apdev):
     """WPA2-PSK supplicant protocol testing: GTK KDE missing from group msg"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1536,7 +2199,7 @@ def test_ap_wpa2_psk_supp_proto_no_gtk_in_group_msg(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1548,7 +2211,7 @@ def test_ap_wpa2_psk_supp_proto_no_gtk_in_group_msg(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_connected(timeout=1)
 
     logger.debug("No GTK KDE in EAPOL-Key group msg 1/2")
@@ -1558,7 +2221,7 @@ def test_ap_wpa2_psk_supp_proto_no_gtk_in_group_msg(dev, apdev):
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
                               key_info=0x13c2)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: No GTK IE in Group Key msg 1/2"])
     if ev is None:
         raise Exception("Missing GTK KDE not reported")
@@ -1566,7 +2229,7 @@ def test_ap_wpa2_psk_supp_proto_no_gtk_in_group_msg(dev, apdev):
 
 def test_ap_wpa2_psk_supp_proto_too_long_gtk_in_group_msg(dev, apdev):
     """WPA2-PSK supplicant protocol testing: too long GTK KDE in group msg"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1577,7 +2240,7 @@ def test_ap_wpa2_psk_supp_proto_too_long_gtk_in_group_msg(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1589,7 +2252,7 @@ def test_ap_wpa2_psk_supp_proto_too_long_gtk_in_group_msg(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_connected(timeout=1)
 
     logger.debug("EAPOL-Key group msg 1/2 with too long GTK KDE")
@@ -1599,7 +2262,7 @@ def test_ap_wpa2_psk_supp_proto_too_long_gtk_in_group_msg(dev, apdev):
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter,
                               key_info=0x13c2)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: Unsupported CCMP Group Cipher key length 33"])
     if ev is None:
         raise Exception("Too long GTK KDE not reported")
@@ -1607,7 +2270,7 @@ def test_ap_wpa2_psk_supp_proto_too_long_gtk_in_group_msg(dev, apdev):
 
 def test_ap_wpa2_psk_supp_proto_too_long_gtk_kde(dev, apdev):
     """WPA2-PSK supplicant protocol testing: too long GTK KDE"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1618,7 +2281,7 @@ def test_ap_wpa2_psk_supp_proto_too_long_gtk_kde(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1630,12 +2293,12 @@ def test_ap_wpa2_psk_supp_proto_too_long_gtk_kde(dev, apdev):
     wrapped = aes_wrap(kek, pad_key_data(plain))
     msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     dev[0].wait_disconnected(timeout=1)
 
 def test_ap_wpa2_psk_supp_proto_gtk_not_encrypted(dev, apdev):
     """WPA2-PSK supplicant protocol testing: GTK KDE not encrypted"""
-    (bssid,ssid,hapd,snonce,pmk,addr,rsne) = eapol_test(apdev[0], dev[0])
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0])
 
     # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
     msg = recv_eapol(hapd)
@@ -1646,7 +2309,7 @@ def test_ap_wpa2_psk_supp_proto_gtk_not_encrypted(dev, apdev):
     counter = 1
     msg = build_eapol_key_1_4(anonce, replay_counter=counter)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     msg = recv_eapol(dev[0])
     snonce = msg['rsn_key_nonce']
 
@@ -1658,12 +2321,93 @@ def test_ap_wpa2_psk_supp_proto_gtk_not_encrypted(dev, apdev):
     msg = build_eapol_key_3_4(anonce, kck, plain, replay_counter=counter,
                               key_info=0x03ca)
     counter += 1
-    send_eapol(dev[0], addr, build_eapol(msg))
+    send_eapol(dev[0], bssid, build_eapol(msg))
     ev = dev[0].wait_event(["WPA: GTK IE in unencrypted key data"])
     if ev is None:
         raise Exception("Unencrypted GTK KDE not reported")
     dev[0].wait_disconnected(timeout=1)
 
+def run_psk_supp_proto_pmf2(dev, apdev, igtk_kde=None, fail=False):
+    (bssid, ssid, hapd, snonce, pmk, addr, rsne) = eapol_test(apdev[0], dev[0],
+                                                              ieee80211w=2)
+
+    # Wait for EAPOL-Key msg 1/4 from hostapd to determine when associated
+    msg = recv_eapol(hapd)
+    dev[0].dump_monitor()
+
+    # Build own EAPOL-Key msg 1/4
+    anonce = binascii.unhexlify('2222222222222222222222222222222222222222222222222222222222222222')
+    counter = 1
+    msg = build_eapol_key_1_4(anonce, replay_counter=counter)
+    counter += 1
+    send_eapol(dev[0], bssid, build_eapol(msg))
+    msg = recv_eapol(dev[0])
+    snonce = msg['rsn_key_nonce']
+
+    (ptk, kck, kek) = pmk_to_ptk(pmk, addr, bssid, snonce, anonce)
+
+    logger.debug("EAPOL-Key msg 3/4")
+    dev[0].dump_monitor()
+    gtk_kde = binascii.unhexlify('dd16000fac010100dc11188831bf4aa4a8678d2b41498618')
+    plain = rsne + gtk_kde
+    if igtk_kde:
+        plain += igtk_kde
+    wrapped = aes_wrap(kek, pad_key_data(plain))
+    msg = build_eapol_key_3_4(anonce, kck, wrapped, replay_counter=counter)
+    counter += 1
+    send_eapol(dev[0], bssid, build_eapol(msg))
+    if fail:
+        dev[0].wait_disconnected(timeout=1)
+        return
+
+    dev[0].wait_connected(timeout=1)
+
+    # Verify that an unprotected broadcast Deauthentication frame is ignored
+    bssid = binascii.unhexlify(hapd.own_addr().replace(':', ''))
+    sock = start_monitor(apdev[1]["ifname"])
+    radiotap = radiotap_build()
+    frame = binascii.unhexlify("c0003a01")
+    frame += 6*b'\xff' + bssid + bssid
+    frame += binascii.unhexlify("1000" + "0300")
+    sock.send(radiotap + frame)
+    # And same with incorrect BIP protection
+    for keyid in ["0400", "0500", "0600", "0004", "0005", "0006", "ffff"]:
+        frame2 = frame + binascii.unhexlify("4c10" + keyid + "010000000000c0e5ca5f2b3b4de9")
+        sock.send(radiotap + frame2)
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.5)
+    if ev is not None:
+        raise Exception("Unexpected disconnection")
+
+def run_psk_supp_proto_pmf(dev, apdev, igtk_kde=None, fail=False):
+    try:
+        run_psk_supp_proto_pmf2(dev, apdev, igtk_kde=igtk_kde, fail=fail)
+    finally:
+        stop_monitor(apdev[1]["ifname"])
+
+def test_ap_wpa2_psk_supp_proto_no_igtk(dev, apdev):
+    """WPA2-PSK supplicant protocol testing: no IGTK KDE"""
+    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=None)
+
+def test_ap_wpa2_psk_supp_proto_igtk_ok(dev, apdev):
+    """WPA2-PSK supplicant protocol testing: valid IGTK KDE"""
+    igtk_kde = binascii.unhexlify('dd1c' + '000fac09' + '0400' + 6*'00' + 16*'77')
+    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=igtk_kde)
+
+def test_ap_wpa2_psk_supp_proto_igtk_keyid_swap(dev, apdev):
+    """WPA2-PSK supplicant protocol testing: swapped IGTK KeyID"""
+    igtk_kde = binascii.unhexlify('dd1c' + '000fac09' + '0004' + 6*'00' + 16*'77')
+    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=igtk_kde)
+
+def test_ap_wpa2_psk_supp_proto_igtk_keyid_too_large(dev, apdev):
+    """WPA2-PSK supplicant protocol testing: too large IGTK KeyID"""
+    igtk_kde = binascii.unhexlify('dd1c' + '000fac09' + 'ffff' + 6*'00' + 16*'77')
+    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=igtk_kde, fail=True)
+
+def test_ap_wpa2_psk_supp_proto_igtk_keyid_unexpected(dev, apdev):
+    """WPA2-PSK supplicant protocol testing: unexpected IGTK KeyID"""
+    igtk_kde = binascii.unhexlify('dd1c' + '000fac09' + '0006' + 6*'00' + 16*'77')
+    run_psk_supp_proto_pmf(dev, apdev, igtk_kde=igtk_kde, fail=True)
+
 def find_wpas_process(dev):
     ifname = dev.ifname
     err, data = dev.cmd_execute(['ps', 'ax'])
@@ -1679,7 +2423,7 @@ def read_process_memory(pid, key=None):
     buf = bytes()
     logger.info("Reading process memory (pid=%d)" % pid)
     with open('/proc/%d/maps' % pid, 'r') as maps, \
-         open('/proc/%d/mem' % pid, 'r') as mem:
+         open('/proc/%d/mem' % pid, 'rb') as mem:
         for l in maps.readlines():
             m = re.match(r'([0-9a-f]+)-([0-9a-f]+) ([-r][-w][-x][-p])', l)
             if not m:
@@ -1693,7 +2437,7 @@ def read_process_memory(pid, key=None):
                 continue
             if not perm.startswith('rw'):
                 continue
-            for name in [ "[heap]", "[stack]" ]:
+            for name in ["[heap]", "[stack]"]:
                 if name in l:
                     logger.info("%s 0x%x-0x%x is at %d-%d" % (name, start, end, len(buf), len(buf) + (end - start)))
             mem.seek(start)
@@ -1710,7 +2454,7 @@ def verify_not_present(buf, key, fname, keyname):
         return
 
     prefix = 2048 if pos > 2048 else pos
-    with open(fname + keyname, 'w') as f:
+    with open(fname + keyname, 'wb') as f:
         f.write(buf[pos - prefix:pos + 2048])
     raise Exception(keyname + " found after disassociation")
 
@@ -1722,7 +2466,7 @@ def get_key_locations(buf, key, keyname):
         if pos < 0:
             break
         logger.info("Found %s at %d" % (keyname, pos))
-        context = 128;
+        context = 128
         start = pos - context if pos > context else 0
         before = binascii.hexlify(buf[start:pos])
         context += len(key)
@@ -1804,11 +2548,8 @@ def test_wpa2_psk_key_lifetime_in_memory(dev, apdev, params):
         raise Exception("KCK not found while associated")
     if kek not in buf:
         raise Exception("KEK not found while associated")
-    if tk in buf:
-        raise Exception("TK found from memory")
-    if gtk in buf:
-        get_key_locations(buf, gtk, "GTK")
-        raise Exception("GTK found from memory")
+    #if tk in buf:
+    #    raise Exception("TK found from memory")
 
     logger.info("Checking keys in memory after disassociation")
     buf = read_process_memory(pid, pmk)
@@ -1821,6 +2562,8 @@ def test_wpa2_psk_key_lifetime_in_memory(dev, apdev, params):
     verify_not_present(buf, kck, fname, "KCK")
     verify_not_present(buf, kek, fname, "KEK")
     verify_not_present(buf, tk, fname, "TK")
+    if gtk in buf:
+        get_key_locations(buf, gtk, "GTK")
     verify_not_present(buf, gtk, fname, "GTK")
 
     dev[0].request("REMOVE_NETWORK all")
@@ -1835,6 +2578,7 @@ def test_wpa2_psk_key_lifetime_in_memory(dev, apdev, params):
     verify_not_present(buf, tk, fname, "TK")
     verify_not_present(buf, gtk, fname, "GTK")
 
+@remote_compatible
 def test_ap_wpa2_psk_wep(dev, apdev):
     """WPA2-PSK AP and WEP enabled"""
     ssid = "test-wpa2-psk"
@@ -1849,8 +2593,8 @@ def test_ap_wpa2_psk_wep(dev, apdev):
 
 def test_ap_wpa2_psk_wpas_in_bridge(dev, apdev):
     """WPA2-PSK AP and wpas interface in a bridge"""
-    br_ifname='sta-br0'
-    ifname='wlan5'
+    br_ifname = 'sta-br0'
+    ifname = 'wlan5'
     try:
         _test_ap_wpa2_psk_wpas_in_bridge(dev, apdev)
     finally:
@@ -1865,8 +2609,8 @@ def _test_ap_wpa2_psk_wpas_in_bridge(dev, apdev):
     params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
     hapd = hostapd.add_ap(apdev[0], params)
 
-    br_ifname='sta-br0'
-    ifname='wlan5'
+    br_ifname = 'sta-br0'
+    ifname = 'wlan5'
     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
     subprocess.call(['brctl', 'addbr', br_ifname])
     subprocess.call(['brctl', 'setfd', br_ifname, '0'])
@@ -1879,6 +2623,7 @@ def _test_ap_wpa2_psk_wpas_in_bridge(dev, apdev):
     wpas.connect(ssid, psk=passphrase, scan_freq="2412")
     wpas.dump_monitor()
 
+@remote_compatible
 def test_ap_wpa2_psk_ifdown(dev, apdev):
     """AP with open mode and external ifconfig down"""
     ssid = "test-wpa2-psk"
@@ -1968,6 +2713,7 @@ def test_ap_wpa2_psk_drop_first_msg_4(dev, apdev):
         # case, this exception can be uncommented here.
         #raise Exception("Unexpected disconnection")
 
+@remote_compatible
 def test_ap_wpa2_psk_disable_enable(dev, apdev):
     """WPA2-PSK AP getting disabled and re-enabled"""
     ssid = "test-wpa2-psk"
@@ -1985,6 +2731,7 @@ def test_ap_wpa2_psk_disable_enable(dev, apdev):
         dev[0].wait_connected()
         hwsim_utils.test_connectivity(dev[0], hapd)
 
+@remote_compatible
 def test_ap_wpa2_psk_incorrect_passphrase(dev, apdev):
     """WPA2-PSK AP and station using incorrect passphrase"""
     ssid = "test-wpa2-psk"
@@ -2004,6 +2751,7 @@ def test_ap_wpa2_psk_incorrect_passphrase(dev, apdev):
 
     dev[0].wait_connected(timeout=20)
 
+@remote_compatible
 def test_ap_wpa_ie_parsing(dev, apdev):
     """WPA IE parsing"""
     skip_with_fips(dev[0])
@@ -2014,29 +2762,29 @@ def test_ap_wpa_ie_parsing(dev, apdev):
     id = dev[0].connect(ssid, psk=passphrase, scan_freq="2412",
                         only_add_network=True)
 
-    tests = [ "dd040050f201",
-              "dd050050f20101",
-              "dd060050f2010100",
-              "dd060050f2010001",
-              "dd070050f201010000",
-              "dd080050f20101000050",
-              "dd090050f20101000050f2",
-              "dd0a0050f20101000050f202",
-              "dd0b0050f20101000050f20201",
-              "dd0c0050f20101000050f2020100",
-              "dd0c0050f20101000050f2020000",
-              "dd0c0050f20101000050f202ffff",
-              "dd0d0050f20101000050f202010000",
-              "dd0e0050f20101000050f20201000050",
-              "dd0f0050f20101000050f20201000050f2",
-              "dd100050f20101000050f20201000050f202",
-              "dd110050f20101000050f20201000050f20201",
-              "dd120050f20101000050f20201000050f2020100",
-              "dd120050f20101000050f20201000050f2020000",
-              "dd120050f20101000050f20201000050f202ffff",
-              "dd130050f20101000050f20201000050f202010000",
-              "dd140050f20101000050f20201000050f20201000050",
-              "dd150050f20101000050f20201000050f20201000050f2" ]
+    tests = ["dd040050f201",
+             "dd050050f20101",
+             "dd060050f2010100",
+             "dd060050f2010001",
+             "dd070050f201010000",
+             "dd080050f20101000050",
+             "dd090050f20101000050f2",
+             "dd0a0050f20101000050f202",
+             "dd0b0050f20101000050f20201",
+             "dd0c0050f20101000050f2020100",
+             "dd0c0050f20101000050f2020000",
+             "dd0c0050f20101000050f202ffff",
+             "dd0d0050f20101000050f202010000",
+             "dd0e0050f20101000050f20201000050",
+             "dd0f0050f20101000050f20201000050f2",
+             "dd100050f20101000050f20201000050f202",
+             "dd110050f20101000050f20201000050f20201",
+             "dd120050f20101000050f20201000050f2020100",
+             "dd120050f20101000050f20201000050f2020000",
+             "dd120050f20101000050f20201000050f202ffff",
+             "dd130050f20101000050f20201000050f202010000",
+             "dd140050f20101000050f20201000050f20201000050",
+             "dd150050f20101000050f20201000050f20201000050f2"]
     for t in tests:
         try:
             if "OK" not in dev[0].request("VENDOR_ELEM_ADD 13 " + t):
@@ -2050,20 +2798,24 @@ def test_ap_wpa_ie_parsing(dev, apdev):
         finally:
             dev[0].request("VENDOR_ELEM_REMOVE 13 *")
 
-    tests = [ "dd170050f20101000050f20201000050f20201000050f202ff",
-              "dd180050f20101000050f20201000050f20201000050f202ffff",
-              "dd190050f20101000050f20201000050f20201000050f202ffffff" ]
+    tests = ["dd170050f20101000050f20201000050f20201000050f202ff",
+             "dd180050f20101000050f20201000050f20201000050f202ffff",
+             "dd190050f20101000050f20201000050f20201000050f202ffffff"]
     for t in tests:
         try:
             if "OK" not in dev[0].request("VENDOR_ELEM_ADD 13 " + t):
                 raise Exception("VENDOR_ELEM_ADD failed")
             dev[0].select_network(id)
-            dev[0].wait_connected()
+            ev = dev[0].wait_event(['CTRL-EVENT-CONNECTED',
+                                    'WPA: 4-Way Handshake failed'], timeout=10)
+            if ev is None:
+                raise Exception("Association failed unexpectedly")
             dev[0].request("DISCONNECT")
             dev[0].dump_monitor()
         finally:
             dev[0].request("VENDOR_ELEM_REMOVE 13 *")
 
+@remote_compatible
 def test_ap_wpa2_psk_no_random(dev, apdev):
     """WPA2-PSK AP and no random numbers available"""
     ssid = "test-wpa2-psk"
@@ -2082,6 +2834,7 @@ def test_ap_wpa2_psk_no_random(dev, apdev):
         dev[0].select_network(id, freq=2412)
         dev[0].wait_connected()
 
+@remote_compatible
 def test_rsn_ie_proto_psk_sta(dev, apdev):
     """RSN element protocol testing for PSK cases on STA side"""
     bssid = apdev[0]['bssid']
@@ -2095,23 +2848,29 @@ def test_rsn_ie_proto_psk_sta(dev, apdev):
         raise Exception("Invalid own_ie_override value accepted")
     id = dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
 
-    tests = [ ('No RSN Capabilities field',
-               '30120100000fac040100000fac040100000fac02'),
-              ('Reserved RSN Capabilities bits set',
-               '30140100000fac040100000fac040100000fac023cff'),
-              ('Extra pairwise cipher suite (unsupported)',
-               '30180100000fac040200ffffffff000fac040100000fac020c00'),
-              ('Extra AKM suite (unsupported)',
-               '30180100000fac040100000fac040200ffffffff000fac020c00'),
-              ('PMKIDCount field included',
-               '30160100000fac040100000fac040100000fac020c000000'),
-              ('Unexpected Group Management Cipher Suite with PMF disabled',
-               '301a0100000fac040100000fac040100000fac020c000000000fac06'),
-              ('Extra octet after defined fields (future extensibility)',
-               '301b0100000fac040100000fac040100000fac020c000000000fac0600') ]
-    for txt,ie in tests:
+    tests = [('No RSN Capabilities field',
+              '30120100000fac040100000fac040100000fac02'),
+             ('Reserved RSN Capabilities bits set',
+              '30140100000fac040100000fac040100000fac023cff'),
+             ('Truncated RSN Capabilities field',
+              '30130100000fac040100000fac040100000fac023c'),
+             ('Extra pairwise cipher suite (unsupported)',
+              '30180100000fac040200ffffffff000fac040100000fac020c00'),
+             ('Extra AKM suite (unsupported)',
+              '30180100000fac040100000fac040200ffffffff000fac020c00'),
+             ('PMKIDCount field included',
+              '30160100000fac040100000fac040100000fac020c000000'),
+             ('Truncated PMKIDCount field',
+              '30150100000fac040100000fac040100000fac020c0000'),
+             ('Unexpected Group Management Cipher Suite with PMF disabled',
+              '301a0100000fac040100000fac040100000fac020c000000000fac06'),
+             ('Extra octet after defined fields (future extensibility)',
+              '301b0100000fac040100000fac040100000fac020c000000000fac0600')]
+    for txt, ie in tests:
         dev[0].request("DISCONNECT")
         dev[0].wait_disconnected()
+        dev[0].dump_monitor()
+        dev[0].request("NOTE " + txt)
         logger.info(txt)
         hapd.disable()
         hapd.set('own_ie_override', ie)
@@ -2121,6 +2880,7 @@ def test_rsn_ie_proto_psk_sta(dev, apdev):
         dev[0].select_network(id, freq=2412)
         dev[0].wait_connected()
 
+@remote_compatible
 def test_ap_cli_order(dev, apdev):
     ssid = "test-rsn-setup"
     passphrase = 'zzzzzzzz'
@@ -2150,6 +2910,7 @@ def set_test_assoc_ie(dev, ie):
     if "OK" not in dev.request("TEST_ASSOC_IE " + ie):
         raise Exception("Could not set TEST_ASSOC_IE")
 
+@remote_compatible
 def test_ap_wpa2_psk_assoc_rsn(dev, apdev):
     """WPA2-PSK AP and association request RSN IE differences"""
     ssid = "test-wpa2-psk"
@@ -2157,10 +2918,10 @@ def test_ap_wpa2_psk_assoc_rsn(dev, apdev):
     params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
     hapd = hostapd.add_ap(apdev[0], params)
 
-    tests = [ ("Normal wpa_supplicant assoc req RSN IE",
-               "30140100000fac040100000fac040100000fac020000"),
-              ("RSN IE without RSN Capabilities",
-               "30120100000fac040100000fac040100000fac02") ]
+    tests = [("Normal wpa_supplicant assoc req RSN IE",
+              "30140100000fac040100000fac040100000fac020000"),
+             ("RSN IE without RSN Capabilities",
+              "30120100000fac040100000fac040100000fac02")]
     for title, ie in tests:
         logger.info(title)
         set_test_assoc_ie(dev[0], ie)
@@ -2168,11 +2929,11 @@ def test_ap_wpa2_psk_assoc_rsn(dev, apdev):
         dev[0].request("REMOVE_NETWORK all")
         dev[0].wait_disconnected()
 
-    tests = [ ("WPA IE instead of RSN IE and only RSN enabled on AP",
-               "dd160050f20101000050f20201000050f20201000050f202", 40),
-              ("Empty RSN IE", "3000", 40),
-              ("RSN IE with truncated Version", "300101", 40),
-              ("RSN IE with only Version", "30020100", 43) ]
+    tests = [("WPA IE instead of RSN IE and only RSN enabled on AP",
+              "dd160050f20101000050f20201000050f20201000050f202", 40),
+             ("Empty RSN IE", "3000", 40),
+             ("RSN IE with truncated Version", "300101", 40),
+             ("RSN IE with only Version", "30020100", 43)]
     for title, ie, status in tests:
         logger.info(title)
         set_test_assoc_ie(dev[0], ie)
@@ -2185,3 +2946,233 @@ def test_ap_wpa2_psk_assoc_rsn(dev, apdev):
             raise Exception("Unexpected status code: " + ev)
         dev[0].request("REMOVE_NETWORK all")
         dev[0].dump_monitor()
+
+def test_ap_wpa2_psk_ft_workaround(dev, apdev):
+    """WPA2-PSK+FT AP and workaround for incorrect STA behavior"""
+    ssid = "test-wpa2-psk-ft"
+    passphrase = 'qwertyuiop'
+
+    params = {"wpa": "2",
+              "wpa_key_mgmt": "FT-PSK WPA-PSK",
+              "rsn_pairwise": "CCMP",
+              "ssid": ssid,
+              "wpa_passphrase": passphrase}
+    params["mobility_domain"] = "a1b2"
+    params["r0_key_lifetime"] = "10000"
+    params["pmk_r1_push"] = "1"
+    params["reassociation_deadline"] = "1000"
+    params['nas_identifier'] = "nas1.w1.fi"
+    params['r1_key_holder'] = "000102030405"
+    hapd = hostapd.add_ap(apdev[0], params)
+
+    # Include both WPA-PSK and FT-PSK AKMs in Association Request frame
+    set_test_assoc_ie(dev[0],
+                      "30180100000fac040100000fac040200000fac02000fac040000")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+def test_ap_wpa2_psk_assoc_rsn_pmkid(dev, apdev):
+    """WPA2-PSK AP and association request RSN IE with PMKID"""
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
+    hapd = hostapd.add_ap(apdev[0], params)
+
+    set_test_assoc_ie(dev[0], "30260100000fac040100000fac040100000fac0200000100" + 16*'00')
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+def test_ap_wpa_psk_rsn_pairwise(dev, apdev):
+    """WPA-PSK AP and only rsn_pairwise set"""
+    params = {"ssid": "wpapsk", "wpa": "1", "wpa_key_mgmt": "WPA-PSK",
+              "rsn_pairwise": "TKIP", "wpa_passphrase": "1234567890"}
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].connect("wpapsk", psk="1234567890", proto="WPA", pairwise="TKIP",
+                   scan_freq="2412")
+
+def test_ap_wpa2_eapol_retry_limit(dev, apdev):
+    """WPA2-PSK EAPOL-Key retry limit configuration"""
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
+    params['wpa_ptk_rekey'] = '2'
+    params['wpa_group_update_count'] = '1'
+    params['wpa_pairwise_update_count'] = '1'
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
+    ev = dev[0].wait_event(["WPA: Key negotiation completed"])
+    if ev is None:
+        raise Exception("PTK rekey timed out")
+
+    if "FAIL" not in hapd.request("SET wpa_group_update_count 0"):
+        raise Exception("Invalid wpa_group_update_count value accepted")
+    if "FAIL" not in hapd.request("SET wpa_pairwise_update_count 0"):
+        raise Exception("Invalid wpa_pairwise_update_count value accepted")
+
+def test_ap_wpa2_disable_eapol_retry(dev, apdev):
+    """WPA2-PSK disable EAPOL-Key retry"""
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
+    params['wpa_disable_eapol_key_retries'] = '1'
+    hapd = hostapd.add_ap(apdev[0], params)
+    bssid = apdev[0]['bssid']
+
+    logger.info("Verify working 4-way handshake without retries")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+    dev[0].dump_monitor()
+    addr = dev[0].own_addr()
+
+    logger.info("Verify no retransmission of message 3/4")
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
+
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX (M1) from hostapd")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX (M1 retry) from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX (M1) to wpa_supplicant failed")
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX (M2) from wpa_supplicant")
+    dev[0].dump_monitor()
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX (M2) to hostapd failed")
+
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX (M3) from hostapd")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=2)
+    if ev is not None:
+        raise Exception("Unexpected EAPOL-TX M3 retry from hostapd")
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=3)
+    if ev is None:
+        raise Exception("Disconnection not reported")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].dump_monitor()
+
+def test_ap_wpa2_disable_eapol_retry_group(dev, apdev):
+    """WPA2-PSK disable EAPOL-Key retry for group handshake"""
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
+    params['wpa_disable_eapol_key_retries'] = '1'
+    params['wpa_strict_rekey'] = '1'
+    hapd = hostapd.add_ap(apdev[0], params)
+    bssid = apdev[0]['bssid']
+
+    id = dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412")
+    dev[0].dump_monitor()
+    addr = dev[0].own_addr()
+
+    dev[1].request("DISCONNECT")
+    ev = dev[0].wait_event(["WPA: Group rekeying completed"], timeout=2)
+    if ev is None:
+        raise Exception("GTK rekey timed out")
+    dev[1].request("RECONNECT")
+    dev[1].wait_connected()
+    dev[0].dump_monitor()
+
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[1].request("DISCONNECT")
+
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX (group M1) from hostapd")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=2)
+    if ev is not None:
+        raise Exception("Unexpected EAPOL-TX group M1 retry from hostapd")
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=3)
+    if ev is None:
+        raise Exception("Disconnection not reported")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].dump_monitor()
+
+def test_ap_wpa2_psk_mic_0(dev, apdev):
+    """WPA2-PSK/TKIP and MIC=0 in EAPOL-Key msg 3/4"""
+    bssid = apdev[0]['bssid']
+    ssid = "test-wpa2-psk"
+    passphrase = 'qwertyuiop'
+    params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
+    params['rsn_pairwise'] = "TKIP"
+    hapd = hostapd.add_ap(apdev[0], params)
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev[0].request("SET ext_eapol_frame_io 1")
+    dev[0].connect(ssid, psk=passphrase, scan_freq="2412", wait_connect=False)
+    addr = dev[0].own_addr()
+
+    # EAPOL-Key msg 1/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    res = dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 2/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to hostapd failed")
+    dev[0].dump_monitor()
+
+    # EAPOL-Key msg 3/4
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from hostapd")
+    msg3 = ev.split(' ')[2]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+
+    # EAPOL-Key msg 4/4
+    ev = dev[0].wait_event(["EAPOL-TX"], timeout=15)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
+    # Do not send to the AP
+
+    # EAPOL-Key msg 3/4 with MIC=0 and modifications
+    eapol_hdr = msg3[0:8]
+    key_type = msg3[8:10]
+    key_info = msg3[10:14]
+    key_length = msg3[14:18]
+    replay_counter = msg3[18:34]
+    key_nonce = msg3[34:98]
+    key_iv = msg3[98:130]
+    key_rsc = msg3[130:146]
+    key_id = msg3[146:162]
+    key_mic = msg3[162:194]
+    key_data_len = msg3[194:198]
+    key_data = msg3[198:]
+
+    msg3b = eapol_hdr + key_type
+    msg3b += "12c9" # Clear MIC bit from key_info (originally 13c9)
+    msg3b += key_length
+    msg3b += '0000000000000003'
+    msg3b += key_nonce + key_iv + key_rsc + key_id
+    msg3b += 32*'0' # Clear MIC value
+    msg3b += key_data_len + key_data
+    dev[0].dump_monitor()
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg3b)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX to wpa_supplicant failed")
+    ev = dev[0].wait_event(["EAPOL-TX", "WPA: Ignore EAPOL-Key"], timeout=2)
+    if ev is None:
+        raise Exception("No event from wpa_supplicant")
+    if "EAPOL-TX" in ev:
+        raise Exception("Unexpected EAPOL-Key message from wpa_supplicant")
+    dev[0].request("DISCONNECT")