]> git.ipfire.org Git - thirdparty/hostap.git/blobdiff - tests/hwsim/test_ap_wps.py
tests: Use hostapd.remove_bss() instead of HostapdGlobal() (WPS)
[thirdparty/hostap.git] / tests / hwsim / test_ap_wps.py
index 29c02a4107552dd7c5fd4df200efbde5cd6d665c..405b4194b74f5639b1259bd829398e7625028c60 100644 (file)
@@ -6,6 +6,9 @@
 
 import base64
 import binascii
+from Crypto.Cipher import AES
+import hashlib
+import hmac
 import os
 import time
 import stat
@@ -14,6 +17,7 @@ import logging
 logger = logging.getLogger()
 import re
 import socket
+import struct
 import httplib
 import urlparse
 import urllib
@@ -25,17 +29,19 @@ import hwsim_utils
 import hostapd
 from wpasupplicant import WpaSupplicant
 from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
+from utils import wait_fail_trigger
+from test_ap_eap import int_eap_server_params
 
 def wps_start_ap(apdev, ssid="test-wps-conf"):
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                "wpa_passphrase": "12345678", "wpa": "2",
                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
-    return hostapd.add_ap(apdev['ifname'], params)
+    return hostapd.add_ap(apdev, params)
 
 def test_ap_wps_init(dev, apdev):
     """Initial AP configuration with first WPS Enrollee"""
     ssid = "test-wps"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
     logger.info("WPS provisioning step")
@@ -92,8 +98,8 @@ def test_ap_wps_init_2ap_pbc(dev, apdev):
     """Initial two-radio AP configuration with first WPS PBC Enrollee"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
-    hostapd.add_ap(apdev[0]['ifname'], params)
-    hostapd.add_ap(apdev[1]['ifname'], params)
+    hostapd.add_ap(apdev[0], params)
+    hostapd.add_ap(apdev[1], params)
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
     logger.info("WPS provisioning step")
     hapd.request("WPS_PBC")
@@ -129,8 +135,8 @@ def test_ap_wps_init_2ap_pin(dev, apdev):
     """Initial two-radio AP configuration with first WPS PIN Enrollee"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
-    hostapd.add_ap(apdev[0]['ifname'], params)
-    hostapd.add_ap(apdev[1]['ifname'], params)
+    hostapd.add_ap(apdev[0], params)
+    hostapd.add_ap(apdev[1], params)
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
     logger.info("WPS provisioning step")
     pin = dev[0].wps_read_pin()
@@ -159,7 +165,7 @@ def test_ap_wps_init_2ap_pin(dev, apdev):
 def test_ap_wps_init_through_wps_config(dev, apdev):
     """Initial AP configuration using wps_config command"""
     ssid = "test-wps-init-config"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
     if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
@@ -175,10 +181,25 @@ def test_ap_wps_init_through_wps_config(dev, apdev):
     dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
                    pairwise="CCMP", group="CCMP")
 
+def test_ap_wps_init_through_wps_config_2(dev, apdev):
+    """AP configuration using wps_config and wps_cred_processing=2"""
+    ssid = "test-wps-init-config"
+    hostapd.add_ap(apdev[0],
+                   { "ssid": ssid, "eap_server": "1", "wps_state": "1",
+                     "wps_cred_processing": "2" })
+    hapd = hostapd.Hostapd(apdev[0]['ifname'])
+    if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
+        raise Exception("WPS_CONFIG command failed")
+    ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
+    if "100e" not in ev:
+        raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
+
 def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
     """AP configuration using wps_config command with invalid passphrase"""
     ssid = "test-wps-init-config"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
     if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
@@ -187,7 +208,7 @@ def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
 def test_ap_wps_conf(dev, apdev):
     """WPS PBC provisioning with configured AP"""
     ssid = "test-wps-conf"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -223,7 +244,7 @@ def test_ap_wps_conf_5ghz(dev, apdev):
                    "wpa_passphrase": "12345678", "wpa": "2",
                    "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
                    "country_code": "FI", "hw_mode": "a", "channel": "36" }
-        hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+        hapd = hostapd.add_ap(apdev[0], params)
         logger.info("WPS provisioning step")
         hapd.request("WPS_PBC")
         dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
@@ -249,7 +270,7 @@ def test_ap_wps_conf_chan14(dev, apdev):
                    "wpa_passphrase": "12345678", "wpa": "2",
                    "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
                    "country_code": "JP", "hw_mode": "b", "channel": "14" }
-        hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+        hapd = hostapd.add_ap(apdev[0], params)
         logger.info("WPS provisioning step")
         hapd.request("WPS_PBC")
         dev[0].request("WPS_PBC")
@@ -271,8 +292,7 @@ def test_ap_wps_twice(dev, apdev):
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                "wpa_passphrase": "12345678", "wpa": "2",
                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
-    hostapd.add_ap(apdev[0]['ifname'], params)
-    hapd = hostapd.Hostapd(apdev[0]['ifname'])
+    hapd = hostapd.add_ap(apdev[0], params)
     logger.info("WPS provisioning step")
     hapd.request("WPS_PBC")
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
@@ -282,11 +302,9 @@ def test_ap_wps_twice(dev, apdev):
     dev[0].request("DISCONNECT")
 
     logger.info("Restart AP with different passphrase and re-run WPS")
-    hapd_global = hostapd.HostapdGlobal()
-    hapd_global.remove(apdev[0]['ifname'])
+    hostapd.remove_bss(apdev[0])
     params['wpa_passphrase'] = 'another passphrase'
-    hostapd.add_ap(apdev[0]['ifname'], params)
-    hapd = hostapd.Hostapd(apdev[0]['ifname'])
+    hapd = hostapd.add_ap(apdev[0], params)
     logger.info("WPS provisioning step")
     hapd.request("WPS_PBC")
     dev[0].dump_monitor()
@@ -299,7 +317,7 @@ def test_ap_wps_twice(dev, apdev):
 def test_ap_wps_incorrect_pin(dev, apdev):
     """WPS PIN provisioning with incorrect PIN"""
     ssid = "test-wps-incorrect-pin"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -342,7 +360,7 @@ def test_ap_wps_incorrect_pin(dev, apdev):
 def test_ap_wps_conf_pin(dev, apdev):
     """WPS PIN provisioning with configured AP"""
     ssid = "test-wps-conf-pin"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -378,10 +396,68 @@ def test_ap_wps_conf_pin(dev, apdev):
     hapd.request("WPS_PIN any " + pin)
     dev[1].wait_connected(timeout=30)
 
+def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
+    """WPS PIN provisioning with configured AP (WPA+WPA2)"""
+    ssid = "test-wps-conf-pin-mixed"
+    hostapd.add_ap(apdev[0],
+                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+                     "wpa_passphrase": "12345678", "wpa": "3",
+                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+                     "wpa_pairwise": "TKIP" })
+    hapd = hostapd.Hostapd(apdev[0]['ifname'])
+
+    logger.info("WPS provisioning step")
+    pin = dev[0].wps_read_pin()
+    hapd.request("WPS_PIN any " + pin)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
+    dev[0].dump_monitor()
+    dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
+    dev[0].wait_connected(timeout=30)
+    status = dev[0].get_status()
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
+        raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
+
+    logger.info("WPS provisioning step (auth_types=0x1b)")
+    if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
+        raise Exception("Failed to set wps_force_auth_types 0x1b")
+    pin = dev[0].wps_read_pin()
+    hapd.request("WPS_PIN any " + pin)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
+    dev[0].dump_monitor()
+    dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
+    dev[0].wait_connected(timeout=30)
+    status = dev[0].get_status()
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
+        raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
+
+    logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
+    if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
+        raise Exception("Failed to set wps_force_auth_types 0")
+    if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
+        raise Exception("Failed to set wps_force_encr_types 0")
+    pin = dev[0].wps_read_pin()
+    hapd.request("WPS_PIN any " + pin)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
+    dev[0].dump_monitor()
+    dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
+    dev[0].wait_connected(timeout=30)
+    status = dev[0].get_status()
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
+        raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
+
+    dev[0].request("SET wps_force_auth_types ")
+    dev[0].request("SET wps_force_encr_types ")
+
 def test_ap_wps_conf_pin_v1(dev, apdev):
     """WPS PIN provisioning with configured WPS v1.0 AP"""
     ssid = "test-wps-conf-pin-v1"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -407,7 +483,7 @@ def test_ap_wps_conf_pin_v1(dev, apdev):
 def test_ap_wps_conf_pin_2sta(dev, apdev):
     """Two stations trying to use WPS PIN at the same time"""
     ssid = "test-wps-conf-pin2"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -429,7 +505,7 @@ def test_ap_wps_conf_pin_2sta(dev, apdev):
 def test_ap_wps_conf_pin_timeout(dev, apdev):
     """WPS PIN provisioning with configured AP timing out PIN"""
     ssid = "test-wps-conf-pin"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -458,7 +534,7 @@ def test_ap_wps_reg_connect(dev, apdev):
     """WPS registrar using AP PIN to connect"""
     ssid = "test-wps-reg-ap-pin"
     appin = "12345670"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -481,7 +557,7 @@ def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
     """WPS registrar using AP PIN to connect (WPA+WPA2)"""
     ssid = "test-wps-reg-ap-pin"
     appin = "12345670"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "3",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -498,6 +574,38 @@ def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
     if status['key_mgmt'] != 'WPA2-PSK':
         raise Exception("Unexpected key_mgmt")
 
+def test_ap_wps_reg_override_ap_settings(dev, apdev):
+    """WPS registrar and ap_settings override"""
+    ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
+    try:
+        os.remove(ap_settings)
+    except:
+        pass
+    # Override AP Settings with values that point to another AP
+    data = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
+    data += build_wsc_attr(ATTR_SSID, "test")
+    data += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
+    data += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
+    data += build_wsc_attr(ATTR_NETWORK_KEY, '')
+    data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
+    with open(ap_settings, "w") as f:
+        f.write(data)
+    ssid = "test-wps-reg-ap-pin"
+    appin = "12345670"
+    hostapd.add_ap(apdev[0],
+                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+                     "wpa_passphrase": "12345678", "wpa": "2",
+                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+                     "ap_pin": appin, "ap_settings": ap_settings })
+    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "test" })
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
+    dev[0].wps_reg(apdev[0]['bssid'], appin)
+    ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
+    os.remove(ap_settings)
+    if ev is None:
+        raise Exception("No connection with the other AP")
+
 def check_wps_reg_failure(dev, ap, appin):
     dev.request("WPS_REG " + ap['bssid'] + " " + appin)
     ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
@@ -512,7 +620,7 @@ def test_ap_wps_random_ap_pin(dev, apdev):
     """WPS registrar using random AP PIN"""
     ssid = "test-wps-reg-random-ap-pin"
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -564,8 +672,7 @@ def test_ap_wps_random_ap_pin(dev, apdev):
     check_wps_reg_failure(dev[1], apdev[0], appin)
 
     with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
-        if "FAIL" in hapd.request("WPS_AP_PIN random 1"):
-            raise Exception("Failed to generate PIN during OOM")
+        hapd.request("WPS_AP_PIN random 1")
         hapd.request("WPS_AP_PIN disable")
 
     with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
@@ -576,7 +683,7 @@ def test_ap_wps_reg_config(dev, apdev):
     """WPS registrar configuring an AP using AP PIN"""
     ssid = "test-wps-init-ap-pin"
     appin = "12345670"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "ap_pin": appin})
     logger.info("WPS configuration step")
@@ -615,7 +722,7 @@ def test_ap_wps_reg_config_ext_processing(dev, apdev):
     appin = "12345670"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                "wps_cred_processing": "1", "ap_pin": appin}
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
     new_ssid = "wps-new-ssid"
     new_passphrase = "1234567890"
@@ -639,7 +746,7 @@ def test_ap_wps_reg_config_tkip(dev, apdev):
     skip_with_fips(dev[0])
     ssid = "test-wps-init-ap"
     appin = "12345670"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
                      "ap_pin": appin})
     logger.info("WPS configuration step")
@@ -670,7 +777,7 @@ def test_ap_wps_setup_locked(dev, apdev):
     """WPS registrar locking up AP setup on AP PIN failures"""
     ssid = "test-wps-incorrect-ap-pin"
     appin = "12345670"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -737,7 +844,7 @@ def test_ap_wps_setup_locked_timeout(dev, apdev):
     """WPS re-enabling AP PIN after timeout"""
     ssid = "test-wps-incorrect-ap-pin"
     appin = "12345670"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -772,14 +879,52 @@ def test_ap_wps_setup_locked_timeout(dev, apdev):
     if ev is None:
         raise Exception("AP PIN did not get unlocked on 60 second timeout")
 
+def test_ap_wps_setup_locked_2(dev, apdev):
+    """WPS AP configured for special ap_setup_locked=2 mode"""
+    ssid = "test-wps-ap-pin"
+    appin = "12345670"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "ap_pin": appin, "ap_setup_locked": "2" }
+    hapd = hostapd.add_ap(apdev[0], params)
+    new_ssid = "wps-new-ssid-test"
+    new_passphrase = "1234567890"
+
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[0].wps_reg(apdev[0]['bssid'], appin)
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+    hapd.dump_monitor()
+    dev[0].dump_monitor()
+    dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
+                   "CCMP", new_passphrase, no_wait=True)
+
+    ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
+    if ev is None:
+        raise Exception("hostapd did not report WPS failure")
+    if "msg=12 config_error=15" not in ev:
+        raise Exception("Unexpected failure reason (AP): " + ev)
+
+    ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
+    if ev is None:
+        raise Exception("Timeout on receiving WPS operation failure event")
+    if "CTRL-EVENT-CONNECTED" in ev:
+        raise Exception("Unexpected connection")
+    if "config_error=15" not in ev:
+        raise Exception("Unexpected failure reason (STA): " + ev)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+
 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
     """WPS PBC session overlap with two active APs"""
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
                      "wps_independent": "1"})
-    hostapd.add_ap(apdev[1]['ifname'],
+    hostapd.add_ap(apdev[1],
                    { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "123456789", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -802,7 +947,7 @@ def test_ap_wps_pbc_overlap_2ap(dev, apdev):
 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
     """WPS PBC session overlap with two active STAs"""
     ssid = "test-wps-pbc-overlap"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -840,7 +985,7 @@ def test_ap_wps_pbc_overlap_2sta(dev, apdev):
 def test_ap_wps_cancel(dev, apdev):
     """WPS AP cancelling enabled config method"""
     ssid = "test-wps-ap-cancel"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
@@ -888,7 +1033,7 @@ def _test_ap_wps_er_add_enrollee(dev, apdev):
     ssid = "wps-er-add-enrollee"
     ap_pin = "12345670"
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
                      "device_name": "Wireless AP", "manufacturer": "Company",
                      "model_name": "WAP", "model_number": "123",
@@ -1021,7 +1166,7 @@ def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
     ssid = "wps-er-add-enrollee"
     ap_pin = "12345670"
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -1093,10 +1238,75 @@ def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
     if ev is None:
         raise Exception("WPS ER did not report success")
 
+    ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
+    if ev is None:
+        raise Exception("No Enrollee STA entry timeout seen")
+
     logger.info("Stop ER")
     dev[0].dump_monitor()
     dev[0].request("WPS_ER_STOP")
 
+def test_ap_wps_er_multi_add_enrollee(dev, apdev):
+    """Multiple WPS ERs adding a new enrollee using PIN"""
+    try:
+        _test_ap_wps_er_multi_add_enrollee(dev, apdev)
+    finally:
+        for i in range(2):
+            dev[i].request("WPS_ER_STOP")
+
+def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
+    ssid = "wps-er-add-enrollee"
+    ap_pin = "12345670"
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    hostapd.add_ap(apdev[0],
+                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+                     "wpa_passphrase": "12345678", "wpa": "2",
+                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+                     "device_name": "Wireless AP", "manufacturer": "Company",
+                     "model_name": "WAP", "model_number": "123",
+                     "serial_number": "12345", "device_type": "6-0050F204-1",
+                     "os_version": "01020300",
+                     'friendly_name': "WPS AP",
+                     "config_methods": "label push_button",
+                     "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
+
+    for i in range(2):
+        dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
+        dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
+    for i in range(2):
+        dev[i].request("WPS_ER_START ifname=lo")
+    for i in range(2):
+        ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
+        if ev is None:
+            raise Exception("AP discovery timed out")
+        dev[i].dump_monitor()
+    for i in range(2):
+        dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
+    for i in range(2):
+        ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
+        if ev is None:
+            raise Exception("AP learn timed out")
+        ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
+        if ev is None:
+            raise Exception("WPS-FAIL after AP learn timed out")
+
+    time.sleep(0.1)
+
+    pin = dev[2].wps_read_pin()
+    addr = dev[2].own_addr()
+    dev[0].dump_monitor()
+    dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
+    dev[1].dump_monitor()
+    dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
+
+    dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[2].dump_monitor()
+    dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
+    ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
+    if ev is None:
+        raise Exception("Enrollee did not report success")
+    dev[2].wait_connected(timeout=15)
+
 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
     """WPS ER connected to AP and adding a new enrollee using PBC"""
     try:
@@ -1108,7 +1318,7 @@ def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
     ssid = "wps-er-add-enrollee-pbc"
     ap_pin = "12345670"
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -1179,7 +1389,7 @@ def _test_ap_wps_er_pbc_overlap(dev, apdev):
     ssid = "wps-er-add-enrollee-pbc"
     ap_pin = "12345670"
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -1254,7 +1464,7 @@ def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
     ssid = "wps-er-add-enrollee-pbc"
     ap_pin = "12345670"
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -1308,7 +1518,7 @@ def _test_ap_wps_er_config_ap(dev, apdev):
     ssid = "wps-er-ap-config"
     ap_pin = "12345670"
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -1371,7 +1581,7 @@ def _test_ap_wps_er_cache_ap_settings(dev, apdev):
                "os_version": "01020300",
                "config_methods": "label push_button",
                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
     id = int(dev[0].list_networks()[0]['id'])
@@ -1403,7 +1613,7 @@ def _test_ap_wps_er_cache_ap_settings(dev, apdev):
         if ev is None:
             raise Exception("AP removal or disconnection timed out")
 
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     for i in range(2):
         ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
                                timeout=15)
@@ -1430,114 +1640,378 @@ def _test_ap_wps_er_cache_ap_settings(dev, apdev):
     dev[0].dump_monitor()
     dev[0].request("WPS_ER_STOP")
 
-def test_ap_wps_fragmentation(dev, apdev):
-    """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
-    ssid = "test-wps-fragmentation"
-    appin = "12345670"
-    hostapd.add_ap(apdev[0]['ifname'],
-                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
-                     "wpa_passphrase": "12345678", "wpa": "3",
-                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
-                     "wpa_pairwise": "TKIP", "ap_pin": appin,
-                     "fragment_size": "50" })
-    hapd = hostapd.Hostapd(apdev[0]['ifname'])
-    logger.info("WPS provisioning step (PBC)")
-    hapd.request("WPS_PBC")
-    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
-    dev[0].dump_monitor()
-    dev[0].request("SET wps_fragment_size 50")
-    dev[0].request("WPS_PBC " + apdev[0]['bssid'])
-    dev[0].wait_connected(timeout=30)
-    status = dev[0].get_status()
-    if status['wpa_state'] != 'COMPLETED':
-        raise Exception("Not fully connected")
-    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
-        raise Exception("Unexpected encryption configuration")
-    if status['key_mgmt'] != 'WPA2-PSK':
-        raise Exception("Unexpected key_mgmt")
+def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
+    """WPS ER caching AP settings (OOM)"""
+    try:
+        _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
+    finally:
+        dev[0].request("WPS_ER_STOP")
 
-    logger.info("WPS provisioning step (PIN)")
-    pin = dev[1].wps_read_pin()
-    hapd.request("WPS_PIN any " + pin)
-    dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
-    dev[1].request("SET wps_fragment_size 50")
-    dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
-    dev[1].wait_connected(timeout=30)
-    status = dev[1].get_status()
-    if status['wpa_state'] != 'COMPLETED':
-        raise Exception("Not fully connected")
-    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
-        raise Exception("Unexpected encryption configuration")
-    if status['key_mgmt'] != 'WPA2-PSK':
-        raise Exception("Unexpected key_mgmt")
+def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
+    ssid = "wps-er-add-enrollee"
+    ap_pin = "12345670"
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "device_name": "Wireless AP", "manufacturer": "Company",
+               "model_name": "WAP", "model_number": "123",
+               "serial_number": "12345", "device_type": "6-0050F204-1",
+               "os_version": "01020300",
+               "config_methods": "label push_button",
+               "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
+    id = int(dev[0].list_networks()[0]['id'])
+    dev[0].set_network(id, "scan_freq", "2412")
 
-    logger.info("WPS connection as registrar")
-    dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
-    dev[2].request("SET wps_fragment_size 50")
-    dev[2].wps_reg(apdev[0]['bssid'], appin)
-    status = dev[2].get_status()
-    if status['wpa_state'] != 'COMPLETED':
-        raise Exception("Not fully connected")
-    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
-        raise Exception("Unexpected encryption configuration")
-    if status['key_mgmt'] != 'WPA2-PSK':
-        raise Exception("Unexpected key_mgmt")
+    dev[0].request("WPS_ER_START ifname=lo")
+    ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
+    if ev is None:
+        raise Exception("AP discovery timed out")
+    if ap_uuid not in ev:
+        raise Exception("Expected AP UUID not found")
 
-def test_ap_wps_new_version_sta(dev, apdev):
-    """WPS compatibility with new version number on the station"""
-    ssid = "test-wps-ver"
-    hostapd.add_ap(apdev[0]['ifname'],
-                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
-                     "wpa_passphrase": "12345678", "wpa": "2",
-                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
-    hapd = hostapd.Hostapd(apdev[0]['ifname'])
-    logger.info("WPS provisioning step")
-    hapd.request("WPS_PBC")
-    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
     dev[0].dump_monitor()
-    dev[0].request("SET wps_version_number 0x43")
-    dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
-    dev[0].request("WPS_PBC " + apdev[0]['bssid'])
-    dev[0].wait_connected(timeout=30)
+    dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
+    ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
+    if ev is None:
+        raise Exception("AP learn timed out")
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
+    if ev is None:
+        raise Exception("WPS-FAIL after AP learn timed out")
+    time.sleep(0.1)
 
-def test_ap_wps_new_version_ap(dev, apdev):
-    """WPS compatibility with new version number on the AP"""
-    ssid = "test-wps-ver"
-    hostapd.add_ap(apdev[0]['ifname'],
-                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
-                     "wpa_passphrase": "12345678", "wpa": "2",
-                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
-    hapd = hostapd.Hostapd(apdev[0]['ifname'])
-    logger.info("WPS provisioning step")
-    if "FAIL" in hapd.request("SET wps_version_number 0x43"):
-        raise Exception("Failed to enable test functionality")
-    hapd.request("WPS_PBC")
-    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
-    dev[0].dump_monitor()
-    dev[0].request("WPS_PBC " + apdev[0]['bssid'])
-    dev[0].wait_connected(timeout=30)
-    hapd.request("SET wps_version_number 0x20")
+    with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
+        hapd.disable()
 
-def test_ap_wps_check_pin(dev, apdev):
-    """Verify PIN checking through control interface"""
-    hostapd.add_ap(apdev[0]['ifname'],
-                   { "ssid": "wps", "eap_server": "1", "wps_state": "2",
-                     "wpa_passphrase": "12345678", "wpa": "2",
-                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
-    hapd = hostapd.Hostapd(apdev[0]['ifname'])
-    for t in [ ("12345670", "12345670"),
-               ("12345678", "FAIL-CHECKSUM"),
-               ("12345", "FAIL"),
-               ("123456789", "FAIL"),
-               ("1234-5670", "12345670"),
-               ("1234 5670", "12345670"),
-               ("1-2.3:4 5670", "12345670") ]:
-        res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
-        res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
-        if res != res2:
-            raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
-        if res != t[1]:
-            raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
+        for i in range(2):
+            ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
+                                     "CTRL-EVENT-DISCONNECTED" ],
+                                   timeout=15)
+            if ev is None:
+                raise Exception("AP removal or disconnection timed out")
+
+        hapd = hostapd.add_ap(apdev[0], params)
+        for i in range(2):
+            ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
+                                   timeout=15)
+            if ev is None:
+                raise Exception("AP discovery or connection timed out")
+
+    dev[0].request("WPS_ER_STOP")
+
+def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
+    """WPS ER caching AP settings (OOM 2)"""
+    try:
+        _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
+    finally:
+        dev[0].request("WPS_ER_STOP")
+
+def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
+    ssid = "wps-er-add-enrollee"
+    ap_pin = "12345670"
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "device_name": "Wireless AP", "manufacturer": "Company",
+               "model_name": "WAP", "model_number": "123",
+               "serial_number": "12345", "device_type": "6-0050F204-1",
+               "os_version": "01020300",
+               "config_methods": "label push_button",
+               "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
+    id = int(dev[0].list_networks()[0]['id'])
+    dev[0].set_network(id, "scan_freq", "2412")
+
+    dev[0].request("WPS_ER_START ifname=lo")
+    ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
+    if ev is None:
+        raise Exception("AP discovery timed out")
+    if ap_uuid not in ev:
+        raise Exception("Expected AP UUID not found")
+
+    dev[0].dump_monitor()
+    dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
+    ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
+    if ev is None:
+        raise Exception("AP learn timed out")
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
+    if ev is None:
+        raise Exception("WPS-FAIL after AP learn timed out")
+    time.sleep(0.1)
+
+    with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
+        hapd.disable()
+
+        for i in range(2):
+            ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
+                                     "CTRL-EVENT-DISCONNECTED" ],
+                                   timeout=15)
+            if ev is None:
+                raise Exception("AP removal or disconnection timed out")
+
+        hapd = hostapd.add_ap(apdev[0], params)
+        for i in range(2):
+            ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
+                                   timeout=15)
+            if ev is None:
+                raise Exception("AP discovery or connection timed out")
+
+    dev[0].request("WPS_ER_STOP")
+
+def test_ap_wps_er_subscribe_oom(dev, apdev):
+    """WPS ER subscribe OOM"""
+    try:
+        _test_ap_wps_er_subscribe_oom(dev, apdev)
+    finally:
+        dev[0].request("WPS_ER_STOP")
+
+def _test_ap_wps_er_subscribe_oom(dev, apdev):
+    ssid = "wps-er-add-enrollee"
+    ap_pin = "12345670"
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "device_name": "Wireless AP", "manufacturer": "Company",
+               "model_name": "WAP", "model_number": "123",
+               "serial_number": "12345", "device_type": "6-0050F204-1",
+               "os_version": "01020300",
+               "config_methods": "label push_button",
+               "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
+    id = int(dev[0].list_networks()[0]['id'])
+    dev[0].set_network(id, "scan_freq", "2412")
+
+    with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
+        dev[0].request("WPS_ER_START ifname=lo")
+        for i in range(50):
+            res = dev[0].request("GET_ALLOC_FAIL")
+            if res.startswith("0:"):
+                break
+            time.sleep(0.1)
+        ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
+        if ev:
+            raise Exception("Unexpected AP discovery during OOM")
+
+    dev[0].request("WPS_ER_STOP")
+
+def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
+    """WPS ER SetSelectedRegistrar OOM"""
+    try:
+        _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
+    finally:
+        dev[0].request("WPS_ER_STOP")
+
+def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
+    ssid = "wps-er-add-enrollee"
+    ap_pin = "12345670"
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "device_name": "Wireless AP", "manufacturer": "Company",
+               "model_name": "WAP", "model_number": "123",
+               "serial_number": "12345", "device_type": "6-0050F204-1",
+               "os_version": "01020300",
+               "config_methods": "label push_button",
+               "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
+
+    dev[0].request("WPS_ER_START ifname=lo")
+    ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
+    if ev is None:
+        raise Exception("AP not discovered")
+
+    dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
+    ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
+    if ev is None:
+        raise Exception("AP learn timed out")
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
+    if ev is None:
+        raise Exception("WPS-FAIL timed out")
+    time.sleep(0.1)
+
+    for func in [ "http_client_url_parse;wps_er_send_set_sel_reg",
+                  "wps_er_soap_hdr;wps_er_send_set_sel_reg",
+                  "http_client_addr;wps_er_send_set_sel_reg",
+                  "wpabuf_alloc;wps_er_set_sel_reg" ]:
+        with alloc_fail(dev[0], 1, func):
+            if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
+                raise Exception("WPS_ER_PBC failed")
+            ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
+            if ev is None:
+                raise Exception("WPS-PBC-ACTIVE not seen")
+
+    dev[0].request("WPS_ER_STOP")
+
+def test_ap_wps_er_learn_oom(dev, apdev):
+    """WPS ER learn OOM"""
+    try:
+        _test_ap_wps_er_learn_oom(dev, apdev)
+    finally:
+        dev[0].request("WPS_ER_STOP")
+
+def _test_ap_wps_er_learn_oom(dev, apdev):
+    ssid = "wps-er-add-enrollee"
+    ap_pin = "12345670"
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "device_name": "Wireless AP", "manufacturer": "Company",
+               "model_name": "WAP", "model_number": "123",
+               "serial_number": "12345", "device_type": "6-0050F204-1",
+               "os_version": "01020300",
+               "config_methods": "label push_button",
+               "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
+    hapd = hostapd.add_ap(apdev[0], params)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
+
+    dev[0].request("WPS_ER_START ifname=lo")
+    ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
+    if ev is None:
+        raise Exception("AP not discovered")
+
+    for func in [ "wps_er_http_put_message_cb",
+                  "xml_get_base64_item;wps_er_http_put_message_cb",
+                  "http_client_url_parse;wps_er_ap_put_message",
+                  "wps_er_soap_hdr;wps_er_ap_put_message",
+                  "http_client_addr;wps_er_ap_put_message" ]:
+        with alloc_fail(dev[0], 1, func):
+            dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
+            ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
+            if ev is not None:
+                raise Exception("AP learn succeeded during OOM")
+
+    dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
+    ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
+    if ev is None:
+        raise Exception("AP learn did not succeed")
+
+    if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
+        raise Exception("WPS_ER_LEARN for unknown AP accepted")
+
+    dev[0].request("WPS_ER_STOP")
+
+def test_ap_wps_fragmentation(dev, apdev):
+    """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
+    ssid = "test-wps-fragmentation"
+    appin = "12345670"
+    hostapd.add_ap(apdev[0],
+                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+                     "wpa_passphrase": "12345678", "wpa": "3",
+                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+                     "wpa_pairwise": "TKIP", "ap_pin": appin,
+                     "fragment_size": "50" })
+    hapd = hostapd.Hostapd(apdev[0]['ifname'])
+    logger.info("WPS provisioning step (PBC)")
+    hapd.request("WPS_PBC")
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[0].dump_monitor()
+    dev[0].request("SET wps_fragment_size 50")
+    dev[0].request("WPS_PBC " + apdev[0]['bssid'])
+    dev[0].wait_connected(timeout=30)
+    status = dev[0].get_status()
+    if status['wpa_state'] != 'COMPLETED':
+        raise Exception("Not fully connected")
+    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
+        raise Exception("Unexpected encryption configuration")
+    if status['key_mgmt'] != 'WPA2-PSK':
+        raise Exception("Unexpected key_mgmt")
+
+    logger.info("WPS provisioning step (PIN)")
+    pin = dev[1].wps_read_pin()
+    hapd.request("WPS_PIN any " + pin)
+    dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[1].request("SET wps_fragment_size 50")
+    dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
+    dev[1].wait_connected(timeout=30)
+    status = dev[1].get_status()
+    if status['wpa_state'] != 'COMPLETED':
+        raise Exception("Not fully connected")
+    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
+        raise Exception("Unexpected encryption configuration")
+    if status['key_mgmt'] != 'WPA2-PSK':
+        raise Exception("Unexpected key_mgmt")
+
+    logger.info("WPS connection as registrar")
+    dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[2].request("SET wps_fragment_size 50")
+    dev[2].wps_reg(apdev[0]['bssid'], appin)
+    status = dev[2].get_status()
+    if status['wpa_state'] != 'COMPLETED':
+        raise Exception("Not fully connected")
+    if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
+        raise Exception("Unexpected encryption configuration")
+    if status['key_mgmt'] != 'WPA2-PSK':
+        raise Exception("Unexpected key_mgmt")
+
+def test_ap_wps_new_version_sta(dev, apdev):
+    """WPS compatibility with new version number on the station"""
+    ssid = "test-wps-ver"
+    hostapd.add_ap(apdev[0],
+                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+                     "wpa_passphrase": "12345678", "wpa": "2",
+                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
+    hapd = hostapd.Hostapd(apdev[0]['ifname'])
+    logger.info("WPS provisioning step")
+    hapd.request("WPS_PBC")
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
+    dev[0].dump_monitor()
+    dev[0].request("SET wps_version_number 0x43")
+    dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
+    dev[0].request("WPS_PBC " + apdev[0]['bssid'])
+    dev[0].wait_connected(timeout=30)
+
+def test_ap_wps_new_version_ap(dev, apdev):
+    """WPS compatibility with new version number on the AP"""
+    ssid = "test-wps-ver"
+    hostapd.add_ap(apdev[0],
+                   { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+                     "wpa_passphrase": "12345678", "wpa": "2",
+                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
+    hapd = hostapd.Hostapd(apdev[0]['ifname'])
+    logger.info("WPS provisioning step")
+    if "FAIL" in hapd.request("SET wps_version_number 0x43"):
+        raise Exception("Failed to enable test functionality")
+    hapd.request("WPS_PBC")
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
+    dev[0].dump_monitor()
+    dev[0].request("WPS_PBC " + apdev[0]['bssid'])
+    dev[0].wait_connected(timeout=30)
+    hapd.request("SET wps_version_number 0x20")
+
+def test_ap_wps_check_pin(dev, apdev):
+    """Verify PIN checking through control interface"""
+    hostapd.add_ap(apdev[0],
+                   { "ssid": "wps", "eap_server": "1", "wps_state": "2",
+                     "wpa_passphrase": "12345678", "wpa": "2",
+                     "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
+    hapd = hostapd.Hostapd(apdev[0]['ifname'])
+    for t in [ ("12345670", "12345670"),
+               ("12345678", "FAIL-CHECKSUM"),
+               ("12345", "FAIL"),
+               ("123456789", "FAIL"),
+               ("1234-5670", "12345670"),
+               ("1234 5670", "12345670"),
+               ("1-2.3:4 5670", "12345670") ]:
+        res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
+        res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
+        if res != res2:
+            raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
+        if res != t[1]:
+            raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
 
     if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
         raise Exception("Unexpected WPS_CHECK_PIN success")
@@ -1554,7 +2028,7 @@ def test_ap_wps_wep_config(dev, apdev):
     """WPS 2.0 AP rejecting WEP configuration"""
     ssid = "test-wps-config"
     appin = "12345670"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "ap_pin": appin})
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
@@ -1577,7 +2051,7 @@ def test_ap_wps_wep_config(dev, apdev):
 def test_ap_wps_wep_enroll(dev, apdev):
     """WPS 2.0 STA rejecting WEP configuration"""
     ssid = "test-wps-wep"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
@@ -1601,7 +2075,7 @@ def test_ap_wps_ie_fragmentation(dev, apdev):
                "model_name": "1234567890abcdef1234567890abcdef",
                "model_number": "1234567890abcdef1234567890abcdef",
                "serial_number": "1234567890abcdef1234567890abcdef" }
-    hostapd.add_ap(apdev[0]['ifname'], params)
+    hostapd.add_ap(apdev[0], params)
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
     hapd.request("WPS_PBC")
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
@@ -1647,6 +2121,7 @@ def test_ap_wps_per_station_psk(dev, apdev):
     except:
         pass
 
+    hapd = None
     try:
         with open(pskfile, "w") as f:
             f.write("# WPA PSKs\n")
@@ -1655,7 +2130,7 @@ def test_ap_wps_per_station_psk(dev, apdev):
                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
                    "rsn_pairwise": "CCMP", "ap_pin": appin,
                    "wpa_psk_file": pskfile }
-        hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+        hapd = hostapd.add_ap(apdev[0], params)
 
         logger.info("First enrollee")
         hapd.request("WPS_PBC")
@@ -1699,6 +2174,14 @@ def test_ap_wps_per_station_psk(dev, apdev):
             raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
     finally:
         os.remove(pskfile)
+        if hapd:
+            dev[0].request("DISCONNECT")
+            dev[1].request("DISCONNECT")
+            dev[2].request("DISCONNECT")
+            hapd.disable()
+            dev[0].flush_scan_cache()
+            dev[1].flush_scan_cache()
+            dev[2].flush_scan_cache()
 
 def test_ap_wps_per_station_psk_failure(dev, apdev):
     """WPS PBC provisioning with per-station PSK (file not writable)"""
@@ -1721,7 +2204,7 @@ def test_ap_wps_per_station_psk_failure(dev, apdev):
                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
                    "rsn_pairwise": "CCMP", "ap_pin": appin,
                    "wpa_psk_file": pskfile }
-        hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+        hapd = hostapd.add_ap(apdev[0], params)
         if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
             raise Exception("Failed to set wpa_psk_file")
 
@@ -1754,7 +2237,7 @@ def test_ap_wps_pin_request_file(dev, apdev):
     pinfile = "/tmp/ap_wps_pin_request_file.log"
     if os.path.exists(pinfile):
         os.remove(pinfile)
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wps_pin_requests": pinfile,
                      "wpa_passphrase": "12345678", "wpa": "2",
@@ -1801,7 +2284,7 @@ def test_ap_wps_auto_setup_with_config_file(dev, apdev):
             f.write("ssid=wps\n")
             f.write("eap_server=1\n")
             f.write("wps_state=1\n")
-        hostapd.add_bss('phy3', ifname, conffile)
+        hostapd.add_bss(apdev[0], ifname, conffile)
         hapd = hostapd.Hostapd(ifname)
         hapd.request("WPS_PBC")
         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
@@ -1832,7 +2315,7 @@ def test_ap_wps_pbc_timeout(dev, apdev, params):
     if not params['long']:
         raise HwsimSkip("Skip test case with long duration due to --long not specified")
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    hapd = add_ssdp_ap(apdev[0], ap_uuid)
 
     location = ssdp_get_location(ap_uuid)
     urls = upnp_get_urls(location)
@@ -1936,7 +2419,7 @@ VFi5hrLk
     if ev is None:
         raise Exception("WPS-TIMEOUT not reported")
 
-def add_ssdp_ap(ifname, ap_uuid):
+def add_ssdp_ap(ap, ap_uuid):
     ssid = "wps-ssdp"
     ap_pin = "12345670"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
@@ -1953,7 +2436,7 @@ def add_ssdp_ap(ifname, ap_uuid):
                "model_description": "Wireless Access Point",
                "model_url": "http://www.example.com/model/",
                "upc": "123456789012" }
-    return hostapd.add_ap(ifname, params)
+    return hostapd.add_ap(ap, params)
 
 def ssdp_send(msg, no_recv=False):
     socket.setdefaulttimeout(1)
@@ -1966,7 +2449,7 @@ def ssdp_send(msg, no_recv=False):
         return None
     return sock.recv(1000)
 
-def ssdp_send_msearch(st):
+def ssdp_send_msearch(st, no_recv=False):
     msg = '\r\n'.join([
             'M-SEARCH * HTTP/1.1',
             'HOST: 239.255.255.250:1900',
@@ -1974,12 +2457,12 @@ def ssdp_send_msearch(st):
             'MAN: "ssdp:discover"',
             'ST: ' + st,
             '', ''])
-    return ssdp_send(msg)
+    return ssdp_send(msg, no_recv=no_recv)
 
 def test_ap_wps_ssdp_msearch(dev, apdev):
     """WPS AP and SSDP M-SEARCH messages"""
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    add_ssdp_ap(apdev[0], ap_uuid)
 
     msg = '\r\n'.join([
             'M-SEARCH * HTTP/1.1',
@@ -2017,7 +2500,7 @@ def test_ap_wps_ssdp_msearch(dev, apdev):
 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
     """WPS AP and invalid SSDP M-SEARCH messages"""
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    add_ssdp_ap(apdev[0], ap_uuid)
 
     socket.setdefaulttimeout(1)
     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
@@ -2189,7 +2672,7 @@ def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
 def test_ap_wps_ssdp_burst(dev, apdev):
     """WPS AP and SSDP burst"""
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    add_ssdp_ap(apdev[0], ap_uuid)
 
     msg = '\r\n'.join([
             'M-SEARCH * HTTP/1.1',
@@ -2254,7 +2737,9 @@ def upnp_get_urls(location):
     res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
     return res
 
-def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
+def upnp_soap_action(conn, path, action, include_soap_action=True,
+                     soap_action_override=None, newmsg=None, neweventtype=None,
+                     neweventmac=None):
     soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
     wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
     ET.register_namespace('soapenv', soapns)
@@ -2264,6 +2749,15 @@ def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_o
     root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
     body = ET.SubElement(root, "{%s}Body" % soapns)
     act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
+    if newmsg:
+        msg = ET.SubElement(act, "NewMessage")
+        msg.text = base64.b64encode(newmsg)
+    if neweventtype:
+        msg = ET.SubElement(act, "NewWLANEventType")
+        msg.text = neweventtype
+    if neweventmac:
+        msg = ET.SubElement(act, "NewWLANEventMAC")
+        msg.text = neweventmac
     tree = ET.ElementTree(root)
     soap = StringIO.StringIO()
     tree.write(soap, xml_declaration=True, encoding='utf-8')
@@ -2279,7 +2773,7 @@ def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_o
 def test_ap_wps_upnp(dev, apdev):
     """WPS AP and UPnP operations"""
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    add_ssdp_ap(apdev[0], ap_uuid)
 
     location = ssdp_get_location(ap_uuid)
     urls = upnp_get_urls(location)
@@ -2361,7 +2855,7 @@ def test_ap_wps_upnp(dev, apdev):
 def test_ap_wps_upnp_subscribe(dev, apdev):
     """WPS AP and UPnP event subscription"""
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    hapd = add_ssdp_ap(apdev[0], ap_uuid)
 
     location = ssdp_get_location(ap_uuid)
     urls = upnp_get_urls(location)
@@ -2706,10 +3200,77 @@ def test_ap_wps_upnp_subscribe(dev, apdev):
         if "FAIL" not in hapd.request("ENABLE"):
             raise Exception("ENABLE succeeded during OOM")
 
+def test_ap_wps_upnp_subscribe_events(dev, apdev):
+    """WPS AP and UPnP event subscription and many events"""
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    hapd = add_ssdp_ap(apdev[0], ap_uuid)
+
+    location = ssdp_get_location(ap_uuid)
+    urls = upnp_get_urls(location)
+    eventurl = urlparse.urlparse(urls['event_sub_url'])
+
+    class WPSERHTTPServer(SocketServer.StreamRequestHandler):
+        def handle(self):
+            data = self.rfile.readline().strip()
+            logger.debug(data)
+            self.wfile.write(gen_wps_event())
+
+    server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
+    server.timeout = 1
+
+    url = urlparse.urlparse(location)
+    conn = httplib.HTTPConnection(url.netloc)
+
+    headers = { "callback": '<http://127.0.0.1:12345/event>',
+                "NT": "upnp:event",
+                "timeout": "Second-1234" }
+    conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
+    resp = conn.getresponse()
+    if resp.status != 200:
+        raise Exception("Unexpected HTTP response: %d" % resp.status)
+    sid = resp.getheader("sid")
+    logger.debug("Subscription SID " + sid)
+
+    # Fetch the first event message
+    server.handle_request()
+
+    # Force subscription event queue to reach the maximum length by generating
+    # new proxied events without the ER fetching any of the pending events.
+    dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
+    for i in range(16):
+        dev[1].dump_monitor()
+        dev[2].dump_monitor()
+        dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
+        dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
+        dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
+        dev[1].request("WPS_CANCEL")
+        dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
+        dev[2].request("WPS_CANCEL")
+        if i % 4 == 1:
+            time.sleep(1)
+        else:
+            time.sleep(0.1)
+
+    hapd.request("WPS_PIN any 12345670")
+    dev[1].dump_monitor()
+    dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
+    ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
+    if ev is None:
+        raise Exception("WPS success not reported")
+
+    # Close the WPS ER HTTP server without fetching all the pending events.
+    # This tests hostapd code path that clears subscription and the remaining
+    # event queue when the interface is deinitialized.
+    server.handle_request()
+    server.server_close()
+
+    dev[1].wait_connected()
+
 def test_ap_wps_upnp_http_proto(dev, apdev):
     """WPS AP and UPnP/HTTP protocol testing"""
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    add_ssdp_ap(apdev[0], ap_uuid)
 
     location = ssdp_get_location(ap_uuid)
 
@@ -2808,7 +3369,7 @@ def test_ap_wps_upnp_http_proto(dev, apdev):
 def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
     """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    add_ssdp_ap(apdev[0], ap_uuid)
 
     location = ssdp_get_location(ap_uuid)
 
@@ -2871,7 +3432,7 @@ def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
 def test_ap_wps_disabled(dev, apdev):
     """WPS operations while WPS is disabled"""
     ssid = "test-wps-disabled"
-    hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
+    hostapd.add_ap(apdev[0], { "ssid": ssid })
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
     if "FAIL" not in hapd.request("WPS_PBC"):
         raise Exception("WPS_PBC succeeded unexpectedly")
@@ -2881,7 +3442,7 @@ def test_ap_wps_disabled(dev, apdev):
 def test_ap_wps_mixed_cred(dev, apdev):
     """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
     ssid = "test-wps-wep"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
@@ -2905,13 +3466,13 @@ def test_ap_wps_mixed_cred(dev, apdev):
 def test_ap_wps_while_connected(dev, apdev):
     """WPS PBC provisioning while connected to another AP"""
     ssid = "test-wps-conf"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
 
-    hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
+    hostapd.add_ap(apdev[1], { "ssid": "open" })
     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
 
     logger.info("WPS provisioning step")
@@ -2926,13 +3487,13 @@ def test_ap_wps_while_connected(dev, apdev):
 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
     """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
     ssid = "test-wps-conf"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
 
-    hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
+    hostapd.add_ap(apdev[1], { "ssid": "open" })
 
     try:
         dev[0].request("STA_AUTOCONNECT 0")
@@ -2952,7 +3513,7 @@ def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
 def test_ap_wps_from_event(dev, apdev):
     """WPS PBC event on AP to enable PBC"""
     ssid = "test-wps-conf"
-    hapd = hostapd.add_ap(apdev[0]['ifname'],
+    hapd = hostapd.add_ap(apdev[0],
                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                             "wpa_passphrase": "12345678", "wpa": "2",
                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -2975,7 +3536,7 @@ def test_ap_wps_from_event(dev, apdev):
 def test_ap_wps_ap_scan_2(dev, apdev):
     """AP_SCAN 2 for WPS"""
     ssid = "test-wps-conf"
-    hapd = hostapd.add_ap(apdev[0]['ifname'],
+    hapd = hostapd.add_ap(apdev[0],
                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                             "wpa_passphrase": "12345678", "wpa": "2",
                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -2983,27 +3544,31 @@ def test_ap_wps_ap_scan_2(dev, apdev):
 
     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
+    wpas.dump_monitor()
 
     if "OK" not in wpas.request("AP_SCAN 2"):
         raise Exception("Failed to set AP_SCAN 2")
 
     wpas.flush_scan_cache()
     wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
+    wpas.dump_monitor()
     wpas.request("WPS_PBC " + apdev[0]['bssid'])
     ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
     if ev is None:
         raise Exception("WPS-SUCCESS event timed out")
     wpas.wait_connected(timeout=30)
+    wpas.dump_monitor()
     wpas.request("DISCONNECT")
     wpas.request("BSS_FLUSH 0")
     wpas.dump_monitor()
     wpas.request("REASSOCIATE")
     wpas.wait_connected(timeout=30)
+    wpas.dump_monitor()
 
 def test_ap_wps_eapol_workaround(dev, apdev):
     """EAPOL workaround code path for 802.1X header length mismatch"""
     ssid = "test-wps"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
     hapd = hostapd.Hostapd(apdev[0]['ifname'])
     bssid = apdev[0]['bssid']
@@ -3023,13 +3588,13 @@ def test_ap_wps_eapol_workaround(dev, apdev):
 def test_ap_wps_iteration(dev, apdev):
     """WPS PIN and iterate through APs without selected registrar"""
     ssid = "test-wps-conf"
-    hapd = hostapd.add_ap(apdev[0]['ifname'],
+    hapd = hostapd.add_ap(apdev[0],
                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                             "wpa_passphrase": "12345678", "wpa": "2",
                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
 
     ssid2 = "test-wps-conf2"
-    hapd2 = hostapd.add_ap(apdev[1]['ifname'],
+    hapd2 = hostapd.add_ap(apdev[1],
                            { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
                              "wpa_passphrase": "12345678", "wpa": "2",
                              "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -3065,7 +3630,7 @@ def test_ap_wps_iteration(dev, apdev):
 def test_ap_wps_iteration_error(dev, apdev):
     """WPS AP iteration on no Selected Registrar and error case with an AP"""
     ssid = "test-wps-conf-pin"
-    hapd = hostapd.add_ap(apdev[0]['ifname'],
+    hapd = hostapd.add_ap(apdev[0],
                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                             "wpa_passphrase": "12345678", "wpa": "2",
                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -3091,7 +3656,7 @@ def test_ap_wps_iteration_error(dev, apdev):
     # a case with an incorrectly behaving WPS AP.
 
     # Start the real target AP and activate registrar on it.
-    hapd2 = hostapd.add_ap(apdev[1]['ifname'],
+    hapd2 = hostapd.add_ap(apdev[1],
                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                             "wpa_passphrase": "12345678", "wpa": "2",
                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -3110,7 +3675,7 @@ def test_ap_wps_iteration_error(dev, apdev):
 def test_ap_wps_priority(dev, apdev):
     """WPS PIN provisioning with configured AP and wps_priority"""
     ssid = "test-wps-conf-pin"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -3134,10 +3699,10 @@ def test_ap_wps_priority(dev, apdev):
 def test_ap_wps_and_non_wps(dev, apdev):
     """WPS and non-WPS AP in single hostapd process"""
     params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
 
     params = { "ssid": "no wps" }
-    hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
+    hapd2 = hostapd.add_ap(apdev[1], params)
 
     appin = hapd.request("WPS_AP_PIN random")
     if "FAIL" in appin:
@@ -3154,7 +3719,7 @@ def test_ap_wps_init_oom(dev, apdev):
     """Initial AP configuration and OOM during PSK generation"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
 
     with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
         pin = dev[0].wps_read_pin()
@@ -3179,7 +3744,7 @@ def _test_ap_wps_er_oom(dev, apdev):
     ssid = "wps-er-ap-config"
     ap_pin = "12345670"
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
@@ -3231,13 +3796,19 @@ def _test_ap_wps_er_init_oom(dev, apdev):
     with alloc_fail(dev[0], 2, "http_server_init"):
         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
             raise Exception("WPS_ER_START succeeded during OOM")
-    with alloc_fail(dev[0], 1, "eloop_register_sock;wps_er_ssdp_init"):
+    with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
             raise Exception("WPS_ER_START succeeded during OOM")
     with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
             raise Exception("WPS_ER_START succeeded during os_get_random failure")
 
+def test_ap_wps_er_init_fail(dev, apdev):
+    """WPS ER init failure"""
+    if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
+        dev[0].request("WPS_ER_STOP")
+        raise Exception("WPS_ER_START with non-existing ifname succeeded")
+
 def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
     """WPS events and wpa_cli action script"""
     logdir = os.path.abspath(test_params['logdir'])
@@ -3257,7 +3828,7 @@ def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
              stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
 
     ssid = "test-wps-conf"
-    hostapd.add_ap(apdev[0]['ifname'],
+    hostapd.add_ap(apdev[0],
                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                      "wpa_passphrase": "12345678", "wpa": "2",
                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
@@ -3561,7 +4132,7 @@ def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
     finally:
             dev.request("WPS_ER_STOP")
 
-def send_wlanevent(url, uuid, data):
+def send_wlanevent(url, uuid, data, no_response=False):
     conn = httplib.HTTPConnection(url.netloc)
     payload = '''<?xml version="1.0" encoding="utf-8"?>
 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
@@ -3578,6 +4149,12 @@ def send_wlanevent(url, uuid, data):
                 "SEQ": "0",
                 "Content-Length": str(len(payload)) }
     conn.request("NOTIFY", url.path, payload, headers)
+    if no_response:
+        try:
+            conn.getresponse()
+        except Exception, e:
+            pass
+        return
     resp = conn.getresponse()
     if resp.status != 200:
         raise Exception("Unexpected HTTP response: %d" % resp.status)
@@ -3865,7 +4442,7 @@ RGV2aWNlIEEQSQAGADcqAAEg
     logger.info("OOM in HTTP server")
     for func in [ "http_request_init", "httpread_create",
                   "eloop_register_timeout;httpread_create",
-                  "eloop_register_sock;httpread_create",
+                  "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
                   "httpread_hdr_analyze" ]:
         with alloc_fail(dev[0], 1, func):
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
@@ -3955,6 +4532,59 @@ RGV2aWNlIEEQSQAGADcqAAEg
         with alloc_fail(dev[0], 1, func):
             send_wlanevent(url, uuid, m1)
 
+    with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
+        send_wlanevent(url, uuid, m1, no_response=True)
+
+    with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
+        url2 = urlparse.urlparse(wps_event_url.replace('/event/', '/notfound/'))
+        send_wlanevent(url2, uuid, m1, no_response=True)
+
+    logger.info("EAP message: M1")
+    data = '\x0202:11:22:00:00:00'
+    data += '\x10\x22\x00\x01\x04'
+    data += '\x10\x47\x00\x10' + 16*'\x00'
+    data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
+    data += '\x10\x1a\x00\x10' + 16*'\x00'
+    data += '\x10\x32\x00\xc0' + 192*'\x00'
+    data += '\x10\x04\x00\x02\x00\x00'
+    data += '\x10\x10\x00\x02\x00\x00'
+    data += '\x10\x0d\x00\x01\x00'
+    data += '\x10\x08\x00\x02\x00\x00'
+    data += '\x10\x44\x00\x01\x00'
+    data += '\x10\x21\x00\x00'
+    data += '\x10\x23\x00\x00'
+    data += '\x10\x24\x00\x00'
+    data += '\x10\x42\x00\x00'
+    data += '\x10\x54\x00\x08' + 8*'\x00'
+    data += '\x10\x11\x00\x00'
+    data += '\x10\x3c\x00\x01\x00'
+    data += '\x10\x02\x00\x02\x00\x00'
+    data += '\x10\x12\x00\x02\x00\x00'
+    data += '\x10\x09\x00\x02\x00\x00'
+    data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
+    dev[0].dump_monitor()
+    with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
+        send_wlanevent(url, uuid, data)
+        ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
+        if ev is not None:
+            raise Exception("Unexpected enrollee add event")
+    send_wlanevent(url, uuid, data)
+    ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
+    if ev is None:
+        raise Exception("Enrollee add event not seen")
+
+    with alloc_fail(dev[0], 1, "base64_encode;wps_er_soap_hdr"):
+        send_wlanevent(url, uuid, data)
+
+    with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
+        send_wlanevent(url, uuid, data)
+
+    with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
+        send_wlanevent(url, uuid, data)
+
+    with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
+        send_wlanevent(url, uuid, data)
+
 def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
     """WPS ER HTTP protocol testing - no eventSubURL"""
     class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
@@ -3982,7 +4612,7 @@ def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
     tests = [ (1, "http_client_url_parse"),
               (1, "wpabuf_alloc;wps_er_subscribe"),
               (1, "http_client_addr"),
-              (1, "eloop_register_sock;http_client_addr"),
+              (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
               (1, "eloop_register_timeout;http_client_addr") ]
     for count,func in tests:
         with alloc_fail(dev[0], count, func):
@@ -4134,7 +4764,7 @@ def test_ap_wps_http_timeout(dev, apdev):
 
 def _test_ap_wps_http_timeout(dev, apdev):
     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+    add_ssdp_ap(apdev[0], ap_uuid)
 
     location = ssdp_get_location(ap_uuid)
     url = urlparse.urlparse(location)
@@ -4230,7 +4860,7 @@ def test_ap_wps_init_oom(dev, apdev):
     appin = "12345670"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                "ap_pin": appin }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     pin = dev[0].wps_read_pin()
 
     with alloc_fail(hapd, 1, "wps_init"):
@@ -4276,7 +4906,7 @@ def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
     """WPS and invalid IE in Association Request frame"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     pin = "12345670"
     hapd.request("WPS_PIN any " + pin)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
@@ -4297,7 +4927,7 @@ def test_ap_wps_pbc_pin_mismatch(dev, apdev):
     """WPS PBC/PIN mismatch"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     hapd.request("SET wps_version_number 0x10")
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
     hapd.request("WPS_PBC")
@@ -4316,9 +4946,9 @@ def test_ap_wps_ie_invalid(dev, apdev):
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                "vendor_elements": "dd050050f20410" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
-    hostapd.add_ap(apdev[1]['ifname'], params)
+    hostapd.add_ap(apdev[1], params)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
     pin = dev[0].wps_read_pin()
     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
@@ -4331,9 +4961,9 @@ def test_ap_wps_scan_prio_order(dev, apdev):
     """WPS scan priority ordering"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
-    hostapd.add_ap(apdev[1]['ifname'], params)
+    hostapd.add_ap(apdev[1], params)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
     pin = dev[0].wps_read_pin()
@@ -4347,7 +4977,7 @@ def test_ap_wps_probe_req_ie_oom(dev, apdev):
     """WPS ProbeReq IE OOM"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     pin = dev[0].wps_read_pin()
     hapd.request("WPS_PIN any " + pin)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
@@ -4357,6 +4987,7 @@ def test_ap_wps_probe_req_ie_oom(dev, apdev):
         if ev is None:
             raise Exception("Association not seen")
     dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
 
     with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
@@ -4364,12 +4995,17 @@ def test_ap_wps_probe_req_ie_oom(dev, apdev):
         if ev is None:
             raise Exception("Association not seen")
     dev[0].request("WPS_CANCEL")
+    hapd.disable()
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+    time.sleep(0.2)
+    dev[0].flush_scan_cache()
 
 def test_ap_wps_assoc_req_ie_oom(dev, apdev):
     """WPS AssocReq IE OOM"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     pin = dev[0].wps_read_pin()
     hapd.request("WPS_PIN any " + pin)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
@@ -4384,7 +5020,7 @@ def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
     """WPS AssocResp IE OOM"""
     ssid = "test-wps"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+    hapd = hostapd.add_ap(apdev[0], params)
     pin = dev[0].wps_read_pin()
     hapd.request("WPS_PIN any " + pin)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
@@ -4399,9 +5035,9 @@ def test_ap_wps_bss_info_errors(dev, apdev):
     """WPS BSS info errors"""
     params = { "ssid": "1",
                "vendor_elements": "dd0e0050f20410440001ff101100010a" }
-    hostapd.add_ap(apdev[0]['ifname'], params)
+    hostapd.add_ap(apdev[0], params)
     params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
-    hostapd.add_ap(apdev[1]['ifname'], params)
+    hostapd.add_ap(apdev[1], params)
     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
     bss = dev[0].get_bss(apdev[0]['bssid'])
@@ -4559,7 +5195,7 @@ def test_ap_wps_random_psk_fail(dev, apdev):
                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
                    "rsn_pairwise": "CCMP", "ap_pin": appin,
                    "wpa_psk_file": pskfile }
-        hapd = hostapd.add_ap(apdev[0]['ifname'], params)
+        hapd = hostapd.add_ap(apdev[0], params)
 
         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
         with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
@@ -4607,22 +5243,29 @@ def wps_ext_eap_wsc(dst, src, src_addr, msg):
     if "OK" not in res:
         raise Exception("EAPOL_RX failed")
 
-def wps_start_ext(apdev, dev):
+def wps_start_ext(apdev, dev, pbc=False, pin=None):
     addr = dev.own_addr()
     bssid = apdev['bssid']
     ssid = "test-wps-conf"
     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
                "wpa_passphrase": "12345678", "wpa": "2",
                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
-    hapd = hostapd.add_ap(apdev['ifname'], params)
+    hapd = hostapd.add_ap(apdev, params)
 
-    pin = dev.wps_read_pin()
-    hapd.request("WPS_PIN any " + pin)
+    if pbc:
+        hapd.request("WPS_PBC")
+    else:
+        if pin is None:
+            pin = dev.wps_read_pin()
+        hapd.request("WPS_PIN any " + pin)
     dev.scan_for_bss(bssid, freq="2412")
     hapd.request("SET ext_eapol_frame_io 1")
     dev.request("SET ext_eapol_frame_io 1")
 
-    dev.request("WPS_PIN " + bssid + " " + pin)
+    if pbc:
+        dev.request("WPS_PBC " + bssid)
+    else:
+        dev.request("WPS_PIN " + bssid + " " + pin)
     return addr,bssid,hapd
 
 def wps_auth_corrupt(dst, src, addr):
@@ -4773,68 +5416,485 @@ def test_ap_wps_authenticator_missing_m2(dev, apdev):
         raise Exception("EAPOL_RX failed")
     wps_fail_finish(hapd, dev[0], "msg=5")
 
-def test_ap_wps_config_methods(dev, apdev):
-    """WPS configuration method parsing"""
-    ssid = "test-wps-conf"
-    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
-               "wpa_passphrase": "12345678", "wpa": "2",
-               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
-               "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
-    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
-    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
-               "wpa_passphrase": "12345678", "wpa": "2",
-               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
-               "config_methods": "display push_button" }
-    hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
+def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
+    """WPS and M2 with different Device Password ID (P2P)"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[722:730] != '10120002':
+        raise Exception("Could not find Device Password ID attribute")
+    # Replace Device Password ID value. This will fail Authenticator check, but
+    # allows the code path in wps_process_dev_pw_id() to be checked from debug
+    # log.
+    msg = msg[0:730] + "0005" + msg[734:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    wps_fail_finish(hapd, dev[0], "msg=5")
 
-def test_ap_wps_set_selected_registrar_proto(dev, apdev):
-    """WPS UPnP SetSelectedRegistrar protocol testing"""
-    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
-    hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
+def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
+    """WPS and M2 with different Device Password ID (PIN to PBC)"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[722:730] != '10120002':
+        raise Exception("Could not find Device Password ID attribute")
+    # Replace Device Password ID value (PIN --> PBC). This will be rejected.
+    msg = msg[0:730] + "0004" + msg[734:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    wps_fail_finish(hapd, dev[0], "msg=5")
 
-    location = ssdp_get_location(ap_uuid)
-    urls = upnp_get_urls(location)
-    eventurl = urlparse.urlparse(urls['event_sub_url'])
-    ctrlurl = urlparse.urlparse(urls['control_url'])
-    url = urlparse.urlparse(location)
-    conn = httplib.HTTPConnection(url.netloc)
+def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
+    """WPS and M2 with different Device Password ID (PBC to PIN)"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[722:730] != '10120002':
+        raise Exception("Could not find Device Password ID attribute")
+    # Replace Device Password ID value. This will fail Authenticator check, but
+    # allows the code path in wps_process_dev_pw_id() to be checked from debug
+    # log.
+    msg = msg[0:730] + "0000" + msg[734:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    wps_fail_finish(hapd, dev[0], "msg=5")
+    dev[0].flush_scan_cache()
 
-    class WPSERHTTPServer(SocketServer.StreamRequestHandler):
-        def handle(self):
-            data = self.rfile.readline().strip()
-            logger.debug(data)
-            self.wfile.write(gen_wps_event())
+def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
+    """WPS and M2 without Device Password ID"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[722:730] != '10120002':
+        raise Exception("Could not find Device Password ID attribute")
+    # Remove Device Password ID value. This will fail Authenticator check, but
+    # allows the code path in wps_process_dev_pw_id() to be checked from debug
+    # log.
+    mlen = "%04x" % (int(msg[4:8], 16) - 6)
+    msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    wps_fail_finish(hapd, dev[0], "msg=5")
 
-    server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
-    server.timeout = 1
+def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
+    """WPS and M2 without Registrar Nonce"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[96:104] != '10390010':
+        raise Exception("Could not find Registrar Nonce attribute")
+    # Remove Registrar Nonce. This will fail Authenticator check, but
+    # allows the code path in wps_process_registrar_nonce() to be checked from
+    # the debug log.
+    mlen = "%04x" % (int(msg[4:8], 16) - 20)
+    msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
+    if ev is None:
+        raise Exception("Disconnect event not seen")
+    dev[0].request("WPS_CANCEL")
+    dev[0].flush_scan_cache()
 
-    headers = { "callback": '<http://127.0.0.1:12345/event>',
-                "NT": "upnp:event",
-                "timeout": "Second-1234" }
-    conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
-    resp = conn.getresponse()
-    if resp.status != 200:
-        raise Exception("Unexpected HTTP response: %d" % resp.status)
-    sid = resp.getheader("sid")
-    logger.debug("Subscription SID " + sid)
-    server.handle_request()
+def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
+    """WPS and M2 without Enrollee Nonce"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[56:64] != '101a0010':
+        raise Exception("Could not find enrollee Nonce attribute")
+    # Remove Enrollee Nonce. This will fail Authenticator check, but
+    # allows the code path in wps_process_enrollee_nonce() to be checked from
+    # the debug log.
+    mlen = "%04x" % (int(msg[4:8], 16) - 20)
+    msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
+    if ev is None:
+        raise Exception("Disconnect event not seen")
+    dev[0].request("WPS_CANCEL")
+    dev[0].flush_scan_cache()
 
-    tests = [ (500, "10"),
-              (200, "104a000110" + "1041000101" + "101200020000" +
-               "105300023148" +
-               "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
-               "10480010362db47ba53a519188fb5458b986b2e4"),
-              (200, "104a000110" + "1041000100" + "101200020000" +
-               "105300020000"),
-              (200, "104a000110" + "1041000100"),
-              (200, "104a000110") ]
-    for status,test in tests:
-        tlvs = binascii.unhexlify(test)
-        newmsg = base64.b64encode(tlvs)
-        msg = '<?xml version="1.0"?>\n'
-        msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
-        msg += '<s:Body>'
-        msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
+def test_ap_wps_m2_missing_uuid_r(dev, apdev):
+    """WPS and M2 without UUID-R"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[136:144] != '10480010':
+        raise Exception("Could not find enrollee Nonce attribute")
+    # Remove UUID-R. This will fail Authenticator check, but allows the code
+    # path in wps_process_uuid_r() to be checked from the debug log.
+    mlen = "%04x" % (int(msg[4:8], 16) - 20)
+    msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
+    if ev is None:
+        raise Exception("Disconnect event not seen")
+    dev[0].request("WPS_CANCEL")
+    dev[0].flush_scan_cache()
+
+def test_ap_wps_m2_invalid(dev, apdev):
+    """WPS and M2 parsing failure"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[136:144] != '10480010':
+        raise Exception("Could not find enrollee Nonce attribute")
+    # Remove UUID-R. This will fail Authenticator check, but allows the code
+    # path in wps_process_uuid_r() to be checked from the debug log.
+    mlen = "%04x" % (int(msg[4:8], 16) - 1)
+    msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
+    if ev is None:
+        raise Exception("Disconnect event not seen")
+    dev[0].request("WPS_CANCEL")
+    dev[0].flush_scan_cache()
+
+def test_ap_wps_m2_missing_msg_type(dev, apdev):
+    """WPS and M2 without Message Type"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[46:54] != '10220001':
+        raise Exception("Could not find Message Type attribute")
+    # Remove Message Type. This will fail Authenticator check, but allows the
+    # code path in wps_process_wsc_msg() to be checked from the debug log.
+    mlen = "%04x" % (int(msg[4:8], 16) - 5)
+    msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
+    if ev is None:
+        raise Exception("Disconnect event not seen")
+    dev[0].request("WPS_CANCEL")
+    dev[0].flush_scan_cache()
+
+def test_ap_wps_m2_unknown_msg_type(dev, apdev):
+    """WPS and M2 but unknown Message Type"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[46:54] != '10220001':
+        raise Exception("Could not find Message Type attribute")
+    # Replace Message Type value. This will be rejected.
+    msg = msg[0:54] + "00" + msg[56:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
+    if ev is None:
+        raise Exception("Disconnect event not seen")
+    dev[0].request("WPS_CANCEL")
+    dev[0].flush_scan_cache()
+
+def test_ap_wps_m2_unknown_opcode(dev, apdev):
+    """WPS and M2 but unknown opcode"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    # Replace opcode. This will be discarded in EAP-WSC processing.
+    msg = msg[0:32] + "00" + msg[34:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_ap_wps_m2_unknown_opcode2(dev, apdev):
+    """WPS and M2 but unknown opcode (WSC_Start)"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    # Replace opcode. This will be discarded in EAP-WSC processing.
+    msg = msg[0:32] + "01" + msg[34:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_ap_wps_m2_unknown_opcode3(dev, apdev):
+    """WPS and M2 but unknown opcode (WSC_Done)"""
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
+    logger.debug("M2")
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    # Replace opcode. This will be discarded in WPS Enrollee processing.
+    msg = msg[0:32] + "05" + msg[34:]
+    res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def wps_m2_but_other(dev, apdev, title, msgtype):
+    addr,bssid,hapd = wps_start_ext(apdev, dev)
+    wps_ext_eap_identity_req(dev, hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev, addr)
+    wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev, addr, "M1")
+    logger.debug(title)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev.request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[46:54] != '10220001':
+        raise Exception("Could not find Message Type attribute")
+    # Replace Message Type value. This will be rejected.
+    msg = msg[0:54] + msgtype + msg[56:]
+    res = dev.request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    ev = dev.wait_event(["WPS-FAIL"], timeout=5)
+    if ev is None:
+        raise Exception("WPS-FAIL event not seen")
+    dev.request("WPS_CANCEL")
+    dev.wait_disconnected()
+
+def wps_m4_but_other(dev, apdev, title, msgtype):
+    addr,bssid,hapd = wps_start_ext(apdev, dev)
+    wps_ext_eap_identity_req(dev, hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev, addr)
+    wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
+    wps_ext_eap_wsc(hapd, dev, addr, "M1")
+    wps_ext_eap_wsc(dev, hapd, bssid, "M2")
+    wps_ext_eap_wsc(hapd, dev, addr, "M3")
+    logger.debug(title)
+    ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev.request("SET ext_eapol_frame_io 0")
+    msg = ev.split(' ')[2]
+    if msg[46:54] != '10220001':
+        raise Exception("Could not find Message Type attribute")
+    # Replace Message Type value. This will be rejected.
+    msg = msg[0:54] + msgtype + msg[56:]
+    res = dev.request("EAPOL_RX " + bssid + " " + msg)
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+    ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
+    if ev is None:
+        raise Exception("WPS-FAIL event not seen")
+    dev.request("WPS_CANCEL")
+    dev.wait_disconnected()
+
+def test_ap_wps_m2_msg_type_m4(dev, apdev):
+    """WPS and M2 but Message Type M4"""
+    wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
+
+def test_ap_wps_m2_msg_type_m6(dev, apdev):
+    """WPS and M2 but Message Type M6"""
+    wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
+
+def test_ap_wps_m2_msg_type_m8(dev, apdev):
+    """WPS and M2 but Message Type M8"""
+    wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
+
+def test_ap_wps_m4_msg_type_m2(dev, apdev):
+    """WPS and M4 but Message Type M2"""
+    wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
+
+def test_ap_wps_m4_msg_type_m2d(dev, apdev):
+    """WPS and M4 but Message Type M2D"""
+    wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
+
+def test_ap_wps_config_methods(dev, apdev):
+    """WPS configuration method parsing"""
+    ssid = "test-wps-conf"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
+    hapd = hostapd.add_ap(apdev[0], params)
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "config_methods": "display push_button" }
+    hapd2 = hostapd.add_ap(apdev[1], params)
+
+def test_ap_wps_set_selected_registrar_proto(dev, apdev):
+    """WPS UPnP SetSelectedRegistrar protocol testing"""
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    hapd = add_ssdp_ap(apdev[0], ap_uuid)
+
+    location = ssdp_get_location(ap_uuid)
+    urls = upnp_get_urls(location)
+    eventurl = urlparse.urlparse(urls['event_sub_url'])
+    ctrlurl = urlparse.urlparse(urls['control_url'])
+    url = urlparse.urlparse(location)
+    conn = httplib.HTTPConnection(url.netloc)
+
+    class WPSERHTTPServer(SocketServer.StreamRequestHandler):
+        def handle(self):
+            data = self.rfile.readline().strip()
+            logger.debug(data)
+            self.wfile.write(gen_wps_event())
+
+    server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
+    server.timeout = 1
+
+    headers = { "callback": '<http://127.0.0.1:12345/event>',
+                "NT": "upnp:event",
+                "timeout": "Second-1234" }
+    conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
+    resp = conn.getresponse()
+    if resp.status != 200:
+        raise Exception("Unexpected HTTP response: %d" % resp.status)
+    sid = resp.getheader("sid")
+    logger.debug("Subscription SID " + sid)
+    server.handle_request()
+
+    tests = [ (500, "10"),
+              (200, "104a000110" + "1041000101" + "101200020000" +
+               "105300023148" +
+               "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
+               "10480010362db47ba53a519188fb5458b986b2e4"),
+              (200, "104a000110" + "1041000100" + "101200020000" +
+               "105300020000"),
+              (200, "104a000110" + "1041000100"),
+              (200, "104a000110") ]
+    for status,test in tests:
+        tlvs = binascii.unhexlify(test)
+        newmsg = base64.b64encode(tlvs)
+        msg = '<?xml version="1.0"?>\n'
+        msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
+        msg += '<s:Body>'
+        msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
         msg += '<NewMessage>'
         msg += newmsg
         msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
@@ -4844,3 +5904,3604 @@ def test_ap_wps_set_selected_registrar_proto(dev, apdev):
         resp = conn.getresponse()
         if resp.status != status:
             raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
+
+def test_ap_wps_adv_oom(dev, apdev):
+    """WPS AP and advertisement OOM"""
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    hapd = add_ssdp_ap(apdev[0], ap_uuid)
+
+    with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
+        ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
+                          no_recv=True)
+        time.sleep(0.2)
+
+    with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
+        ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
+                          no_recv=True)
+        time.sleep(0.2)
+
+    with alloc_fail(hapd, 1,
+                    "next_advertisement;advertisement_state_machine_stop"):
+        hapd.disable()
+
+    with alloc_fail(hapd, 1, "ssdp_listener_start"):
+        if "FAIL" not in hapd.request("ENABLE"):
+            raise Exception("ENABLE succeeded during OOM")
+
+def test_wps_config_methods(dev):
+    """WPS config method update"""
+    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
+    wpas.interface_add("wlan5")
+    if "OK" not in wpas.request("SET config_methods display label"):
+        raise Exception("Failed to set config_methods")
+    if wpas.request("GET config_methods").strip() != "display label":
+        raise Exception("config_methods were not updated")
+    if "OK" not in wpas.request("SET config_methods "):
+        raise Exception("Failed to clear config_methods")
+    if wpas.request("GET config_methods").strip() != "":
+        raise Exception("config_methods were not cleared")
+
+WPS_VENDOR_ID_WFA = 14122
+WPS_VENDOR_TYPE = 1
+
+# EAP-WSC Op-Code values
+WSC_Start = 0x01
+WSC_ACK = 0x02
+WSC_NACK = 0x03
+WSC_MSG = 0x04
+WSC_Done = 0x05
+WSC_FRAG_ACK = 0x06
+
+ATTR_AP_CHANNEL = 0x1001
+ATTR_ASSOC_STATE = 0x1002
+ATTR_AUTH_TYPE = 0x1003
+ATTR_AUTH_TYPE_FLAGS = 0x1004
+ATTR_AUTHENTICATOR = 0x1005
+ATTR_CONFIG_METHODS = 0x1008
+ATTR_CONFIG_ERROR = 0x1009
+ATTR_CONFIRM_URL4 = 0x100a
+ATTR_CONFIRM_URL6 = 0x100b
+ATTR_CONN_TYPE = 0x100c
+ATTR_CONN_TYPE_FLAGS = 0x100d
+ATTR_CRED = 0x100e
+ATTR_ENCR_TYPE = 0x100f
+ATTR_ENCR_TYPE_FLAGS = 0x1010
+ATTR_DEV_NAME = 0x1011
+ATTR_DEV_PASSWORD_ID = 0x1012
+ATTR_E_HASH1 = 0x1014
+ATTR_E_HASH2 = 0x1015
+ATTR_E_SNONCE1 = 0x1016
+ATTR_E_SNONCE2 = 0x1017
+ATTR_ENCR_SETTINGS = 0x1018
+ATTR_ENROLLEE_NONCE = 0x101a
+ATTR_FEATURE_ID = 0x101b
+ATTR_IDENTITY = 0x101c
+ATTR_IDENTITY_PROOF = 0x101d
+ATTR_KEY_WRAP_AUTH = 0x101e
+ATTR_KEY_ID = 0x101f
+ATTR_MAC_ADDR = 0x1020
+ATTR_MANUFACTURER = 0x1021
+ATTR_MSG_TYPE = 0x1022
+ATTR_MODEL_NAME = 0x1023
+ATTR_MODEL_NUMBER = 0x1024
+ATTR_NETWORK_INDEX = 0x1026
+ATTR_NETWORK_KEY = 0x1027
+ATTR_NETWORK_KEY_INDEX = 0x1028
+ATTR_NEW_DEVICE_NAME = 0x1029
+ATTR_NEW_PASSWORD = 0x102a
+ATTR_OOB_DEVICE_PASSWORD = 0x102c
+ATTR_OS_VERSION = 0x102d
+ATTR_POWER_LEVEL = 0x102f
+ATTR_PSK_CURRENT = 0x1030
+ATTR_PSK_MAX = 0x1031
+ATTR_PUBLIC_KEY = 0x1032
+ATTR_RADIO_ENABLE = 0x1033
+ATTR_REBOOT = 0x1034
+ATTR_REGISTRAR_CURRENT = 0x1035
+ATTR_REGISTRAR_ESTABLISHED = 0x1036
+ATTR_REGISTRAR_LIST = 0x1037
+ATTR_REGISTRAR_MAX = 0x1038
+ATTR_REGISTRAR_NONCE = 0x1039
+ATTR_REQUEST_TYPE = 0x103a
+ATTR_RESPONSE_TYPE = 0x103b
+ATTR_RF_BANDS = 0x103c
+ATTR_R_HASH1 = 0x103d
+ATTR_R_HASH2 = 0x103e
+ATTR_R_SNONCE1 = 0x103f
+ATTR_R_SNONCE2 = 0x1040
+ATTR_SELECTED_REGISTRAR = 0x1041
+ATTR_SERIAL_NUMBER = 0x1042
+ATTR_WPS_STATE = 0x1044
+ATTR_SSID = 0x1045
+ATTR_TOTAL_NETWORKS = 0x1046
+ATTR_UUID_E = 0x1047
+ATTR_UUID_R = 0x1048
+ATTR_VENDOR_EXT = 0x1049
+ATTR_VERSION = 0x104a
+ATTR_X509_CERT_REQ = 0x104b
+ATTR_X509_CERT = 0x104c
+ATTR_EAP_IDENTITY = 0x104d
+ATTR_MSG_COUNTER = 0x104e
+ATTR_PUBKEY_HASH = 0x104f
+ATTR_REKEY_KEY = 0x1050
+ATTR_KEY_LIFETIME = 0x1051
+ATTR_PERMITTED_CFG_METHODS = 0x1052
+ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
+ATTR_PRIMARY_DEV_TYPE = 0x1054
+ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
+ATTR_PORTABLE_DEV = 0x1056
+ATTR_AP_SETUP_LOCKED = 0x1057
+ATTR_APPLICATION_EXT = 0x1058
+ATTR_EAP_TYPE = 0x1059
+ATTR_IV = 0x1060
+ATTR_KEY_PROVIDED_AUTO = 0x1061
+ATTR_802_1X_ENABLED = 0x1062
+ATTR_APPSESSIONKEY = 0x1063
+ATTR_WEPTRANSMITKEY = 0x1064
+ATTR_REQUESTED_DEV_TYPE = 0x106a
+
+# Message Type
+WPS_Beacon = 0x01
+WPS_ProbeRequest = 0x02
+WPS_ProbeResponse = 0x03
+WPS_M1 = 0x04
+WPS_M2 = 0x05
+WPS_M2D = 0x06
+WPS_M3 = 0x07
+WPS_M4 = 0x08
+WPS_M5 = 0x09
+WPS_M6 = 0x0a
+WPS_M7 = 0x0b
+WPS_M8 = 0x0c
+WPS_WSC_ACK = 0x0d
+WPS_WSC_NACK = 0x0e
+WPS_WSC_DONE = 0x0f
+
+def get_wsc_msg(dev):
+    ev = dev.wait_event(["EAPOL-TX"], timeout=10)
+    if ev is None:
+        raise Exception("Timeout on EAPOL-TX")
+    data = binascii.unhexlify(ev.split(' ')[2])
+    msg = {}
+
+    # Parse EAPOL header
+    if len(data) < 4:
+        raise Exception("No room for EAPOL header")
+    version,type,length = struct.unpack('>BBH', data[0:4])
+    msg['eapol_version'] = version
+    msg['eapol_type'] = type
+    msg['eapol_length'] = length
+    data = data[4:]
+    if length != len(data):
+        raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
+    if type != 0:
+        raise Exception("Unexpected EAPOL header type: %d" % type)
+
+    # Parse EAP header
+    if len(data) < 4:
+        raise Exception("No room for EAP header")
+    code,identifier,length = struct.unpack('>BBH', data[0:4])
+    msg['eap_code'] = code
+    msg['eap_identifier'] = identifier
+    msg['eap_length'] = length
+    data = data[4:]
+    if msg['eapol_length'] != msg['eap_length']:
+        raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
+
+    # Parse EAP expanded header
+    if len(data) < 1:
+        raise Exception("No EAP type included")
+    msg['eap_type'], = struct.unpack('B', data[0])
+    data = data[1:]
+
+    if msg['eap_type'] == 254:
+        if len(data) < 3 + 4:
+            raise Exception("Truncated EAP expanded header")
+        msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', '\0' + data[0:7])
+        data = data[7:]
+    else:
+        raise Exception("Unexpected EAP type")
+
+    if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
+        raise Exception("Unexpected Vendor-Id")
+    if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
+        raise Exception("Unexpected Vendor-Type")
+
+    # Parse EAP-WSC header
+    if len(data) < 2:
+        raise Exception("Truncated EAP-WSC header")
+    msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
+    data = data[2:]
+
+    # Parse WSC attributes
+    msg['raw_attrs'] = data
+    attrs = {}
+    while len(data) > 0:
+        if len(data) < 4:
+            raise Exception("Truncated attribute header")
+        attr,length = struct.unpack('>HH', data[0:4])
+        data = data[4:]
+        if length > len(data):
+            raise Exception("Truncated attribute 0x%04x" % attr)
+        attrs[attr] = data[0:length]
+        data = data[length:]
+    msg['wsc_attrs'] = attrs
+
+    if ATTR_MSG_TYPE in attrs:
+        msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
+
+    return msg
+
+def recv_wsc_msg(dev, opcode, msg_type):
+    msg = get_wsc_msg(dev)
+    if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
+        raise Exception("Unexpected Op-Code/MsgType")
+    return msg, msg['wsc_attrs'], msg['raw_attrs']
+
+def build_wsc_attr(attr, payload):
+    return struct.pack('>HH', attr, len(payload)) + payload
+
+def build_attr_msg_type(msg_type):
+    return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
+
+def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
+    length = 4 + 8 + 2 + len(payload)
+    # EAPOL header
+    msg = struct.pack('>BBH', 2, 0, length)
+    # EAP header
+    msg += struct.pack('>BBH', eap_code, eap_id, length)
+    # EAP expanded header for EAP-WSC
+    msg += struct.pack('B', 254)
+    msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
+    msg += struct.pack('>L', WPS_VENDOR_TYPE)
+    # EAP-WSC header
+    msg += struct.pack('BB', opcode, 0)
+    # WSC attributes
+    msg += payload
+    return msg
+
+def build_eap_success(eap_id):
+    length = 4
+    # EAPOL header
+    msg = struct.pack('>BBH', 2, 0, length)
+    # EAP header
+    msg += struct.pack('>BBH', 3, eap_id, length)
+    return msg
+
+def build_eap_failure(eap_id):
+    length = 4
+    # EAPOL header
+    msg = struct.pack('>BBH', 2, 0, length)
+    # EAP header
+    msg += struct.pack('>BBH', 4, eap_id, length)
+    return msg
+
+def send_wsc_msg(dev, src, msg):
+    res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg))
+    if "OK" not in res:
+        raise Exception("EAPOL_RX failed")
+
+group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
+group_5_generator = 2
+
+def wsc_kdf(key, label, bits):
+    result = ''
+    i = 1
+    while len(result) * 8 < bits:
+        data = struct.pack('>L', i) + label + struct.pack('>L', bits)
+        m = hmac.new(key, data, hashlib.sha256)
+        result += m.digest()
+        i += 1
+    return result[0:bits / 8]
+
+def wsc_keys(kdk):
+    keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
+    authkey = keys[0:32]
+    keywrapkey = keys[32:48]
+    emsk = keys[48:80]
+    return authkey,keywrapkey,emsk
+
+def wsc_dev_pw_half_psk(authkey, dev_pw):
+    m = hmac.new(authkey, dev_pw, hashlib.sha256)
+    return m.digest()[0:16]
+
+def wsc_dev_pw_psk(authkey, dev_pw):
+    dev_pw_1 = dev_pw[0:len(dev_pw) / 2]
+    dev_pw_2 = dev_pw[len(dev_pw) / 2:]
+    psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
+    psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
+    return psk1,psk2
+
+def build_attr_authenticator(authkey, prev_msg, curr_msg):
+    m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
+    auth = m.digest()[0:8]
+    return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
+
+def build_attr_encr_settings(authkey, keywrapkey, data):
+    m = hmac.new(authkey, data, hashlib.sha256)
+    kwa = m.digest()[0:8]
+    data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
+    iv = 16*'\x99'
+    aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
+    pad_len = 16 - len(data) % 16
+    ps = pad_len * struct.pack('B', pad_len)
+    data += ps
+    wrapped = aes.encrypt(data)
+    return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
+
+def decrypt_attr_encr_settings(authkey, keywrapkey, data):
+    if len(data) < 32 or len(data) % 16 != 0:
+        raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
+    iv = data[0:16]
+    encr = data[16:]
+    aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
+    decrypted = aes.decrypt(encr)
+    pad_len, = struct.unpack('B', decrypted[-1])
+    if pad_len > len(decrypted):
+        raise Exception("Invalid padding in Encrypted Settings")
+    for i in range(-pad_len, -1):
+        if decrypted[i] != decrypted[-1]:
+            raise Exception("Invalid PS value in Encrypted Settings")
+    
+    decrypted = decrypted[0:len(decrypted) - pad_len]
+    if len(decrypted) < 12:
+        raise Exception("Truncated Encrypted Settings plaintext")
+    kwa = decrypted[-12:]
+    attr,length = struct.unpack(">HH", kwa[0:4])
+    if attr != ATTR_KEY_WRAP_AUTH or length != 8:
+        raise Exception("Invalid KWA header")
+    kwa = kwa[4:]
+    decrypted = decrypted[0:len(decrypted) - 12]
+
+    m = hmac.new(authkey, decrypted, hashlib.sha256)
+    calc_kwa = m.digest()[0:8]
+    if kwa != calc_kwa:
+        raise Exception("KWA mismatch")
+
+    return decrypted
+
+def zeropad_str(val, pad_len):
+    while len(val) < pad_len * 2:
+        val = '0' + val
+    return val
+
+def wsc_dh_init():
+    # For now, use a hardcoded private key. In theory, this is supposed to be
+    # randomly selected.
+    own_private = 0x123456789
+    own_public = pow(group_5_generator, own_private, group_5_prime)
+    pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
+    return own_private, pk
+
+def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
+    peer_public = long(binascii.hexlify(peer_pk), 16)
+    if peer_public < 2 or peer_public >= group_5_prime:
+        raise Exception("Invalid peer public key")
+    if pow(peer_public, (group_5_prime - 1) / 2, group_5_prime) != 1:
+        raise Exception("Unexpected Legendre symbol for peer public key")
+
+    shared_secret = pow(peer_public, own_private, group_5_prime)
+    ss = zeropad_str(format(shared_secret, "02x"), 192)
+    logger.debug("DH shared secret: " + ss)
+
+    dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
+    logger.debug("DHKey: " + binascii.hexlify(dhkey))
+
+    m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
+    kdk = m.digest()
+    logger.debug("KDK: " + binascii.hexlify(kdk))
+    authkey,keywrapkey,emsk = wsc_keys(kdk)
+    logger.debug("AuthKey: " + binascii.hexlify(authkey))
+    logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey))
+    logger.debug("EMSK: " + binascii.hexlify(emsk))
+    return authkey,keywrapkey
+
+def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
+    psk1,psk2 = wsc_dev_pw_psk(authkey, dev_pw)
+    logger.debug("PSK1: " + binascii.hexlify(psk1))
+    logger.debug("PSK2: " + binascii.hexlify(psk2))
+
+    # Note: Secret values are supposed to be random, but hardcoded values are
+    # fine for testing.
+    s1 = 16*'\x77'
+    m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
+    hash1 = m.digest()
+    logger.debug("Hash1: " + binascii.hexlify(hash1))
+
+    s2 = 16*'\x88'
+    m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
+    hash2 = m.digest()
+    logger.debug("Hash2: " + binascii.hexlify(hash2))
+    return s1,s2,hash1,hash2
+
+def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
+             manufacturer='', model_name='', config_methods='\x00\x00'):
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M1)
+    attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
+    attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
+    attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
+    attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
+    attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
+    attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
+    attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
+    attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
+    attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
+    attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
+    attrs += build_wsc_attr(ATTR_DEV_NAME, '')
+    attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
+    attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
+    m1 = build_eap_wsc(2, eap_id, attrs)
+    return m1, attrs
+
+def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
+             dev_pw_id='\x00\x00', eap_code=1):
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M2)
+    if e_nonce:
+        attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    if r_nonce:
+        attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
+    if r_pk:
+        attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
+    attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
+    attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
+    attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
+    attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
+    attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
+    attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
+    attrs += build_wsc_attr(ATTR_DEV_NAME, '')
+    attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
+    attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
+    attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
+    attrs += build_attr_authenticator(authkey, m1, attrs)
+    m2 = build_eap_wsc(eap_code, eap_id, attrs)
+    return m2, attrs
+
+def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M2D)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
+    attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
+    attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
+    attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
+    #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
+    attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
+    attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
+    attrs += build_wsc_attr(ATTR_DEV_NAME, '')
+    attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
+    attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
+    attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
+    if dev_pw_id:
+        attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
+    m2d = build_eap_wsc(eap_code, eap_id, attrs)
+    return m2d, attrs
+
+def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    if msg_type is not None:
+        attrs += build_attr_msg_type(msg_type)
+    if e_nonce:
+        attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    if r_nonce:
+        attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
+    return msg, attrs
+
+def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
+               msg_type=WPS_WSC_NACK, eap_code=1):
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    if msg_type is not None:
+        attrs += build_attr_msg_type(msg_type)
+    if e_nonce:
+        attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    if r_nonce:
+        attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    if config_error:
+        attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
+    msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
+    return msg, attrs
+
+def test_wps_ext(dev, apdev):
+    """WPS against external implementation"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+    wsc_start_id = msg['eap_identifier']
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+
+    authkey,keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, e_nonce,
+                                    m2_attrs[ATTR_REGISTRAR_NONCE])
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
+                                                m2_attrs[ATTR_PUBLIC_KEY])
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
+                            m2_attrs[ATTR_REGISTRAR_NONCE])
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    logger.debug("Receive M4 from AP")
+    msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
+
+    logger.debug("Send M5 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M5)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
+                            m2_attrs[ATTR_REGISTRAR_NONCE])
+    data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
+    raw_m5_attrs = attrs
+    m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m5)
+
+    logger.debug("Receive M6 from AP")
+    msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
+
+    logger.debug("Send M7 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M7)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
+                            m2_attrs[ATTR_REGISTRAR_NONCE])
+    data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
+    m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    raw_m7_attrs = attrs
+    send_wsc_msg(hapd, addr, m7)
+
+    logger.debug("Receive M8 from AP")
+    msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
+    m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
+                                         m8_attrs[ATTR_ENCR_SETTINGS])
+    logger.debug("M8 Credential: " + binascii.hexlify(m8_cred))
+
+    logger.debug("Prepare WSC_Done")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_WSC_DONE)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
+                            m2_attrs[ATTR_REGISTRAR_NONCE])
+    wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
+    # Do not send WSC_Done yet to allow exchangw with STA complete before the
+    # AP disconnects.
+
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+
+    eap_id = wsc_start_id
+    logger.debug("Send WSC/Start to STA")
+    wsc_start = build_eap_wsc(1, eap_id, "", opcode=WSC_Start)
+    send_wsc_msg(dev[0], bssid, wsc_start)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, e_pk)
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M3 from STA")
+    msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
+    raw_m4_attrs = attrs
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 from STA")
+    msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
+
+    logger.debug("Send M6 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M6)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
+                            m1_attrs[ATTR_ENROLLEE_NONCE])
+    data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
+    raw_m6_attrs = attrs
+    m6 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m6)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M7 from STA")
+    msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
+
+    logger.debug("Send M8 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M8)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
+                            m1_attrs[ATTR_ENROLLEE_NONCE])
+    attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
+    attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
+    raw_m8_attrs = attrs
+    m8 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m8)
+    eap_id = (eap_id + 1) % 256
+
+    ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
+    if ev is None:
+        raise Exception("wpa_supplicant did not report credential")
+
+    logger.debug("Receive WSC_Done from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
+        raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
+
+    logger.debug("Send WSC_Done to AP")
+    hapd.request("SET ext_eapol_frame_io 0")
+    dev[0].request("SET ext_eapol_frame_io 0")
+    send_wsc_msg(hapd, addr, wsc_done)
+
+    ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
+    if ev is None:
+        raise Exception("hostapd did not report WPS success")
+
+    dev[0].wait_connected()
+
+def wps_start_kwa(dev, apdev):
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, e_pk)
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M3 from STA")
+    msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+
+    return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
+
+def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
+    attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
+    """WPS and KWA error: No KWA attribute"""
+    r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    # Encrypted Settings without KWA
+    iv = 16*'\x99'
+    aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
+    pad_len = 16 - len(data) % 16
+    ps = pad_len * struct.pack('B', pad_len)
+    data += ps
+    wrapped = aes.encrypt(data)
+    attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
+    wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
+
+def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
+    """WPS and KWA error: Data after KWA"""
+    r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    # Encrypted Settings and data after KWA
+    m = hmac.new(authkey, data, hashlib.sha256)
+    kwa = m.digest()[0:8]
+    data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
+    data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
+    iv = 16*'\x99'
+    aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
+    pad_len = 16 - len(data) % 16
+    ps = pad_len * struct.pack('B', pad_len)
+    data += ps
+    wrapped = aes.encrypt(data)
+    attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
+    wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
+
+def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
+    """WPS and KWA error: KWA mismatch"""
+    r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    # Encrypted Settings and KWA with incorrect value
+    data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
+    iv = 16*'\x99'
+    aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
+    pad_len = 16 - len(data) % 16
+    ps = pad_len * struct.pack('B', pad_len)
+    data += ps
+    wrapped = aes.encrypt(data)
+    attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
+    wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
+
+def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, e_pk)
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M3 from STA")
+    msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
+    raw_m4_attrs = attrs
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 from STA")
+    msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
+
+    logger.debug("Send M6 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M6)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
+                            m1_attrs[ATTR_ENROLLEE_NONCE])
+    data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
+    raw_m6_attrs = attrs
+    m6 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m6)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M7 from STA")
+    msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
+
+    logger.debug("Send M8 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M8)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
+                            m1_attrs[ATTR_ENROLLEE_NONCE])
+    attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
+    attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
+    raw_m8_attrs = attrs
+    m8 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m8)
+    eap_id = (eap_id + 1) % 256
+
+    if no_connect:
+        logger.debug("Receive WSC_Done from STA")
+        msg = get_wsc_msg(dev[0])
+        if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
+            raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
+
+        hapd.request("SET ext_eapol_frame_io 0")
+        dev[0].request("SET ext_eapol_frame_io 0")
+
+        send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+
+        dev[0].wait_disconnected()
+        dev[0].request("REMOVE_NETWORK all")
+    elif connect:
+        logger.debug("Receive WSC_Done from STA")
+        msg = get_wsc_msg(dev[0])
+        if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
+            raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
+
+        hapd.request("SET ext_eapol_frame_io 0")
+        dev[0].request("SET ext_eapol_frame_io 0")
+
+        send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+
+        dev[0].wait_connected()
+    else:
+        # Verify STA NACK's the credential
+        msg = get_wsc_msg(dev[0])
+        if msg['wsc_opcode'] != WSC_NACK:
+            raise Exception("Unexpected message - expected WSC_Nack")
+        dev[0].request("WPS_CANCEL")
+        send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+        dev[0].wait_disconnected()
+
+def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
+               encr_type='\x00\x08', nw_key="12345678",
+               mac_addr='\x00\x00\x00\x00\x00\x00'):
+    attrs = ''
+    if nw_idx is not None:
+        attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
+    if ssid is not None:
+        attrs += build_wsc_attr(ATTR_SSID, ssid)
+    if auth_type is not None:
+        attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
+    if encr_type is not None:
+        attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
+    if nw_key is not None:
+        attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
+    if mac_addr is not None:
+        attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
+    return build_wsc_attr(ATTR_CRED, attrs)
+
+def test_wps_ext_cred_proto_success(dev, apdev):
+    """WPS and Credential: success"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr)
+    wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
+
+def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
+    """WPS and Credential: MAC Address mismatch"""
+    m8_cred = build_cred()
+    wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
+
+def test_wps_ext_cred_proto_zero_padding(dev, apdev):
+    """WPS and Credential: zeropadded attributes"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
+                         nw_key="12345678\x00")
+    wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
+
+def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
+    """WPS and Credential: SSID missing"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
+    wps_run_cred_proto(dev, apdev, m8_cred)
+
+def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
+    """WPS and Credential: Zero-length SSID"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr, ssid="")
+    wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
+
+def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
+    """WPS and Credential: Auth Type missing"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
+    wps_run_cred_proto(dev, apdev, m8_cred)
+
+def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
+    """WPS and Credential: Encr Type missing"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
+    wps_run_cred_proto(dev, apdev, m8_cred)
+
+def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
+    """WPS and Credential: Network Key missing"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
+    wps_run_cred_proto(dev, apdev, m8_cred)
+
+def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
+    """WPS and Credential: Network Key missing (open)"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
+                         encr_type='\x00\x01', nw_key=None, ssid="foo")
+    wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
+
+def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
+    """WPS and Credential: MAC Address missing"""
+    m8_cred = build_cred(mac_addr=None)
+    wps_run_cred_proto(dev, apdev, m8_cred)
+
+def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
+    """WPS and Credential: Invalid Encr Type"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
+    wps_run_cred_proto(dev, apdev, m8_cred)
+
+def test_wps_ext_cred_proto_missing_cred(dev, apdev):
+    """WPS and Credential: Missing Credential"""
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    m8_cred = ''
+    wps_run_cred_proto(dev, apdev, m8_cred)
+
+def test_wps_ext_proto_m2_no_public_key(dev, apdev):
+    """WPS and no Public Key in M2"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, None)
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    # Verify STA NACK's the credential
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
+    """WPS and invalid Public Key in M2"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, 192*'\xff')
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    # Verify STA NACK's the credential
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
+    """WPS and Public Key OOM in M2"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, e_pk)
+    with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
+        send_wsc_msg(dev[0], bssid, m2)
+        eap_id = (eap_id + 1) % 256
+
+        # Verify STA NACK's the credential
+        msg = get_wsc_msg(dev[0])
+        if msg['wsc_opcode'] != WSC_NACK:
+            raise Exception("Unexpected message - expected WSC_Nack")
+        dev[0].request("WPS_CANCEL")
+        send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+        dev[0].wait_disconnected()
+
+def test_wps_ext_proto_nack_m3(dev, apdev):
+    """WPS and NACK M3"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, e_pk)
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M3 from STA")
+    msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
+
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
+                            r_nonce, config_error='\x01\x23')
+    send_wsc_msg(dev[0], bssid, msg)
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
+    if ev is None:
+        raise Exception("Failure not reported")
+    if "msg=7 config_error=291" not in ev:
+        raise Exception("Unexpected failure reason: " + ev)
+
+def test_wps_ext_proto_nack_m5(dev, apdev):
+    """WPS and NACK M5"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, e_pk)
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M3 from STA")
+    msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
+    raw_m4_attrs = attrs
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 from STA")
+    msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
+
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
+                            r_nonce, config_error='\x01\x24')
+    send_wsc_msg(dev[0], bssid, msg)
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
+    if ev is None:
+        raise Exception("Failure not reported")
+    if "msg=9 config_error=292" not in ev:
+        raise Exception("Unexpected failure reason: " + ev)
+
+def wps_nack_m3(dev, apdev):
+    pin = "00000000"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M3 from STA")
+    msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
+    return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
+
+def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
+    """WPS and NACK M3 missing Config Error"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
+    """WPS and NACK M3 missing E-Nonce"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, None, r_nonce)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
+    """WPS and NACK M3 E-Nonce mismatch"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
+    """WPS and NACK M3 missing R-Nonce"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, e_nonce, None)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
+    """WPS and NACK M3 R-Nonce mismatch"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
+    """WPS and NACK M3 no Message Type"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
+    """WPS and NACK M3 invalid Message Type"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
+    """WPS and NACK M3 invalid attribute"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    attrs = '\x10\x10\x00'
+    msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
+    """WPS and ACK M3 missing E-Nonce"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_ack(eap_id, None, r_nonce)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
+    """WPS and ACK M3 E-Nonce mismatch"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
+    """WPS and ACK M3 missing R-Nonce"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_ack(eap_id, e_nonce, None)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
+    """WPS and ACK M3 R-Nonce mismatch"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
+    """WPS and ACK M3 no Message Type"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
+    """WPS and ACK M3 invalid Message Type"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send NACK to STA")
+    msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
+    """WPS and ACK M3 invalid attribute"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send ACK to STA")
+    attrs = '\x10\x10\x00'
+    msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def test_wps_ext_proto_ack_m3(dev, apdev):
+    """WPS and ACK M3"""
+    eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
+    logger.debug("Send ACK to STA")
+    msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
+    send_wsc_msg(dev[0], bssid, msg)
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    dev[0].flush_scan_cache()
+
+def wps_to_m3_helper(dev, apdev):
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+    wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Receive M1 from STA")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
+    eap_id = (msg['eap_identifier'] + 1) % 256
+
+    authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
+                                    mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
+                                                m1_attrs[ATTR_PUBLIC_KEY], e_pk)
+
+    logger.debug("Send M2 to STA")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
+                                m1_attrs[ATTR_ENROLLEE_NONCE],
+                                r_nonce, uuid_r, e_pk)
+    send_wsc_msg(dev[0], bssid, m2)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M3 from STA")
+    msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
+    return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
+
+def wps_to_m3(dev, apdev):
+    eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey = wps_to_m3_helper(dev, apdev)
+    return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
+
+def wps_to_m5(dev, apdev):
+    eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey = wps_to_m3_helper(dev, apdev)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
+    raw_m4_attrs = attrs
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 from STA")
+    msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
+
+    return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
+
+def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
+    """WPS and no R-Hash1 in M4"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, m3, attrs)
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
+    """WPS and no R-Hash2 in M4"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, m3, attrs)
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
+    """WPS and no R-SNonce1 in M4"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    data = ''
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, m3, attrs)
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
+    """WPS and invalid pad string in M4"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+
+    m = hmac.new(authkey, data, hashlib.sha256)
+    kwa = m.digest()[0:8]
+    data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
+    iv = 16*'\x99'
+    aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
+    pad_len = 16 - len(data) % 16
+    ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
+    data += ps
+    wrapped = aes.encrypt(data)
+    attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
+
+    attrs += build_attr_authenticator(authkey, m3, attrs)
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
+    """WPS and invalid pad value in M4"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+
+    m = hmac.new(authkey, data, hashlib.sha256)
+    kwa = m.digest()[0:8]
+    data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
+    iv = 16*'\x99'
+    aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
+    pad_len = 16 - len(data) % 16
+    ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
+    data += ps
+    wrapped = aes.encrypt(data)
+    attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
+
+    attrs += build_attr_authenticator(authkey, m3, attrs)
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
+    """WPS and no Encr Settings in M4"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
+
+    logger.debug("Send M4 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    attrs += build_attr_authenticator(authkey, m3, attrs)
+    m4 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m4)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M5 (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
+    """WPS and no R-SNonce2 in M6"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
+
+    logger.debug("Send M6 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M6)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
+    data = ''
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, m5, attrs)
+    m6 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m6)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M7 (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
+    """WPS and no Encr Settings in M6"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
+
+    logger.debug("Send M6 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M6)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
+    #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, m5, attrs)
+    m6 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m6)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M7 (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
+    """WPS and no Encr Settings in M6"""
+    eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
+
+    logger.debug("Send M6 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M6)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, m5, attrs)
+    raw_m6_attrs = attrs
+    m6 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m6)
+    eap_id = (eap_id + 1) % 256
+
+    logger.debug("Receive M7 from STA")
+    msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
+
+    logger.debug("Send M8 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M8)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
+    attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
+    raw_m8_attrs = attrs
+    m8 = build_eap_wsc(1, eap_id, attrs)
+    send_wsc_msg(dev[0], bssid, m8)
+
+    logger.debug("Receive WSC_Done (NACK) from STA")
+    msg = get_wsc_msg(dev[0])
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_Nack")
+
+    dev[0].request("WPS_CANCEL")
+    send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
+    dev[0].wait_disconnected()
+
+def wps_start_ext_reg(apdev, dev):
+    addr = dev.own_addr()
+    bssid = apdev['bssid']
+    ssid = "test-wps-conf"
+    appin = "12345670"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "ap_pin": appin }
+    hapd = hostapd.add_ap(apdev, params)
+
+    dev.scan_for_bss(bssid, freq="2412")
+    hapd.request("SET ext_eapol_frame_io 1")
+    dev.request("SET ext_eapol_frame_io 1")
+
+    dev.request("WPS_REG " + bssid + " " + appin)
+
+    return addr,bssid,hapd
+
+def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
+    addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive M1 from AP")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
+    mac_addr = m1_attrs[ATTR_MAC_ADDR]
+    e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
+    e_pk = m1_attrs[ATTR_PUBLIC_KEY]
+
+    appin = '12345670'
+    uuid_r = 16*'\x33'
+    r_nonce = 16*'\x44'
+    own_private, r_pk = wsc_dh_init()
+    authkey,keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
+
+    logger.debug("Send M2 to AP")
+    m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
+                                e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
+    send_wsc_msg(hapd, addr, m2)
+
+    logger.debug("Receive M3 from AP")
+    msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
+
+    logger.debug("Send M4 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M4)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
+    attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
+    data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
+    raw_m4_attrs = attrs
+    m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m4)
+
+    logger.debug("Receive M5 from AP")
+    msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
+
+    logger.debug("Send M6 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M6)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
+    raw_m6_attrs = attrs
+    m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m6)
+
+    logger.debug("Receive M7 from AP")
+    msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
+
+    logger.debug("Send M8 to STA")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M8)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    if ap_settings:
+        attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
+    attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
+    raw_m8_attrs = attrs
+    m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m8)
+
+    if success:
+        ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
+        if ev is None:
+            raise Exception("New AP settings not reported")
+        logger.debug("Receive WSC_Done from AP")
+        msg = get_wsc_msg(hapd)
+        if msg['wsc_opcode'] != WSC_Done:
+            raise Exception("Unexpected message - expected WSC_Done")
+
+        logger.debug("Send WSC_ACK to AP")
+        ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
+                              eap_code=2)
+        send_wsc_msg(hapd, addr, ack)
+        dev[0].wait_disconnected()
+    else:
+        ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
+        if ev is None:
+            raise Exception("WPS failure not reported")
+        logger.debug("Receive WSC_NACK from AP")
+        msg = get_wsc_msg(hapd)
+        if msg['wsc_opcode'] != WSC_NACK:
+            raise Exception("Unexpected message - expected WSC_NACK")
+
+        logger.debug("Send WSC_NACK to AP")
+        nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
+                                eap_code=2)
+        send_wsc_msg(hapd, addr, nack)
+        dev[0].wait_disconnected()
+
+def test_wps_ext_ap_settings_success(dev, apdev):
+    """WPS and AP Settings: success"""
+    ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
+    ap_settings += build_wsc_attr(ATTR_SSID, "test")
+    ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
+    ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
+    ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
+    ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
+    wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
+
+def test_wps_ext_ap_settings_missing(dev, apdev):
+    """WPS and AP Settings: missing"""
+    wps_run_ap_settings_proto(dev, apdev, None, False)
+
+def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
+    """WPS and AP Settings: MAC Address mismatch"""
+    ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
+    ap_settings += build_wsc_attr(ATTR_SSID, "test")
+    ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
+    ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
+    ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
+    ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
+    wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
+
+def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
+    """WPS and AP Settings: missing MAC Address"""
+    ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
+    ap_settings += build_wsc_attr(ATTR_SSID, "test")
+    ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
+    ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
+    ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
+    wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
+
+def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
+    """WPS and AP Settings: reject Encr Type"""
+    ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
+    ap_settings += build_wsc_attr(ATTR_SSID, "test")
+    ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
+    ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
+    ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
+    ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
+    wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
+
+def test_wps_ext_ap_settings_m2d(dev, apdev):
+    """WPS and AP Settings: M2D"""
+    addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive M1 from AP")
+    msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
+    e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
+
+    r_nonce = 16*'\x44'
+    uuid_r = 16*'\x33'
+
+    logger.debug("Send M2D to AP")
+    m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
+                                   e_nonce, r_nonce, uuid_r,
+                                   dev_pw_id='\x00\x00', eap_code=2)
+    send_wsc_msg(hapd, addr, m2d)
+
+    ev = hapd.wait_event(["WPS-M2D"], timeout=5)
+    if ev is None:
+        raise Exception("M2D not reported")
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
+    logger.debug("Receive WSC_NACK from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_NACK:
+        raise Exception("Unexpected message - expected WSC_NACK")
+
+    logger.debug("Send WSC_NACK to AP")
+    nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
+                            eap_code=2)
+    send_wsc_msg(hapd, dev.own_addr(), nack)
+    dev.wait_disconnected()
+
+def test_wps_ext_m3_missing_e_hash1(dev, apdev):
+    """WPS proto: M3 missing E-Hash1"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m3_missing_e_hash2(dev, apdev):
+    """WPS proto: M3 missing E-Hash2"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
+    """WPS proto: M5 missing E-SNonce1"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    logger.debug("Receive M4 from AP")
+    msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
+
+    logger.debug("Send M5 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M5)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
+    data = ''
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
+    raw_m5_attrs = attrs
+    m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m5)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
+    """WPS proto: M5 E-SNonce1 mismatch"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    logger.debug("Receive M4 from AP")
+    msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
+
+    logger.debug("Send M5 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M5)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
+    raw_m5_attrs = attrs
+    m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m5)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
+    """WPS proto: M7 missing E-SNonce2"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    logger.debug("Receive M4 from AP")
+    msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
+
+    logger.debug("Send M5 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M5)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
+    raw_m5_attrs = attrs
+    m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m5)
+
+    logger.debug("Receive M6 from AP")
+    msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
+
+    logger.debug("Send M7 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M7)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
+    data = ''
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
+    m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    raw_m7_attrs = attrs
+    send_wsc_msg(hapd, addr, m7)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
+    """WPS proto: M7 E-SNonce2 mismatch"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    logger.debug("Receive M4 from AP")
+    msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
+
+    logger.debug("Send M5 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M5)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
+    raw_m5_attrs = attrs
+    m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m5)
+
+    logger.debug("Receive M6 from AP")
+    msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
+
+    logger.debug("Send M7 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M7)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
+    m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    raw_m7_attrs = attrs
+    send_wsc_msg(hapd, addr, m7)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m1_pubkey_oom(dev, apdev):
+    """WPS proto: M1 PubKey OOM"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
+        m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                    e_nonce, e_pk)
+        send_wsc_msg(hapd, addr, m1)
+        wps_wait_eap_failure(hapd, dev[0])
+
+def wps_wait_eap_failure(hapd, dev):
+    ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("EAP-Failure not reported")
+    dev.wait_disconnected()
+
+def test_wps_ext_m3_m1(dev, apdev):
+    """WPS proto: M3 replaced with M1"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3(M1) to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M1)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m5_m3(dev, apdev):
+    """WPS proto: M5 replaced with M3"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    logger.debug("Receive M4 from AP")
+    msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
+
+    logger.debug("Send M5(M3) to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
+    raw_m5_attrs = attrs
+    m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m5)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m3_m2(dev, apdev):
+    """WPS proto: M3 replaced with M2"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3(M2) to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M2)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m3_m5(dev, apdev):
+    """WPS proto: M3 replaced with M5"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3(M5) to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M5)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m3_m7(dev, apdev):
+    """WPS proto: M3 replaced with M7"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3(M7) to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M7)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m3_done(dev, apdev):
+    """WPS proto: M3 replaced with WSC_Done"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3(WSC_Done) to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_WSC_DONE)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
+    send_wsc_msg(hapd, addr, m3)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_nack_invalid(dev, apdev):
+    """WPS proto: M2 followed by invalid NACK"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_NACK to AP")
+    attrs = '\x10\x00\x00'
+    nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
+    send_wsc_msg(hapd, addr, nack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
+    """WPS proto: M2 followed by NACK without Msg Type"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_NACK to AP")
+    nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
+                            msg_type=None, eap_code=2)
+    send_wsc_msg(hapd, addr, nack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
+    """WPS proto: M2 followed by NACK with invalid Msg Type"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_NACK to AP")
+    nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
+                            msg_type=WPS_WSC_ACK, eap_code=2)
+    send_wsc_msg(hapd, addr, nack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
+    """WPS proto: M2 followed by NACK with e-nonce mismatch"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_NACK to AP")
+    nack,attrs = build_nack(msg['eap_identifier'], 16*'\x00', r_nonce,
+                            eap_code=2)
+    send_wsc_msg(hapd, addr, nack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_nack_no_config_error(dev, apdev):
+    """WPS proto: M2 followed by NACK without Config Error"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_NACK to AP")
+    nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
+                            config_error=None, eap_code=2)
+    send_wsc_msg(hapd, addr, nack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_ack_invalid(dev, apdev):
+    """WPS proto: M2 followed by invalid ACK"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_ACK to AP")
+    attrs = '\x10\x00\x00'
+    ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
+    send_wsc_msg(hapd, addr, ack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_ack(dev, apdev):
+    """WPS proto: M2 followed by ACK"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_ACK to AP")
+    ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
+    send_wsc_msg(hapd, addr, ack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
+    """WPS proto: M2 followed by ACK missing Msg Type"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_ACK to AP")
+    ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
+                          msg_type=None, eap_code=2)
+    send_wsc_msg(hapd, addr, ack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
+    """WPS proto: M2 followed by ACK with invalid Msg Type"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_ACK to AP")
+    ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
+                          msg_type=WPS_WSC_NACK, eap_code=2)
+    send_wsc_msg(hapd, addr, ack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
+    """WPS proto: M2 followed by ACK with e-nonce mismatch"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send WSC_ACK to AP")
+    ack,attrs = build_ack(msg['eap_identifier'], 16*'\x00', r_nonce,
+                          eap_code=2)
+    send_wsc_msg(hapd, addr, ack)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m1_invalid(dev, apdev):
+    """WPS proto: M1 failing parsing"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    logger.debug("Send M1 to AP")
+    attrs = '\x10\x00\x00'
+    m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m1)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m1_missing_msg_type(dev, apdev):
+    """WPS proto: M1 missing Msg Type"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    logger.debug("Send M1 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m1)
+
+    wps_wait_ap_nack(hapd, dev[0], 16*'\x00', 16*'\x00')
+
+def wps_ext_wsc_done(dev, apdev):
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    logger.debug("Receive M4 from AP")
+    msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
+
+    logger.debug("Send M5 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M5)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
+    raw_m5_attrs = attrs
+    m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m5)
+
+    logger.debug("Receive M6 from AP")
+    msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
+
+    logger.debug("Send M7 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M7)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
+    m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    raw_m7_attrs = attrs
+    send_wsc_msg(hapd, addr, m7)
+
+    logger.debug("Receive M8 from AP")
+    msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
+    return hapd, msg, e_nonce, r_nonce
+
+def test_wps_ext_wsc_done_invalid(dev, apdev):
+    """WPS proto: invalid WSC_Done"""
+    hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
+
+    logger.debug("Send WSC_Done to AP")
+    attrs = '\x10\x00\x00'
+    wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
+    send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
+    """WPS proto: invalid WSC_Done"""
+    hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
+
+    logger.debug("Send WSC_Done to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    #attrs += build_attr_msg_type(WPS_WSC_DONE)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
+    send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
+    """WPS proto: WSC_Done with wrong Msg Type"""
+    hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
+
+    logger.debug("Send WSC_Done to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_WSC_ACK)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
+    send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
+    """WPS proto: WSC_Done without e_nonce"""
+    hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
+
+    logger.debug("Send WSC_Done to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_WSC_DONE)
+    #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
+    send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
+    """WPS proto: WSC_Done without r_nonce"""
+    hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
+
+    logger.debug("Send WSC_Done to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_WSC_DONE)
+    attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
+    #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
+    send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
+
+    wps_wait_eap_failure(hapd, dev[0])
+
+def test_wps_ext_m7_no_encr_settings(dev, apdev):
+    """WPS proto: M7 without Encr Settings"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk)
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+    r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
+    r_pk = m2_attrs[ATTR_PUBLIC_KEY]
+
+    authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
+                                    r_nonce)
+    e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
+
+    logger.debug("Send M3 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M3)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
+    attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
+    attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
+    raw_m3_attrs = attrs
+    m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m3)
+
+    logger.debug("Receive M4 from AP")
+    msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
+
+    logger.debug("Send M5 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M5)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
+    attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
+    raw_m5_attrs = attrs
+    m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    send_wsc_msg(hapd, addr, m5)
+
+    logger.debug("Receive M6 from AP")
+    msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
+
+    logger.debug("Send M7 to AP")
+    attrs = build_wsc_attr(ATTR_VERSION, '\x10')
+    attrs += build_attr_msg_type(WPS_M7)
+    attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
+    #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
+    #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
+    attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
+    m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
+    raw_m7_attrs = attrs
+    send_wsc_msg(hapd, addr, m7)
+
+    wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
+
+def test_wps_ext_m1_workaround(dev, apdev):
+    """WPS proto: M1 Manufacturer/Model workaround"""
+    pin = "12345670"
+    addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
+    wps_ext_eap_identity_req(dev[0], hapd, bssid)
+    wps_ext_eap_identity_resp(hapd, dev[0], addr)
+
+    logger.debug("Receive WSC/Start from AP")
+    msg = get_wsc_msg(hapd)
+    if msg['wsc_opcode'] != WSC_Start:
+        raise Exception("Unexpected Op-Code for WSC/Start")
+
+    mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
+    uuid_e = 16*'\x11'
+    e_nonce = 16*'\x22'
+    own_private, e_pk = wsc_dh_init()
+
+    logger.debug("Send M1 to AP")
+    m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
+                                e_nonce, e_pk, manufacturer='Apple TEST',
+                                model_name='AirPort', config_methods='\xff\xff')
+    send_wsc_msg(hapd, addr, m1)
+
+    logger.debug("Receive M2 from AP")
+    msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
+
+def test_ap_wps_disable_enable(dev, apdev):
+    """WPS and DISABLE/ENABLE AP"""
+    hapd = wps_start_ap(apdev[0])
+    hapd.disable()
+    hapd.enable()
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
+
+def test_ap_wps_upnp_web_oom(dev, apdev, params):
+    """hostapd WPS UPnP web OOM"""
+    ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
+    hapd = add_ssdp_ap(apdev[0], ap_uuid)
+
+    location = ssdp_get_location(ap_uuid)
+    url = urlparse.urlparse(location)
+    urls = upnp_get_urls(location)
+    eventurl = urlparse.urlparse(urls['event_sub_url'])
+    ctrlurl = urlparse.urlparse(urls['control_url'])
+
+    conn = httplib.HTTPConnection(url.netloc)
+    with alloc_fail(hapd, 1, "web_connection_parse_get"):
+        conn.request("GET", "/wps_device.xml")
+        try:
+            resp = conn.getresponse()
+        except:
+            pass
+
+    conn = httplib.HTTPConnection(url.netloc)
+    conn.request("GET", "/unknown")
+    resp = conn.getresponse()
+    if resp.status != 404:
+        raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
+
+    with alloc_fail(hapd, 1, "web_connection_parse_get"):
+        conn.request("GET", "/unknown")
+        try:
+            resp = conn.getresponse()
+            print resp.status
+        except:
+            pass
+
+    conn = httplib.HTTPConnection(url.netloc)
+    conn.request("GET", "/wps_device.xml")
+    resp = conn.getresponse()
+    if resp.status != 200:
+        raise Exception("GET /wps_device.xml failed")
+
+    conn = httplib.HTTPConnection(url.netloc)
+    resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
+    if resp.status != 200:
+        raise Exception("GetDeviceInfo failed")
+
+    with alloc_fail(hapd, 1, "web_process_get_device_info"):
+        conn = httplib.HTTPConnection(url.netloc)
+        resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
+        if resp.status != 500:
+            raise Exception("Internal error not reported from GetDeviceInfo OOM")
+
+    with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
+        conn = httplib.HTTPConnection(url.netloc)
+        resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
+        if resp.status != 500:
+            raise Exception("Internal error not reported from GetDeviceInfo OOM")
+
+    with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
+        conn = httplib.HTTPConnection(url.netloc)
+        try:
+            resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
+        except:
+            pass
+
+    conn = httplib.HTTPConnection(url.netloc)
+    resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
+    if resp.status != 200:
+        raise Exception("GetDeviceInfo failed")
+
+    # No NewWLANEventType in PutWLANResponse NewMessage
+    conn = httplib.HTTPConnection(url.netloc)
+    resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
+    if resp.status != 600:
+        raise Exception("Unexpected HTTP response: %d" % resp.status)
+
+    # No NewWLANEventMAC in PutWLANResponse NewMessage
+    conn = httplib.HTTPConnection(url.netloc)
+    resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
+                            newmsg="foo", neweventtype="1")
+    if resp.status != 600:
+        raise Exception("Unexpected HTTP response: %d" % resp.status)
+
+    # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
+    conn = httplib.HTTPConnection(url.netloc)
+    resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
+                            newmsg="foo", neweventtype="1",
+                            neweventmac="foo")
+    if resp.status != 600:
+        raise Exception("Unexpected HTTP response: %d" % resp.status)
+
+    # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
+    # Ignored unexpected PutWLANResponse WLANEventType 1
+    conn = httplib.HTTPConnection(url.netloc)
+    resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
+                            newmsg="foo", neweventtype="1",
+                            neweventmac="00.11.22.33.44.55")
+    if resp.status != 500:
+        raise Exception("Unexpected HTTP response: %d" % resp.status)
+
+    # PutWLANResponse NewMessage with invalid EAP message
+    conn = httplib.HTTPConnection(url.netloc)
+    resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
+                            newmsg="foo", neweventtype="2",
+                            neweventmac="00:11:22:33:44:55")
+    if resp.status != 200:
+        raise Exception("Unexpected HTTP response: %d" % resp.status)
+
+    with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
+        conn = httplib.HTTPConnection(url.netloc)
+        headers = { "callback": '<http://127.0.0.1:12345/event>',
+                    "NT": "upnp:event",
+                    "timeout": "Second-1234" }
+        conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
+        try:
+            resp = conn.getresponse()
+        except:
+            pass
+
+    with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
+        conn = httplib.HTTPConnection(url.netloc)
+        headers = { "callback": '<http://127.0.0.1:12345/event>',
+                    "NT": "upnp:event",
+                    "timeout": "Second-1234" }
+        conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
+        resp = conn.getresponse()
+        if resp.status != 500:
+            raise Exception("Unexpected HTTP response: %d" % resp.status)
+
+    with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
+        conn = httplib.HTTPConnection(url.netloc)
+        headers = { "callback": '<http://127.0.0.1:12345/event>',
+                    "NT": "upnp:event",
+                    "timeout": "Second-1234" }
+        conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
+        try:
+            resp = conn.getresponse()
+        except:
+            pass
+
+    with alloc_fail(hapd, 1, "web_connection_unimplemented"):
+        conn = httplib.HTTPConnection(url.netloc)
+        conn.request("HEAD", "/wps_device.xml")
+        try:
+            resp = conn.getresponse()
+        except:
+            pass
+
+def test_ap_wps_frag_ack_oom(dev, apdev):
+    """WPS and fragment ack OOM"""
+    dev[0].request("SET wps_fragment_size 50")
+    hapd = wps_start_ap(apdev[0])
+    with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
+        wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
+
+def wait_scan_stopped(dev):
+    dev.request("ABORT_SCAN")
+    for i in range(50):
+        res = dev.get_driver_status_field("scan_state")
+        if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
+            break
+        logger.debug("Waiting for scan to complete")
+        time.sleep(0.1)
+
+def test_ap_wps_eap_wsc_errors(dev, apdev):
+    """WPS and EAP-WSC error cases"""
+    ssid = "test-wps-conf-pin"
+    appin = "12345670"
+    params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
+               "wpa_passphrase": "12345678", "wpa": "2",
+               "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
+               "fragment_size": "300", "ap_pin": appin }
+    hapd = hostapd.add_ap(apdev[0], params)
+    bssid = apdev[0]['bssid']
+
+    pin = dev[0].wps_read_pin()
+    hapd.request("WPS_PIN any " + pin)
+    dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
+    dev[0].dump_monitor()
+
+    dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
+                   "new passphrase", no_wait=True)
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
+    if ev is None:
+        raise Exception("WPS-FAIL not reported")
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    wait_scan_stopped(dev[0])
+    dev[0].dump_monitor()
+
+    dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
+                   "new passphrase", no_wait=True)
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
+    if ev is None:
+        raise Exception("WPS-FAIL not reported")
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    wait_scan_stopped(dev[0])
+    dev[0].dump_monitor()
+
+    dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
+                   "new passphrase", no_wait=True)
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
+    if ev is None:
+        raise Exception("WPS-FAIL not reported")
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    wait_scan_stopped(dev[0])
+    dev[0].dump_monitor()
+
+    dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
+                   "new passphrase", no_wait=True)
+    ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
+    if ev is None:
+        raise Exception("WPS-FAIL not reported")
+    dev[0].request("WPS_CANCEL")
+    dev[0].wait_disconnected()
+    wait_scan_stopped(dev[0])
+    dev[0].dump_monitor()
+
+    tests = [ "eap_wsc_init",
+              "eap_msg_alloc;eap_wsc_build_msg",
+              "wpabuf_alloc;eap_wsc_process_fragment" ]
+    for func in tests:
+        with alloc_fail(dev[0], 1, func):
+            dev[0].request("WPS_PIN %s %s" % (bssid, pin))
+            wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
+            dev[0].request("WPS_CANCEL")
+            dev[0].wait_disconnected()
+            wait_scan_stopped(dev[0])
+            dev[0].dump_monitor()
+
+    with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
+        dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
+                       "CCMP", "new passphrase", no_wait=True)
+        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
+        dev[0].request("WPS_CANCEL")
+        dev[0].wait_disconnected()
+        wait_scan_stopped(dev[0])
+        dev[0].dump_monitor()
+
+def test_ap_wps_eap_wsc(dev, apdev):
+    """WPS and EAP-WSC in network profile"""
+    params = int_eap_server_params()
+    params["wps_state"] = "2"
+    hapd = hostapd.add_ap(apdev[0], params)
+    bssid = apdev[0]['bssid']
+
+    logger.info("Unexpected identity")
+    dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
+                   eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
+                   wait_connect=False)
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("No EAP-Failure seen")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+    logger.info("No phase1 parameter")
+    dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
+                   eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
+                   wait_connect=False)
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAP method start")
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("No EAP-Failure seen")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+    logger.info("No PIN/PBC in phase1")
+    dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
+                   eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
+                   phase1="foo", wait_connect=False)
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAP method start")
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("No EAP-Failure seen")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+    logger.info("Invalid pkhash in phase1")
+    dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
+                   eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
+                   phase1="foo pkhash=q pbc=1", wait_connect=False)
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAP method start")
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("No EAP-Failure seen")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+    logger.info("Zero fragment_size")
+    dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
+                   eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
+                   fragment_size="0", phase1="pin=12345670", wait_connect=False)
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAP method start")
+    ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
+    if ev is None:
+        raise Exception("No M2D seen")
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("No EAP-Failure seen")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+    logger.info("Missing new_auth")
+    dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
+                   eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
+                   phase1="pin=12345670 new_ssid=aa", wait_connect=False)
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAP method start")
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("No EAP-Failure seen")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+    logger.info("Missing new_encr")
+    dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
+                   eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
+                   phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAP method start")
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("No EAP-Failure seen")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()
+
+    logger.info("Missing new_key")
+    dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
+                   eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
+                   phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
+                   wait_connect=False)
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
+    if ev is None:
+        raise Exception("Timeout on EAP method start")
+    ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
+    if ev is None:
+        raise Exception("No EAP-Failure seen")
+    dev[0].request("REMOVE_NETWORK all")
+    dev[0].wait_disconnected()