tests: Try to clear scan results after regulatory domain changes
[mech_eap.git] / tests / hwsim / test_ap_wps.py
1 # WPS tests
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import os
8 import time
9 import subprocess
10 import logging
11 logger = logging.getLogger()
12 import re
13 import socket
14 import httplib
15 import urlparse
16 import urllib
17 import xml.etree.ElementTree as ET
18 import StringIO
19
20 import hwsim_utils
21 import hostapd
22 from wpasupplicant import WpaSupplicant
23
24 def test_ap_wps_init(dev, apdev):
25     """Initial AP configuration with first WPS Enrollee"""
26     ssid = "test-wps"
27     hostapd.add_ap(apdev[0]['ifname'],
28                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
29     hapd = hostapd.Hostapd(apdev[0]['ifname'])
30     logger.info("WPS provisioning step")
31     hapd.request("WPS_PBC")
32     if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
33         raise Exception("PBC status not shown correctly")
34
35     id = dev[0].add_network()
36     dev[0].set_network_quoted(id, "ssid", "home")
37     dev[0].set_network_quoted(id, "psk", "12345678")
38     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
39
40     id = dev[0].add_network()
41     dev[0].set_network_quoted(id, "ssid", "home2")
42     dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
43     dev[0].set_network(id, "key_mgmt", "NONE")
44     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
45
46     dev[0].request("WPS_PBC")
47     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
48     if ev is None:
49         raise Exception("Association with the AP timed out")
50     status = dev[0].get_status()
51     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
52         raise Exception("Not fully connected")
53     if status['ssid'] != ssid:
54         raise Exception("Unexpected SSID")
55     if status['pairwise_cipher'] != 'CCMP':
56         raise Exception("Unexpected encryption configuration")
57     if status['key_mgmt'] != 'WPA2-PSK':
58         raise Exception("Unexpected key_mgmt")
59
60     status = hapd.request("WPS_GET_STATUS")
61     if "PBC Status: Disabled" not in status:
62         raise Exception("PBC status not shown correctly")
63     if "Last WPS result: Success" not in status:
64         raise Exception("Last WPS result not shown correctly")
65     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
66         raise Exception("Peer address not shown correctly")
67     conf = hapd.request("GET_CONFIG")
68     if "wps_state=configured" not in conf:
69         raise Exception("AP not in WPS configured state")
70     if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
71         raise Exception("Unexpected rsn_pairwise_cipher")
72     if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
73         raise Exception("Unexpected wpa_pairwise_cipher")
74     if "group_cipher=TKIP" not in conf:
75         raise Exception("Unexpected group_cipher")
76
77     if len(dev[0].list_networks()) != 3:
78         raise Exception("Unexpected number of network blocks")
79
80 def test_ap_wps_init_2ap_pbc(dev, apdev):
81     """Initial two-radio AP configuration with first WPS PBC Enrollee"""
82     ssid = "test-wps"
83     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
84     hostapd.add_ap(apdev[0]['ifname'], params)
85     hostapd.add_ap(apdev[1]['ifname'], params)
86     hapd = hostapd.Hostapd(apdev[0]['ifname'])
87     logger.info("WPS provisioning step")
88     hapd.request("WPS_PBC")
89     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
90     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
91     bss = dev[0].get_bss(apdev[0]['bssid'])
92     if "[WPS-PBC]" not in bss['flags']:
93         raise Exception("WPS-PBC flag missing from AP1")
94     bss = dev[0].get_bss(apdev[1]['bssid'])
95     if "[WPS-PBC]" not in bss['flags']:
96         raise Exception("WPS-PBC flag missing from AP2")
97     dev[0].dump_monitor()
98     dev[0].request("SET wps_cred_processing 2")
99     dev[0].request("WPS_PBC")
100     ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
101     dev[0].request("SET wps_cred_processing 0")
102     if ev is None:
103         raise Exception("WPS cred event not seen")
104     if "100e" not in ev:
105         raise Exception("WPS attributes not included in the cred event")
106     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
107     if ev is None:
108         raise Exception("Association with the AP timed out")
109
110     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
111     dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
112     bss = dev[1].get_bss(apdev[0]['bssid'])
113     if "[WPS-PBC]" in bss['flags']:
114         raise Exception("WPS-PBC flag not cleared from AP1")
115     bss = dev[1].get_bss(apdev[1]['bssid'])
116     if "[WPS-PBC]" in bss['flags']:
117         raise Exception("WPS-PBC flag not cleared from AP2")
118
119 def test_ap_wps_init_2ap_pin(dev, apdev):
120     """Initial two-radio AP configuration with first WPS PIN Enrollee"""
121     ssid = "test-wps"
122     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
123     hostapd.add_ap(apdev[0]['ifname'], params)
124     hostapd.add_ap(apdev[1]['ifname'], params)
125     hapd = hostapd.Hostapd(apdev[0]['ifname'])
126     logger.info("WPS provisioning step")
127     pin = dev[0].wps_read_pin()
128     hapd.request("WPS_PIN any " + pin)
129     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
130     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
131     bss = dev[0].get_bss(apdev[0]['bssid'])
132     if "[WPS-AUTH]" not in bss['flags']:
133         raise Exception("WPS-AUTH flag missing from AP1")
134     bss = dev[0].get_bss(apdev[1]['bssid'])
135     if "[WPS-AUTH]" not in bss['flags']:
136         raise Exception("WPS-AUTH flag missing from AP2")
137     dev[0].dump_monitor()
138     dev[0].request("WPS_PIN any " + pin)
139     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
140     if ev is None:
141         raise Exception("Association with the AP timed out")
142
143     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
144     dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
145     bss = dev[1].get_bss(apdev[0]['bssid'])
146     if "[WPS-AUTH]" in bss['flags']:
147         raise Exception("WPS-AUTH flag not cleared from AP1")
148     bss = dev[1].get_bss(apdev[1]['bssid'])
149     if "[WPS-AUTH]" in bss['flags']:
150         raise Exception("WPS-AUTH flag not cleared from AP2")
151
152 def test_ap_wps_init_through_wps_config(dev, apdev):
153     """Initial AP configuration using wps_config command"""
154     ssid = "test-wps-init-config"
155     hostapd.add_ap(apdev[0]['ifname'],
156                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
157     hapd = hostapd.Hostapd(apdev[0]['ifname'])
158     if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
159         raise Exception("WPS_CONFIG command failed")
160     ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
161     if ev is None:
162         raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
163     # It takes some time for the AP to update Beacon and Probe Response frames,
164     # so wait here before requesting the scan to be started to avoid adding
165     # extra five second wait to the test due to fetching obsolete scan results.
166     hapd.ping()
167     time.sleep(0.2)
168     dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
169                    pairwise="CCMP", group="CCMP")
170
171 def test_ap_wps_conf(dev, apdev):
172     """WPS PBC provisioning with configured AP"""
173     ssid = "test-wps-conf"
174     hostapd.add_ap(apdev[0]['ifname'],
175                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
176                      "wpa_passphrase": "12345678", "wpa": "2",
177                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
178     hapd = hostapd.Hostapd(apdev[0]['ifname'])
179     logger.info("WPS provisioning step")
180     hapd.request("WPS_PBC")
181     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
182     dev[0].dump_monitor()
183     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
184     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
185     if ev is None:
186         raise Exception("Association with the AP timed out")
187     status = dev[0].get_status()
188     if status['wpa_state'] != 'COMPLETED':
189         raise Exception("Not fully connected")
190     if status['bssid'] != apdev[0]['bssid']:
191         raise Exception("Unexpected BSSID")
192     if status['ssid'] != ssid:
193         raise Exception("Unexpected SSID")
194     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
195         raise Exception("Unexpected encryption configuration")
196     if status['key_mgmt'] != 'WPA2-PSK':
197         raise Exception("Unexpected key_mgmt")
198
199     sta = hapd.get_sta(dev[0].p2p_interface_addr())
200     if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
201         raise Exception("Device name not available in STA command")
202
203 def test_ap_wps_conf_5ghz(dev, apdev):
204     """WPS PBC provisioning with configured AP on 5 GHz band"""
205     try:
206         hapd = None
207         ssid = "test-wps-conf"
208         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
209                    "wpa_passphrase": "12345678", "wpa": "2",
210                    "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
211                    "country_code": "FI", "hw_mode": "a", "channel": "36" }
212         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
213         logger.info("WPS provisioning step")
214         hapd.request("WPS_PBC")
215         dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
216         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
217         ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
218         if ev is None:
219             raise Exception("Association with the AP timed out")
220
221         sta = hapd.get_sta(dev[0].p2p_interface_addr())
222         if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
223             raise Exception("Device name not available in STA command")
224     finally:
225         dev[0].request("DISCONNECT")
226         if hapd:
227             hapd.request("DISABLE")
228         subprocess.call(['sudo', 'iw', 'reg', 'set', '00'])
229         dev[0].flush_scan_cache()
230
231 def test_ap_wps_conf_chan14(dev, apdev):
232     """WPS PBC provisioning with configured AP on channel 14"""
233     try:
234         hapd = None
235         ssid = "test-wps-conf"
236         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
237                    "wpa_passphrase": "12345678", "wpa": "2",
238                    "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
239                    "country_code": "JP", "hw_mode": "b", "channel": "14" }
240         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
241         logger.info("WPS provisioning step")
242         hapd.request("WPS_PBC")
243         dev[0].request("WPS_PBC")
244         ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
245         if ev is None:
246             raise Exception("Association with the AP timed out")
247
248         sta = hapd.get_sta(dev[0].p2p_interface_addr())
249         if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
250             raise Exception("Device name not available in STA command")
251     finally:
252         dev[0].request("DISCONNECT")
253         if hapd:
254             hapd.request("DISABLE")
255         subprocess.call(['sudo', 'iw', 'reg', 'set', '00'])
256         dev[0].flush_scan_cache()
257
258 def test_ap_wps_twice(dev, apdev):
259     """WPS provisioning with twice to change passphrase"""
260     ssid = "test-wps-twice"
261     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
262                "wpa_passphrase": "12345678", "wpa": "2",
263                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
264     hostapd.add_ap(apdev[0]['ifname'], params)
265     hapd = hostapd.Hostapd(apdev[0]['ifname'])
266     logger.info("WPS provisioning step")
267     hapd.request("WPS_PBC")
268     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
269     dev[0].dump_monitor()
270     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
271     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
272     if ev is None:
273         raise Exception("Association with the AP timed out")
274     dev[0].request("DISCONNECT")
275
276     logger.info("Restart AP with different passphrase and re-run WPS")
277     hapd_global = hostapd.HostapdGlobal()
278     hapd_global.remove(apdev[0]['ifname'])
279     params['wpa_passphrase'] = 'another passphrase'
280     hostapd.add_ap(apdev[0]['ifname'], params)
281     hapd = hostapd.Hostapd(apdev[0]['ifname'])
282     logger.info("WPS provisioning step")
283     hapd.request("WPS_PBC")
284     dev[0].dump_monitor()
285     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
286     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
287     if ev is None:
288         raise Exception("Association with the AP timed out")
289     networks = dev[0].list_networks()
290     if len(networks) > 1:
291         raise Exception("Unexpected duplicated network block present")
292
293 def test_ap_wps_incorrect_pin(dev, apdev):
294     """WPS PIN provisioning with incorrect PIN"""
295     ssid = "test-wps-incorrect-pin"
296     hostapd.add_ap(apdev[0]['ifname'],
297                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
298                      "wpa_passphrase": "12345678", "wpa": "2",
299                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
300     hapd = hostapd.Hostapd(apdev[0]['ifname'])
301
302     logger.info("WPS provisioning attempt 1")
303     hapd.request("WPS_PIN any 12345670")
304     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
305     dev[0].dump_monitor()
306     dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
307     ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
308     if ev is None:
309         raise Exception("WPS operation timed out")
310     if "config_error=18" not in ev:
311         raise Exception("Incorrect config_error reported")
312     if "msg=8" not in ev:
313         raise Exception("PIN error detected on incorrect message")
314     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
315     if ev is None:
316         raise Exception("Timeout on disconnection event")
317     dev[0].request("WPS_CANCEL")
318     # if a scan was in progress, wait for it to complete before trying WPS again
319     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
320
321     status = hapd.request("WPS_GET_STATUS")
322     if "Last WPS result: Failed" not in status:
323         raise Exception("WPS failure result not shown correctly")
324
325     logger.info("WPS provisioning attempt 2")
326     hapd.request("WPS_PIN any 12345670")
327     dev[0].dump_monitor()
328     dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
329     ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
330     if ev is None:
331         raise Exception("WPS operation timed out")
332     if "config_error=18" not in ev:
333         raise Exception("Incorrect config_error reported")
334     if "msg=10" not in ev:
335         raise Exception("PIN error detected on incorrect message")
336     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
337     if ev is None:
338         raise Exception("Timeout on disconnection event")
339
340 def test_ap_wps_conf_pin(dev, apdev):
341     """WPS PIN provisioning with configured AP"""
342     ssid = "test-wps-conf-pin"
343     hostapd.add_ap(apdev[0]['ifname'],
344                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
345                      "wpa_passphrase": "12345678", "wpa": "2",
346                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
347     hapd = hostapd.Hostapd(apdev[0]['ifname'])
348     logger.info("WPS provisioning step")
349     pin = dev[0].wps_read_pin()
350     hapd.request("WPS_PIN any " + pin)
351     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
352     dev[0].dump_monitor()
353     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
354     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
355     if ev is None:
356         raise Exception("Association with the AP timed out")
357     status = dev[0].get_status()
358     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
359         raise Exception("Not fully connected")
360     if status['ssid'] != ssid:
361         raise Exception("Unexpected SSID")
362     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
363         raise Exception("Unexpected encryption configuration")
364     if status['key_mgmt'] != 'WPA2-PSK':
365         raise Exception("Unexpected key_mgmt")
366
367     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
368     bss = dev[1].get_bss(apdev[0]['bssid'])
369     if "[WPS-AUTH]" in bss['flags']:
370         raise Exception("WPS-AUTH flag not cleared")
371     logger.info("Try to connect from another station using the same PIN")
372     pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
373     ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
374     if ev is None:
375         raise Exception("Operation timed out")
376     if "WPS-M2D" not in ev:
377         raise Exception("Unexpected WPS operation started")
378     hapd.request("WPS_PIN any " + pin)
379     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
380     if ev is None:
381         raise Exception("Association with the AP timed out")
382
383 def test_ap_wps_conf_pin_v1(dev, apdev):
384     """WPS PIN provisioning with configured WPS v1.0 AP"""
385     ssid = "test-wps-conf-pin-v1"
386     hostapd.add_ap(apdev[0]['ifname'],
387                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
388                      "wpa_passphrase": "12345678", "wpa": "2",
389                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
390     hapd = hostapd.Hostapd(apdev[0]['ifname'])
391     logger.info("WPS provisioning step")
392     pin = dev[0].wps_read_pin()
393     hapd.request("SET wps_version_number 0x10")
394     hapd.request("WPS_PIN any " + pin)
395     found = False
396     for i in range(0, 10):
397         dev[0].scan(freq="2412")
398         if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
399             found = True
400             break
401     if not found:
402         hapd.request("SET wps_version_number 0x20")
403         raise Exception("WPS-PIN flag not seen in scan results")
404     dev[0].dump_monitor()
405     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
406     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
407     hapd.request("SET wps_version_number 0x20")
408     if ev is None:
409         raise Exception("Association with the AP timed out")
410
411 def test_ap_wps_conf_pin_2sta(dev, apdev):
412     """Two stations trying to use WPS PIN at the same time"""
413     ssid = "test-wps-conf-pin2"
414     hostapd.add_ap(apdev[0]['ifname'],
415                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
416                      "wpa_passphrase": "12345678", "wpa": "2",
417                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
418     hapd = hostapd.Hostapd(apdev[0]['ifname'])
419     logger.info("WPS provisioning step")
420     pin = "12345670"
421     pin2 = "55554444"
422     hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
423     hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
424     dev[0].dump_monitor()
425     dev[1].dump_monitor()
426     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
427     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
428     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
429     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
430     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
431     if ev is None:
432         raise Exception("Association with the AP timed out")
433     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
434     if ev is None:
435         raise Exception("Association with the AP timed out")
436
437 def test_ap_wps_conf_pin_timeout(dev, apdev):
438     """WPS PIN provisioning with configured AP timing out PIN"""
439     ssid = "test-wps-conf-pin"
440     hostapd.add_ap(apdev[0]['ifname'],
441                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
442                      "wpa_passphrase": "12345678", "wpa": "2",
443                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
444     hapd = hostapd.Hostapd(apdev[0]['ifname'])
445     addr = dev[0].p2p_interface_addr()
446     pin = dev[0].wps_read_pin()
447     if "FAIL" not in hapd.request("WPS_PIN "):
448         raise Exception("Unexpected success on invalid WPS_PIN")
449     hapd.request("WPS_PIN any " + pin + " 1")
450     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
451     time.sleep(1.1)
452     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
453     ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
454     if ev is None:
455         raise Exception("WPS-PIN-NEEDED event timed out")
456     ev = dev[0].wait_event(["WPS-M2D"])
457     if ev is None:
458         raise Exception("M2D not reported")
459     dev[0].request("WPS_CANCEL")
460
461     hapd.request("WPS_PIN any " + pin + " 20 " + addr)
462     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
463     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
464     if ev is None:
465         raise Exception("Association with the AP timed out")
466
467 def test_ap_wps_reg_connect(dev, apdev):
468     """WPS registrar using AP PIN to connect"""
469     ssid = "test-wps-reg-ap-pin"
470     appin = "12345670"
471     hostapd.add_ap(apdev[0]['ifname'],
472                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
473                      "wpa_passphrase": "12345678", "wpa": "2",
474                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
475                      "ap_pin": appin})
476     logger.info("WPS provisioning step")
477     dev[0].dump_monitor()
478     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
479     dev[0].wps_reg(apdev[0]['bssid'], appin)
480     status = dev[0].get_status()
481     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
482         raise Exception("Not fully connected")
483     if status['ssid'] != ssid:
484         raise Exception("Unexpected SSID")
485     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
486         raise Exception("Unexpected encryption configuration")
487     if status['key_mgmt'] != 'WPA2-PSK':
488         raise Exception("Unexpected key_mgmt")
489
490 def check_wps_reg_failure(dev, ap, appin):
491     dev.request("WPS_REG " + ap['bssid'] + " " + appin)
492     ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
493     if ev is None:
494         raise Exception("WPS operation timed out")
495     if "WPS-SUCCESS" in ev:
496         raise Exception("WPS operation succeeded unexpectedly")
497     if "config_error=15" not in ev:
498         raise Exception("WPS setup locked state was not reported correctly")
499
500 def test_ap_wps_random_ap_pin(dev, apdev):
501     """WPS registrar using random AP PIN"""
502     ssid = "test-wps-reg-random-ap-pin"
503     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
504     hostapd.add_ap(apdev[0]['ifname'],
505                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
506                      "wpa_passphrase": "12345678", "wpa": "2",
507                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
508                      "device_name": "Wireless AP", "manufacturer": "Company",
509                      "model_name": "WAP", "model_number": "123",
510                      "serial_number": "12345", "device_type": "6-0050F204-1",
511                      "os_version": "01020300",
512                      "config_methods": "label push_button",
513                      "uuid": ap_uuid, "upnp_iface": "lo" })
514     hapd = hostapd.Hostapd(apdev[0]['ifname'])
515     appin = hapd.request("WPS_AP_PIN random")
516     if "FAIL" in appin:
517         raise Exception("Could not generate random AP PIN")
518     if appin not in hapd.request("WPS_AP_PIN get"):
519         raise Exception("Could not fetch current AP PIN")
520     logger.info("WPS provisioning step")
521     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
522     dev[0].wps_reg(apdev[0]['bssid'], appin)
523
524     hapd.request("WPS_AP_PIN disable")
525     logger.info("WPS provisioning step with AP PIN disabled")
526     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
527     check_wps_reg_failure(dev[1], apdev[0], appin)
528
529     logger.info("WPS provisioning step with AP PIN reset")
530     appin = "12345670"
531     hapd.request("WPS_AP_PIN set " + appin)
532     dev[1].wps_reg(apdev[0]['bssid'], appin)
533     dev[0].request("REMOVE_NETWORK all")
534     dev[1].request("REMOVE_NETWORK all")
535     dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
536     dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
537
538     logger.info("WPS provisioning step after AP PIN timeout")
539     hapd.request("WPS_AP_PIN disable")
540     appin = hapd.request("WPS_AP_PIN random 1")
541     time.sleep(1.1)
542     if "FAIL" not in hapd.request("WPS_AP_PIN get"):
543         raise Exception("AP PIN unexpectedly still enabled")
544     check_wps_reg_failure(dev[0], apdev[0], appin)
545
546     logger.info("WPS provisioning step after AP PIN timeout(2)")
547     hapd.request("WPS_AP_PIN disable")
548     appin = "12345670"
549     hapd.request("WPS_AP_PIN set " + appin + " 1")
550     time.sleep(1.1)
551     if "FAIL" not in hapd.request("WPS_AP_PIN get"):
552         raise Exception("AP PIN unexpectedly still enabled")
553     check_wps_reg_failure(dev[1], apdev[0], appin)
554
555 def test_ap_wps_reg_config(dev, apdev):
556     """WPS registrar configuring an AP using AP PIN"""
557     ssid = "test-wps-init-ap-pin"
558     appin = "12345670"
559     hostapd.add_ap(apdev[0]['ifname'],
560                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
561                      "ap_pin": appin})
562     logger.info("WPS configuration step")
563     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
564     dev[0].dump_monitor()
565     new_ssid = "wps-new-ssid"
566     new_passphrase = "1234567890"
567     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
568                    new_passphrase)
569     status = dev[0].get_status()
570     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
571         raise Exception("Not fully connected")
572     if status['ssid'] != new_ssid:
573         raise Exception("Unexpected SSID")
574     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
575         raise Exception("Unexpected encryption configuration")
576     if status['key_mgmt'] != 'WPA2-PSK':
577         raise Exception("Unexpected key_mgmt")
578
579     logger.info("Re-configure back to open")
580     dev[0].request("REMOVE_NETWORK all")
581     dev[0].flush_scan_cache()
582     dev[0].dump_monitor()
583     dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
584     status = dev[0].get_status()
585     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
586         raise Exception("Not fully connected")
587     if status['ssid'] != "wps-open":
588         raise Exception("Unexpected SSID")
589     if status['key_mgmt'] != 'NONE':
590         raise Exception("Unexpected key_mgmt")
591
592 def test_ap_wps_reg_config_ext_processing(dev, apdev):
593     """WPS registrar configuring an AP with external config processing"""
594     ssid = "test-wps-init-ap-pin"
595     appin = "12345670"
596     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
597                "wps_cred_processing": "1", "ap_pin": appin}
598     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
599     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
600     new_ssid = "wps-new-ssid"
601     new_passphrase = "1234567890"
602     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
603                    new_passphrase, no_wait=True)
604     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
605     if ev is None:
606         raise Exception("WPS registrar operation timed out")
607     ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
608     if ev is None:
609         raise Exception("WPS configuration timed out")
610     if "1026" not in ev:
611         raise Exception("AP Settings missing from event")
612     hapd.request("SET wps_cred_processing 0")
613     if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
614         raise Exception("WPS_CONFIG command failed")
615     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
616     if ev is None:
617         raise Exception("Association with the AP timed out")
618
619 def test_ap_wps_reg_config_tkip(dev, apdev):
620     """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
621     ssid = "test-wps-init-ap"
622     appin = "12345670"
623     hostapd.add_ap(apdev[0]['ifname'],
624                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
625                      "ap_pin": appin})
626     logger.info("WPS configuration step")
627     dev[0].request("SET wps_version_number 0x10")
628     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
629     dev[0].dump_monitor()
630     new_ssid = "wps-new-ssid-with-tkip"
631     new_passphrase = "1234567890"
632     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
633                    new_passphrase)
634     logger.info("Re-connect to verify WPA2 mixed mode")
635     dev[0].request("DISCONNECT")
636     id = 0
637     dev[0].set_network(id, "pairwise", "CCMP")
638     dev[0].set_network(id, "proto", "RSN")
639     dev[0].connect_network(id)
640     status = dev[0].get_status()
641     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
642         raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
643     if status['ssid'] != new_ssid:
644         raise Exception("Unexpected SSID")
645     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
646         raise Exception("Unexpected encryption configuration")
647     if status['key_mgmt'] != 'WPA2-PSK':
648         raise Exception("Unexpected key_mgmt")
649
650 def test_ap_wps_setup_locked(dev, apdev):
651     """WPS registrar locking up AP setup on AP PIN failures"""
652     ssid = "test-wps-incorrect-ap-pin"
653     appin = "12345670"
654     hostapd.add_ap(apdev[0]['ifname'],
655                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
656                      "wpa_passphrase": "12345678", "wpa": "2",
657                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
658                      "ap_pin": appin})
659     new_ssid = "wps-new-ssid-test"
660     new_passphrase = "1234567890"
661
662     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
663     ap_setup_locked=False
664     for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
665         dev[0].dump_monitor()
666         logger.info("Try incorrect AP PIN - attempt " + pin)
667         dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
668                        "CCMP", new_passphrase, no_wait=True)
669         ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
670         if ev is None:
671             raise Exception("Timeout on receiving WPS operation failure event")
672         if "CTRL-EVENT-CONNECTED" in ev:
673             raise Exception("Unexpected connection")
674         if "config_error=15" in ev:
675             logger.info("AP Setup Locked")
676             ap_setup_locked=True
677         elif "config_error=18" not in ev:
678             raise Exception("config_error=18 not reported")
679         ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
680         if ev is None:
681             raise Exception("Timeout on disconnection event")
682         time.sleep(0.1)
683     if not ap_setup_locked:
684         raise Exception("AP setup was not locked")
685
686     hapd = hostapd.Hostapd(apdev[0]['ifname'])
687     status = hapd.request("WPS_GET_STATUS")
688     if "Last WPS result: Failed" not in status:
689         raise Exception("WPS failure result not shown correctly")
690     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
691         raise Exception("Peer address not shown correctly")
692
693     time.sleep(0.5)
694     dev[0].dump_monitor()
695     logger.info("WPS provisioning step")
696     pin = dev[0].wps_read_pin()
697     hapd = hostapd.Hostapd(apdev[0]['ifname'])
698     hapd.request("WPS_PIN any " + pin)
699     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
700     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
701     if ev is None:
702         raise Exception("WPS success was not reported")
703     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
704     if ev is None:
705         raise Exception("Association with the AP timed out")
706
707     appin = hapd.request("WPS_AP_PIN random")
708     if "FAIL" in appin:
709         raise Exception("Could not generate random AP PIN")
710     ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
711     if ev is None:
712         raise Exception("Failed to unlock AP PIN")
713
714 def test_ap_wps_setup_locked_timeout(dev, apdev):
715     """WPS re-enabling AP PIN after timeout"""
716     ssid = "test-wps-incorrect-ap-pin"
717     appin = "12345670"
718     hostapd.add_ap(apdev[0]['ifname'],
719                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
720                      "wpa_passphrase": "12345678", "wpa": "2",
721                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
722                      "ap_pin": appin})
723     new_ssid = "wps-new-ssid-test"
724     new_passphrase = "1234567890"
725
726     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
727     ap_setup_locked=False
728     for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
729         dev[0].dump_monitor()
730         logger.info("Try incorrect AP PIN - attempt " + pin)
731         dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
732                        "CCMP", new_passphrase, no_wait=True)
733         ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
734         if ev is None:
735             raise Exception("Timeout on receiving WPS operation failure event")
736         if "CTRL-EVENT-CONNECTED" in ev:
737             raise Exception("Unexpected connection")
738         if "config_error=15" in ev:
739             logger.info("AP Setup Locked")
740             ap_setup_locked=True
741             break
742         elif "config_error=18" not in ev:
743             raise Exception("config_error=18 not reported")
744         ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
745         if ev is None:
746             raise Exception("Timeout on disconnection event")
747         time.sleep(0.1)
748     if not ap_setup_locked:
749         raise Exception("AP setup was not locked")
750     hapd = hostapd.Hostapd(apdev[0]['ifname'])
751     ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
752     if ev is None:
753         raise Exception("AP PIN did not get unlocked on 60 second timeout")
754
755 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
756     """WPS PBC session overlap with two active APs"""
757     hostapd.add_ap(apdev[0]['ifname'],
758                    { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
759                      "wpa_passphrase": "12345678", "wpa": "2",
760                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
761                      "wps_independent": "1"})
762     hostapd.add_ap(apdev[1]['ifname'],
763                    { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
764                      "wpa_passphrase": "123456789", "wpa": "2",
765                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
766                      "wps_independent": "1"})
767     hapd = hostapd.Hostapd(apdev[0]['ifname'])
768     hapd.request("WPS_PBC")
769     hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
770     hapd2.request("WPS_PBC")
771     logger.info("WPS provisioning step")
772     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
773     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
774     dev[0].request("WPS_PBC")
775     ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
776     if ev is None:
777         raise Exception("PBC session overlap not detected")
778
779 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
780     """WPS PBC session overlap with two active STAs"""
781     ssid = "test-wps-pbc-overlap"
782     hostapd.add_ap(apdev[0]['ifname'],
783                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
784                      "wpa_passphrase": "12345678", "wpa": "2",
785                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
786     hapd = hostapd.Hostapd(apdev[0]['ifname'])
787     logger.info("WPS provisioning step")
788     hapd.request("WPS_PBC")
789     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
790     dev[0].dump_monitor()
791     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
792     dev[1].dump_monitor()
793     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
794     dev[1].request("WPS_PBC " + apdev[0]['bssid'])
795     ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
796     if ev is None:
797         raise Exception("PBC session overlap not detected (dev0)")
798     if "config_error=12" not in ev:
799         raise Exception("PBC session overlap not correctly reported (dev0)")
800     ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
801     if ev is None:
802         raise Exception("PBC session overlap not detected (dev1)")
803     if "config_error=12" not in ev:
804         raise Exception("PBC session overlap not correctly reported (dev1)")
805     hapd.request("WPS_CANCEL")
806     ret = hapd.request("WPS_PBC")
807     if "FAIL" not in ret:
808         raise Exception("PBC mode allowed to be started while PBC overlap still active")
809
810 def test_ap_wps_cancel(dev, apdev):
811     """WPS AP cancelling enabled config method"""
812     ssid = "test-wps-ap-cancel"
813     hostapd.add_ap(apdev[0]['ifname'],
814                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
815                      "wpa_passphrase": "12345678", "wpa": "2",
816                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
817     bssid = apdev[0]['bssid']
818     hapd = hostapd.Hostapd(apdev[0]['ifname'])
819
820     logger.info("Verify PBC enable/cancel")
821     hapd.request("WPS_PBC")
822     dev[0].scan(freq="2412")
823     dev[0].scan(freq="2412")
824     bss = dev[0].get_bss(apdev[0]['bssid'])
825     if "[WPS-PBC]" not in bss['flags']:
826         raise Exception("WPS-PBC flag missing")
827     if "FAIL" in hapd.request("WPS_CANCEL"):
828         raise Exception("WPS_CANCEL failed")
829     dev[0].scan(freq="2412")
830     dev[0].scan(freq="2412")
831     bss = dev[0].get_bss(apdev[0]['bssid'])
832     if "[WPS-PBC]" in bss['flags']:
833         raise Exception("WPS-PBC flag not cleared")
834
835     logger.info("Verify PIN enable/cancel")
836     hapd.request("WPS_PIN any 12345670")
837     dev[0].scan(freq="2412")
838     dev[0].scan(freq="2412")
839     bss = dev[0].get_bss(apdev[0]['bssid'])
840     if "[WPS-AUTH]" not in bss['flags']:
841         raise Exception("WPS-AUTH flag missing")
842     if "FAIL" in hapd.request("WPS_CANCEL"):
843         raise Exception("WPS_CANCEL failed")
844     dev[0].scan(freq="2412")
845     dev[0].scan(freq="2412")
846     bss = dev[0].get_bss(apdev[0]['bssid'])
847     if "[WPS-AUTH]" in bss['flags']:
848         raise Exception("WPS-AUTH flag not cleared")
849
850 def test_ap_wps_er_add_enrollee(dev, apdev):
851     """WPS ER configuring AP and adding a new enrollee using PIN"""
852     try:
853         _test_ap_wps_er_add_enrollee(dev, apdev)
854     finally:
855         dev[0].request("WPS_ER_STOP")
856
857 def _test_ap_wps_er_add_enrollee(dev, apdev):
858     ssid = "wps-er-add-enrollee"
859     ap_pin = "12345670"
860     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
861     hostapd.add_ap(apdev[0]['ifname'],
862                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
863                      "device_name": "Wireless AP", "manufacturer": "Company",
864                      "model_name": "WAP", "model_number": "123",
865                      "serial_number": "12345", "device_type": "6-0050F204-1",
866                      "os_version": "01020300",
867                      "config_methods": "label push_button",
868                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
869     logger.info("WPS configuration step")
870     new_passphrase = "1234567890"
871     dev[0].dump_monitor()
872     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
873     dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
874                    new_passphrase)
875     status = dev[0].get_status()
876     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
877         raise Exception("Not fully connected")
878     if status['ssid'] != ssid:
879         raise Exception("Unexpected SSID")
880     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
881         raise Exception("Unexpected encryption configuration")
882     if status['key_mgmt'] != 'WPA2-PSK':
883         raise Exception("Unexpected key_mgmt")
884
885     logger.info("Start ER")
886     dev[0].request("WPS_ER_START ifname=lo")
887     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
888     if ev is None:
889         raise Exception("AP discovery timed out")
890     if ap_uuid not in ev:
891         raise Exception("Expected AP UUID not found")
892
893     logger.info("Learn AP configuration through UPnP")
894     dev[0].dump_monitor()
895     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
896     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
897     if ev is None:
898         raise Exception("AP learn timed out")
899     if ap_uuid not in ev:
900         raise Exception("Expected AP UUID not in settings")
901     if "ssid=" + ssid not in ev:
902         raise Exception("Expected SSID not in settings")
903     if "key=" + new_passphrase not in ev:
904         raise Exception("Expected passphrase not in settings")
905     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
906     if ev is None:
907         raise Exception("WPS-FAIL after AP learn timed out")
908     time.sleep(0.1)
909
910     logger.info("Add Enrollee using ER")
911     pin = dev[1].wps_read_pin()
912     dev[0].dump_monitor()
913     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
914     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
915     dev[1].dump_monitor()
916     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
917     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
918     if ev is None:
919         raise Exception("Enrollee did not report success")
920     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
921     if ev is None:
922         raise Exception("Association with the AP timed out")
923     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
924     if ev is None:
925         raise Exception("WPS ER did not report success")
926     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
927
928     logger.info("Add a specific Enrollee using ER")
929     pin = dev[2].wps_read_pin()
930     addr2 = dev[2].p2p_interface_addr()
931     dev[0].dump_monitor()
932     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
933     dev[2].dump_monitor()
934     dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
935     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
936     if ev is None:
937         raise Exception("Enrollee not seen")
938     if addr2 not in ev:
939         raise Exception("Unexpected Enrollee MAC address")
940     dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
941     ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
942     if ev is None:
943         raise Exception("Association with the AP timed out")
944     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
945     if ev is None:
946         raise Exception("WPS ER did not report success")
947
948     logger.info("Verify registrar selection behavior")
949     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
950     dev[1].request("DISCONNECT")
951     dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
952     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
953     dev[1].scan(freq="2412")
954     bss = dev[1].get_bss(apdev[0]['bssid'])
955     if "[WPS-AUTH]" not in bss['flags']:
956         # It is possible for scan to miss an update especially when running
957         # tests under load with multiple VMs, so allow another attempt.
958         dev[1].scan(freq="2412")
959         bss = dev[1].get_bss(apdev[0]['bssid'])
960         if "[WPS-AUTH]" not in bss['flags']:
961             raise Exception("WPS-AUTH flag missing")
962
963     logger.info("Stop ER")
964     dev[0].dump_monitor()
965     dev[0].request("WPS_ER_STOP")
966     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
967     if ev is None:
968         raise Exception("WPS ER unsubscription timed out")
969     # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
970     # a bit before verifying that the scan results have changed.
971     time.sleep(0.2)
972
973     for i in range(0, 10):
974         dev[1].request("BSS_FLUSH 0")
975         dev[1].scan(freq="2412", only_new=True)
976         bss = dev[1].get_bss(apdev[0]['bssid'])
977         if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
978             break
979         logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
980         time.sleep(0.1)
981     if "[WPS-AUTH]" in bss['flags']:
982         raise Exception("WPS-AUTH flag not removed")
983
984 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
985     """WPS ER connected to AP and adding a new enrollee using PBC"""
986     try:
987         _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
988     finally:
989         dev[0].request("WPS_ER_STOP")
990
991 def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
992     ssid = "wps-er-add-enrollee-pbc"
993     ap_pin = "12345670"
994     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
995     hostapd.add_ap(apdev[0]['ifname'],
996                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
997                      "wpa_passphrase": "12345678", "wpa": "2",
998                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
999                      "device_name": "Wireless AP", "manufacturer": "Company",
1000                      "model_name": "WAP", "model_number": "123",
1001                      "serial_number": "12345", "device_type": "6-0050F204-1",
1002                      "os_version": "01020300",
1003                      "config_methods": "label push_button",
1004                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1005     logger.info("Learn AP configuration")
1006     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1007     dev[0].dump_monitor()
1008     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1009     status = dev[0].get_status()
1010     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1011         raise Exception("Not fully connected")
1012
1013     logger.info("Start ER")
1014     dev[0].request("WPS_ER_START ifname=lo")
1015     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1016     if ev is None:
1017         raise Exception("AP discovery timed out")
1018     if ap_uuid not in ev:
1019         raise Exception("Expected AP UUID not found")
1020
1021     enrollee = dev[1].p2p_interface_addr()
1022
1023     if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1024         raise Exception("Unknown UUID not reported")
1025
1026     logger.info("Add Enrollee using ER and PBC")
1027     dev[0].dump_monitor()
1028     dev[1].dump_monitor()
1029     dev[1].request("WPS_PBC")
1030
1031     for i in range(0, 2):
1032         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1033         if ev is None:
1034             raise Exception("Enrollee discovery timed out")
1035         if enrollee in ev:
1036             break
1037         if i == 1:
1038             raise Exception("Expected Enrollee not found")
1039     if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1040         raise Exception("Unknown UUID not reported")
1041     logger.info("Use learned network configuration on ER")
1042     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1043     if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1044         raise Exception("WPS_ER_PBC failed")
1045
1046     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1047     if ev is None:
1048         raise Exception("Enrollee did not report success")
1049     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
1050     if ev is None:
1051         raise Exception("Association with the AP timed out")
1052     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1053     if ev is None:
1054         raise Exception("WPS ER did not report success")
1055     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1056
1057 def test_ap_wps_er_pbc_overlap(dev, apdev):
1058     """WPS ER connected to AP and PBC session overlap"""
1059     try:
1060         _test_ap_wps_er_pbc_overlap(dev, apdev)
1061     finally:
1062         dev[0].request("WPS_ER_STOP")
1063
1064 def _test_ap_wps_er_pbc_overlap(dev, apdev):
1065     ssid = "wps-er-add-enrollee-pbc"
1066     ap_pin = "12345670"
1067     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1068     hostapd.add_ap(apdev[0]['ifname'],
1069                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1070                      "wpa_passphrase": "12345678", "wpa": "2",
1071                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1072                      "device_name": "Wireless AP", "manufacturer": "Company",
1073                      "model_name": "WAP", "model_number": "123",
1074                      "serial_number": "12345", "device_type": "6-0050F204-1",
1075                      "os_version": "01020300",
1076                      "config_methods": "label push_button",
1077                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1078     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1079     dev[0].dump_monitor()
1080     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1081
1082     dev[0].dump_monitor()
1083     dev[0].request("WPS_ER_START ifname=lo")
1084
1085     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1086     if ev is None:
1087         raise Exception("AP discovery timed out")
1088     if ap_uuid not in ev:
1089         raise Exception("Expected AP UUID not found")
1090
1091     # verify BSSID selection of the AP instead of UUID
1092     if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1093         raise Exception("Could not select AP based on BSSID")
1094
1095     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1096     dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1097     dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1098     dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1099     ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1100     if ev is None:
1101         raise Exception("PBC scan failed")
1102     ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1103     if ev is None:
1104         raise Exception("PBC scan failed")
1105     for i in range(0, 2):
1106         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1107         if ev is None:
1108             raise Exception("Enrollee discovery timed out")
1109     if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1110         raise Exception("PBC overlap not reported")
1111     dev[1].request("WPS_CANCEL")
1112     dev[2].request("WPS_CANCEL")
1113     if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1114         raise Exception("Invalid WPS_ER_PBC accepted")
1115
1116 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1117     """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
1118     try:
1119         _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1120     finally:
1121         dev[0].request("WPS_ER_STOP")
1122
1123 def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1124     ssid = "wps-er-add-enrollee-pbc"
1125     ap_pin = "12345670"
1126     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1127     hostapd.add_ap(apdev[0]['ifname'],
1128                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1129                      "wpa_passphrase": "12345678", "wpa": "2",
1130                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1131                      "device_name": "Wireless AP", "manufacturer": "Company",
1132                      "model_name": "WAP", "model_number": "123",
1133                      "serial_number": "12345", "device_type": "6-0050F204-1",
1134                      "os_version": "01020300",
1135                      "config_methods": "label push_button",
1136                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1137     logger.info("Learn AP configuration")
1138     dev[0].request("SET wps_version_number 0x10")
1139     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1140     dev[0].dump_monitor()
1141     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1142     status = dev[0].get_status()
1143     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1144         raise Exception("Not fully connected")
1145
1146     logger.info("Start ER")
1147     dev[0].request("WPS_ER_START ifname=lo")
1148     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1149     if ev is None:
1150         raise Exception("AP discovery timed out")
1151     if ap_uuid not in ev:
1152         raise Exception("Expected AP UUID not found")
1153
1154     logger.info("Use learned network configuration on ER")
1155     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1156
1157     logger.info("Add Enrollee using ER and PIN")
1158     enrollee = dev[1].p2p_interface_addr()
1159     pin = dev[1].wps_read_pin()
1160     dev[0].dump_monitor()
1161     dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1162     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1163     dev[1].dump_monitor()
1164     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1165     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1166     if ev is None:
1167         raise Exception("Association with the AP timed out")
1168     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1169     if ev is None:
1170         raise Exception("WPS ER did not report success")
1171
1172 def test_ap_wps_er_config_ap(dev, apdev):
1173     """WPS ER configuring AP over UPnP"""
1174     try:
1175         _test_ap_wps_er_config_ap(dev, apdev)
1176     finally:
1177         dev[0].request("WPS_ER_STOP")
1178
1179 def _test_ap_wps_er_config_ap(dev, apdev):
1180     ssid = "wps-er-ap-config"
1181     ap_pin = "12345670"
1182     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1183     hostapd.add_ap(apdev[0]['ifname'],
1184                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1185                      "wpa_passphrase": "12345678", "wpa": "2",
1186                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1187                      "device_name": "Wireless AP", "manufacturer": "Company",
1188                      "model_name": "WAP", "model_number": "123",
1189                      "serial_number": "12345", "device_type": "6-0050F204-1",
1190                      "os_version": "01020300",
1191                      "config_methods": "label push_button",
1192                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1193
1194     logger.info("Connect ER to the AP")
1195     dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1196
1197     logger.info("WPS configuration step")
1198     dev[0].request("WPS_ER_START ifname=lo")
1199     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1200     if ev is None:
1201         raise Exception("AP discovery timed out")
1202     if ap_uuid not in ev:
1203         raise Exception("Expected AP UUID not found")
1204     new_passphrase = "1234567890"
1205     dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1206                    ssid.encode("hex") + " WPA2PSK CCMP " +
1207                    new_passphrase.encode("hex"))
1208     ev = dev[0].wait_event(["WPS-SUCCESS"])
1209     if ev is None:
1210         raise Exception("WPS ER configuration operation timed out")
1211     dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
1212     dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1213
1214     logger.info("WPS ER restart")
1215     dev[0].request("WPS_ER_START")
1216     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1217     if ev is None:
1218         raise Exception("AP discovery timed out on ER restart")
1219     if ap_uuid not in ev:
1220         raise Exception("Expected AP UUID not found on ER restart")
1221     if "OK" not in dev[0].request("WPS_ER_STOP"):
1222         raise Exception("WPS_ER_STOP failed")
1223     if "OK" not in dev[0].request("WPS_ER_STOP"):
1224         raise Exception("WPS_ER_STOP failed")
1225
1226 def test_ap_wps_fragmentation(dev, apdev):
1227     """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1228     ssid = "test-wps-fragmentation"
1229     appin = "12345670"
1230     hostapd.add_ap(apdev[0]['ifname'],
1231                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1232                      "wpa_passphrase": "12345678", "wpa": "3",
1233                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1234                      "wpa_pairwise": "TKIP", "ap_pin": appin,
1235                      "fragment_size": "50" })
1236     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1237     logger.info("WPS provisioning step (PBC)")
1238     hapd.request("WPS_PBC")
1239     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1240     dev[0].dump_monitor()
1241     dev[0].request("SET wps_fragment_size 50")
1242     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1243     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1244     if ev is None:
1245         raise Exception("Association with the AP timed out")
1246     status = dev[0].get_status()
1247     if status['wpa_state'] != 'COMPLETED':
1248         raise Exception("Not fully connected")
1249     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1250         raise Exception("Unexpected encryption configuration")
1251     if status['key_mgmt'] != 'WPA2-PSK':
1252         raise Exception("Unexpected key_mgmt")
1253
1254     logger.info("WPS provisioning step (PIN)")
1255     pin = dev[1].wps_read_pin()
1256     hapd.request("WPS_PIN any " + pin)
1257     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1258     dev[1].request("SET wps_fragment_size 50")
1259     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1260     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1261     if ev is None:
1262         raise Exception("Association with the AP timed out")
1263     status = dev[1].get_status()
1264     if status['wpa_state'] != 'COMPLETED':
1265         raise Exception("Not fully connected")
1266     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1267         raise Exception("Unexpected encryption configuration")
1268     if status['key_mgmt'] != 'WPA2-PSK':
1269         raise Exception("Unexpected key_mgmt")
1270
1271     logger.info("WPS connection as registrar")
1272     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1273     dev[2].request("SET wps_fragment_size 50")
1274     dev[2].wps_reg(apdev[0]['bssid'], appin)
1275     status = dev[2].get_status()
1276     if status['wpa_state'] != 'COMPLETED':
1277         raise Exception("Not fully connected")
1278     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1279         raise Exception("Unexpected encryption configuration")
1280     if status['key_mgmt'] != 'WPA2-PSK':
1281         raise Exception("Unexpected key_mgmt")
1282
1283 def test_ap_wps_new_version_sta(dev, apdev):
1284     """WPS compatibility with new version number on the station"""
1285     ssid = "test-wps-ver"
1286     hostapd.add_ap(apdev[0]['ifname'],
1287                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1288                      "wpa_passphrase": "12345678", "wpa": "2",
1289                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1290     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1291     logger.info("WPS provisioning step")
1292     hapd.request("WPS_PBC")
1293     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1294     dev[0].dump_monitor()
1295     dev[0].request("SET wps_version_number 0x43")
1296     dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
1297     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1298     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1299     if ev is None:
1300         raise Exception("Association with the AP timed out")
1301
1302 def test_ap_wps_new_version_ap(dev, apdev):
1303     """WPS compatibility with new version number on the AP"""
1304     ssid = "test-wps-ver"
1305     hostapd.add_ap(apdev[0]['ifname'],
1306                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1307                      "wpa_passphrase": "12345678", "wpa": "2",
1308                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1309     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1310     logger.info("WPS provisioning step")
1311     if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1312         raise Exception("Failed to enable test functionality")
1313     hapd.request("WPS_PBC")
1314     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1315     dev[0].dump_monitor()
1316     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1317     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1318     hapd.request("SET wps_version_number 0x20")
1319     if ev is None:
1320         raise Exception("Association with the AP timed out")
1321
1322 def test_ap_wps_check_pin(dev, apdev):
1323     """Verify PIN checking through control interface"""
1324     hostapd.add_ap(apdev[0]['ifname'],
1325                    { "ssid": "wps", "eap_server": "1", "wps_state": "2",
1326                      "wpa_passphrase": "12345678", "wpa": "2",
1327                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1328     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1329     for t in [ ("12345670", "12345670"),
1330                ("12345678", "FAIL-CHECKSUM"),
1331                ("12345", "FAIL"),
1332                ("123456789", "FAIL"),
1333                ("1234-5670", "12345670"),
1334                ("1234 5670", "12345670"),
1335                ("1-2.3:4 5670", "12345670") ]:
1336         res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1337         res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1338         if res != res2:
1339             raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
1340         if res != t[1]:
1341             raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
1342
1343     if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
1344         raise Exception("Unexpected WPS_CHECK_PIN success")
1345     if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
1346         raise Exception("Unexpected WPS_CHECK_PIN success")
1347
1348     for i in range(0, 10):
1349         pin = dev[0].request("WPS_PIN get")
1350         rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
1351         if pin != rpin:
1352             raise Exception("Random PIN validation failed for " + pin)
1353
1354 def test_ap_wps_wep_config(dev, apdev):
1355     """WPS 2.0 AP rejecting WEP configuration"""
1356     ssid = "test-wps-config"
1357     appin = "12345670"
1358     hostapd.add_ap(apdev[0]['ifname'],
1359                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1360                      "ap_pin": appin})
1361     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1362     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1363     dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
1364                    "hello", no_wait=True)
1365     ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
1366     if ev is None:
1367         raise Exception("WPS-FAIL timed out")
1368     if "reason=2" not in ev:
1369         raise Exception("Unexpected reason code in WPS-FAIL")
1370     status = hapd.request("WPS_GET_STATUS")
1371     if "Last WPS result: Failed" not in status:
1372         raise Exception("WPS failure result not shown correctly")
1373     if "Failure Reason: WEP Prohibited" not in status:
1374         raise Exception("Failure reason not reported correctly")
1375     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
1376         raise Exception("Peer address not shown correctly")
1377
1378 def test_ap_wps_wep_enroll(dev, apdev):
1379     """WPS 2.0 STA rejecting WEP configuration"""
1380     ssid = "test-wps-wep"
1381     hostapd.add_ap(apdev[0]['ifname'],
1382                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1383                      "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
1384     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1385     hapd.request("WPS_PBC")
1386     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1387     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1388     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1389     if ev is None:
1390         raise Exception("WPS-FAIL event timed out")
1391     if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
1392         raise Exception("Unexpected WPS-FAIL event: " + ev)
1393
1394 def test_ap_wps_ie_fragmentation(dev, apdev):
1395     """WPS AP using fragmented WPS IE"""
1396     ssid = "test-wps-ie-fragmentation"
1397     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1398                "wpa_passphrase": "12345678", "wpa": "2",
1399                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1400                "device_name": "1234567890abcdef1234567890abcdef",
1401                "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1402                "model_name": "1234567890abcdef1234567890abcdef",
1403                "model_number": "1234567890abcdef1234567890abcdef",
1404                "serial_number": "1234567890abcdef1234567890abcdef" }
1405     hostapd.add_ap(apdev[0]['ifname'], params)
1406     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1407     hapd.request("WPS_PBC")
1408     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1409     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1410     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1411     if ev is None:
1412         raise Exception("Association with the AP timed out")
1413     bss = dev[0].get_bss(apdev[0]['bssid'])
1414     if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1415         logger.info("Device Name not received correctly")
1416         logger.info(bss)
1417         # This can fail if Probe Response frame is missed and Beacon frame was
1418         # used to fill in the BSS entry. This can happen, e.g., during heavy
1419         # load every now and then and is not really an error, so try to
1420         # workaround by runnign another scan.
1421         dev[0].scan(freq="2412", only_new=True)
1422         bss = dev[0].get_bss(apdev[0]['bssid'])
1423         if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1424             logger.info(bss)
1425             raise Exception("Device Name not received correctly")
1426     if len(re.findall("dd..0050f204", bss['ie'])) != 2:
1427         raise Exception("Unexpected number of WPS IEs")
1428
1429 def get_psk(pskfile):
1430     psks = {}
1431     with open(pskfile, "r") as f:
1432         lines = f.read().splitlines()
1433         for l in lines:
1434             if l == "# WPA PSKs":
1435                 continue
1436             (addr,psk) = l.split(' ')
1437             psks[addr] = psk
1438     return psks
1439
1440 def test_ap_wps_per_station_psk(dev, apdev):
1441     """WPS PBC provisioning with per-station PSK"""
1442     addr0 = dev[0].p2p_dev_addr()
1443     addr1 = dev[1].p2p_dev_addr()
1444     addr2 = dev[2].p2p_dev_addr()
1445     ssid = "wps"
1446     appin = "12345670"
1447     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1448     try:
1449         os.remove(pskfile)
1450     except:
1451         pass
1452
1453     try:
1454         with open(pskfile, "w") as f:
1455             f.write("# WPA PSKs\n")
1456
1457         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1458                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1459                    "rsn_pairwise": "CCMP", "ap_pin": appin,
1460                    "wpa_psk_file": pskfile }
1461         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1462
1463         logger.info("First enrollee")
1464         hapd.request("WPS_PBC")
1465         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1466         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1467         ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1468         if ev is None:
1469             raise Exception("Association with the AP timed out (1)")
1470
1471         logger.info("Second enrollee")
1472         hapd.request("WPS_PBC")
1473         dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1474         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1475         ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1476         if ev is None:
1477             raise Exception("Association with the AP timed out (2)")
1478
1479         logger.info("External registrar")
1480         dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1481         dev[2].wps_reg(apdev[0]['bssid'], appin)
1482
1483         logger.info("Verifying PSK results")
1484         psks = get_psk(pskfile)
1485         if addr0 not in psks:
1486             raise Exception("No PSK recorded for sta0")
1487         if addr1 not in psks:
1488             raise Exception("No PSK recorded for sta1")
1489         if addr2 not in psks:
1490             raise Exception("No PSK recorded for sta2")
1491         if psks[addr0] == psks[addr1]:
1492             raise Exception("Same PSK recorded for sta0 and sta1")
1493         if psks[addr0] == psks[addr2]:
1494             raise Exception("Same PSK recorded for sta0 and sta2")
1495         if psks[addr1] == psks[addr2]:
1496             raise Exception("Same PSK recorded for sta1 and sta2")
1497
1498         dev[0].request("REMOVE_NETWORK all")
1499         logger.info("Second external registrar")
1500         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1501         dev[0].wps_reg(apdev[0]['bssid'], appin)
1502         psks2 = get_psk(pskfile)
1503         if addr0 not in psks2:
1504             raise Exception("No PSK recorded for sta0(reg)")
1505         if psks[addr0] == psks2[addr0]:
1506             raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
1507     finally:
1508         os.remove(pskfile)
1509
1510 def test_ap_wps_per_station_psk_failure(dev, apdev):
1511     """WPS PBC provisioning with per-station PSK (file not writable)"""
1512     addr0 = dev[0].p2p_dev_addr()
1513     addr1 = dev[1].p2p_dev_addr()
1514     addr2 = dev[2].p2p_dev_addr()
1515     ssid = "wps"
1516     appin = "12345670"
1517     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1518     try:
1519         os.remove(pskfile)
1520     except:
1521         pass
1522
1523     try:
1524         with open(pskfile, "w") as f:
1525             f.write("# WPA PSKs\n")
1526
1527         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1528                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1529                    "rsn_pairwise": "CCMP", "ap_pin": appin,
1530                    "wpa_psk_file": pskfile }
1531         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1532         if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
1533             raise Exception("Failed to set wpa_psk_file")
1534
1535         logger.info("First enrollee")
1536         hapd.request("WPS_PBC")
1537         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1538         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1539         ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1540         if ev is None:
1541             raise Exception("Association with the AP timed out (1)")
1542
1543         logger.info("Second enrollee")
1544         hapd.request("WPS_PBC")
1545         dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1546         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1547         ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1548         if ev is None:
1549             raise Exception("Association with the AP timed out (2)")
1550
1551         logger.info("External registrar")
1552         dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1553         dev[2].wps_reg(apdev[0]['bssid'], appin)
1554
1555         logger.info("Verifying PSK results")
1556         psks = get_psk(pskfile)
1557         if len(psks) > 0:
1558             raise Exception("PSK recorded unexpectedly")
1559     finally:
1560         os.remove(pskfile)
1561
1562 def test_ap_wps_pin_request_file(dev, apdev):
1563     """WPS PIN provisioning with configured AP"""
1564     ssid = "wps"
1565     pinfile = "/tmp/ap_wps_pin_request_file.log"
1566     if os.path.exists(pinfile):
1567         subprocess.call(['sudo', 'rm', pinfile])
1568     hostapd.add_ap(apdev[0]['ifname'],
1569                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1570                      "wps_pin_requests": pinfile,
1571                      "wpa_passphrase": "12345678", "wpa": "2",
1572                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1573     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1574     uuid = dev[0].get_status_field("uuid")
1575     pin = dev[0].wps_read_pin()
1576     try:
1577         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1578         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1579         ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
1580         if ev is None:
1581             raise Exception("PIN needed event not shown")
1582         if uuid not in ev:
1583             raise Exception("UUID mismatch")
1584         dev[0].request("WPS_CANCEL")
1585         success = False
1586         with open(pinfile, "r") as f:
1587             lines = f.readlines()
1588             for l in lines:
1589                 if uuid in l:
1590                     success = True
1591                     break
1592         if not success:
1593             raise Exception("PIN request entry not in the log file")
1594     finally:
1595         subprocess.call(['sudo', 'rm', pinfile])
1596
1597 def test_ap_wps_auto_setup_with_config_file(dev, apdev):
1598     """WPS auto-setup with configuration file"""
1599     conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
1600     ifname = apdev[0]['ifname']
1601     try:
1602         with open(conffile, "w") as f:
1603             f.write("driver=nl80211\n")
1604             f.write("hw_mode=g\n")
1605             f.write("channel=1\n")
1606             f.write("ieee80211n=1\n")
1607             f.write("interface=%s\n" % ifname)
1608             f.write("ctrl_interface=/var/run/hostapd\n")
1609             f.write("ssid=wps\n")
1610             f.write("eap_server=1\n")
1611             f.write("wps_state=1\n")
1612         hostapd.add_bss('phy3', ifname, conffile)
1613         hapd = hostapd.Hostapd(ifname)
1614         hapd.request("WPS_PBC")
1615         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1616         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1617         ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1618         if ev is None:
1619             raise Exception("Association with the AP timed out")
1620         with open(conffile, "r") as f:
1621             lines = f.read().splitlines()
1622             vals = dict()
1623             for l in lines:
1624                 try:
1625                     [name,value] = l.split('=', 1)
1626                     vals[name] = value
1627                 except ValueError, e:
1628                     if "# WPS configuration" in l:
1629                         pass
1630                     else:
1631                         raise Exception("Unexpected configuration line: " + l)
1632         if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
1633             raise Exception("Incorrect configuration: " + str(vals))
1634     finally:
1635         subprocess.call(['sudo', 'rm', conffile])
1636
1637 def test_ap_wps_pbc_timeout(dev, apdev, params):
1638     """wpa_supplicant PBC walk time [long]"""
1639     if not params['long']:
1640         logger.info("Skip test case with long duration due to --long not specified")
1641         return "skip"
1642     ssid = "test-wps"
1643     hostapd.add_ap(apdev[0]['ifname'],
1644                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
1645     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1646     logger.info("Start WPS_PBC and wait for PBC walk time expiration")
1647     if "OK" not in dev[0].request("WPS_PBC"):
1648         raise Exception("WPS_PBC failed")
1649     ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=150)
1650     if ev is None:
1651         raise Exception("WPS-TIMEOUT not reported")
1652
1653 def add_ssdp_ap(ifname, ap_uuid):
1654     ssid = "wps-ssdp"
1655     ap_pin = "12345670"
1656     hostapd.add_ap(ifname,
1657                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1658                      "wpa_passphrase": "12345678", "wpa": "2",
1659                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1660                      "device_name": "Wireless AP", "manufacturer": "Company",
1661                      "model_name": "WAP", "model_number": "123",
1662                      "serial_number": "12345", "device_type": "6-0050F204-1",
1663                      "os_version": "01020300",
1664                      "config_methods": "label push_button",
1665                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
1666                      "friendly_name": "WPS Access Point",
1667                      "manufacturer_url": "http://www.example.com/",
1668                      "model_description": "Wireless Access Point",
1669                      "model_url": "http://www.example.com/model/",
1670                      "upc": "123456789012" })
1671
1672 def ssdp_send(msg, no_recv=False):
1673     socket.setdefaulttimeout(1)
1674     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1675     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1676     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1677     sock.bind(("127.0.0.1", 0))
1678     sock.sendto(msg, ("239.255.255.250", 1900))
1679     if no_recv:
1680         return None
1681     return sock.recv(1000)
1682
1683 def ssdp_send_msearch(st):
1684     msg = '\r\n'.join([
1685             'M-SEARCH * HTTP/1.1',
1686             'HOST: 239.255.255.250:1900',
1687             'MX: 1',
1688             'MAN: "ssdp:discover"',
1689             'ST: ' + st,
1690             '', ''])
1691     return ssdp_send(msg)
1692
1693 def test_ap_wps_ssdp_msearch(dev, apdev):
1694     """WPS AP and SSDP M-SEARCH messages"""
1695     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1696     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1697
1698     msg = '\r\n'.join([
1699             'M-SEARCH * HTTP/1.1',
1700             'Host: 239.255.255.250:1900',
1701             'Mx: 1',
1702             'Man: "ssdp:discover"',
1703             'St: urn:schemas-wifialliance-org:device:WFADevice:1',
1704             '', ''])
1705     ssdp_send(msg)
1706
1707     msg = '\r\n'.join([
1708             'M-SEARCH * HTTP/1.1',
1709             'host:\t239.255.255.250:1900\t\t\t\t \t\t',
1710             'mx: \t1\t\t   ',
1711             'man: \t \t "ssdp:discover"   ',
1712             'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
1713             '', ''])
1714     ssdp_send(msg)
1715
1716     ssdp_send_msearch("ssdp:all")
1717     ssdp_send_msearch("upnp:rootdevice")
1718     ssdp_send_msearch("uuid:" + ap_uuid)
1719     ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
1720     ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
1721
1722     msg = '\r\n'.join([
1723             'M-SEARCH * HTTP/1.1',
1724             'HOST:\t239.255.255.250:1900',
1725             'MAN: "ssdp:discover"',
1726             'MX: 130',
1727             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1728             '', ''])
1729     ssdp_send(msg, no_recv=True)
1730
1731 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
1732     """WPS AP and invalid SSDP M-SEARCH messages"""
1733     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1734     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1735
1736     socket.setdefaulttimeout(1)
1737     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1738     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1739     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1740     sock.bind(("127.0.0.1", 0))
1741
1742     logger.debug("Missing MX")
1743     msg = '\r\n'.join([
1744             'M-SEARCH * HTTP/1.1',
1745             'HOST: 239.255.255.250:1900',
1746             'MAN: "ssdp:discover"',
1747             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1748             '', ''])
1749     sock.sendto(msg, ("239.255.255.250", 1900))
1750
1751     logger.debug("Negative MX")
1752     msg = '\r\n'.join([
1753             'M-SEARCH * HTTP/1.1',
1754             'HOST: 239.255.255.250:1900',
1755             'MX: -1',
1756             'MAN: "ssdp:discover"',
1757             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1758             '', ''])
1759     sock.sendto(msg, ("239.255.255.250", 1900))
1760
1761     logger.debug("Invalid MX")
1762     msg = '\r\n'.join([
1763             'M-SEARCH * HTTP/1.1',
1764             'HOST: 239.255.255.250:1900',
1765             'MX; 1',
1766             'MAN: "ssdp:discover"',
1767             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1768             '', ''])
1769     sock.sendto(msg, ("239.255.255.250", 1900))
1770
1771     logger.debug("Missing MAN")
1772     msg = '\r\n'.join([
1773             'M-SEARCH * HTTP/1.1',
1774             'HOST: 239.255.255.250:1900',
1775             'MX: 1',
1776             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1777             '', ''])
1778     sock.sendto(msg, ("239.255.255.250", 1900))
1779
1780     logger.debug("Invalid MAN")
1781     msg = '\r\n'.join([
1782             'M-SEARCH * HTTP/1.1',
1783             'HOST: 239.255.255.250:1900',
1784             'MX: 1',
1785             'MAN: foo',
1786             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1787             '', ''])
1788     sock.sendto(msg, ("239.255.255.250", 1900))
1789     msg = '\r\n'.join([
1790             'M-SEARCH * HTTP/1.1',
1791             'HOST: 239.255.255.250:1900',
1792             'MX: 1',
1793             'MAN; "ssdp:discover"',
1794             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1795             '', ''])
1796     sock.sendto(msg, ("239.255.255.250", 1900))
1797
1798     logger.debug("Missing HOST")
1799     msg = '\r\n'.join([
1800             'M-SEARCH * HTTP/1.1',
1801             'MAN: "ssdp:discover"',
1802             'MX: 1',
1803             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1804             '', ''])
1805     sock.sendto(msg, ("239.255.255.250", 1900))
1806
1807     logger.debug("Missing ST")
1808     msg = '\r\n'.join([
1809             'M-SEARCH * HTTP/1.1',
1810             'HOST: 239.255.255.250:1900',
1811             'MAN: "ssdp:discover"',
1812             'MX: 1',
1813             '', ''])
1814     sock.sendto(msg, ("239.255.255.250", 1900))
1815
1816     logger.debug("Mismatching ST")
1817     msg = '\r\n'.join([
1818             'M-SEARCH * HTTP/1.1',
1819             'HOST: 239.255.255.250:1900',
1820             'MAN: "ssdp:discover"',
1821             'MX: 1',
1822             'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
1823             '', ''])
1824     sock.sendto(msg, ("239.255.255.250", 1900))
1825     msg = '\r\n'.join([
1826             'M-SEARCH * HTTP/1.1',
1827             'HOST: 239.255.255.250:1900',
1828             'MAN: "ssdp:discover"',
1829             'MX: 1',
1830             'ST: foo:bar',
1831             '', ''])
1832     sock.sendto(msg, ("239.255.255.250", 1900))
1833     msg = '\r\n'.join([
1834             'M-SEARCH * HTTP/1.1',
1835             'HOST: 239.255.255.250:1900',
1836             'MAN: "ssdp:discover"',
1837             'MX: 1',
1838             'ST: foobar',
1839             '', ''])
1840     sock.sendto(msg, ("239.255.255.250", 1900))
1841
1842     logger.debug("Invalid ST")
1843     msg = '\r\n'.join([
1844             'M-SEARCH * HTTP/1.1',
1845             'HOST: 239.255.255.250:1900',
1846             'MAN: "ssdp:discover"',
1847             'MX: 1',
1848             'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
1849             '', ''])
1850     sock.sendto(msg, ("239.255.255.250", 1900))
1851
1852     logger.debug("Invalid M-SEARCH")
1853     msg = '\r\n'.join([
1854             'M+SEARCH * HTTP/1.1',
1855             'HOST: 239.255.255.250:1900',
1856             'MAN: "ssdp:discover"',
1857             'MX: 1',
1858             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1859             '', ''])
1860     sock.sendto(msg, ("239.255.255.250", 1900))
1861     msg = '\r\n'.join([
1862             'M-SEARCH-* HTTP/1.1',
1863             'HOST: 239.255.255.250:1900',
1864             'MAN: "ssdp:discover"',
1865             'MX: 1',
1866             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1867             '', ''])
1868     sock.sendto(msg, ("239.255.255.250", 1900))
1869
1870     logger.debug("Invalid message format")
1871     sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
1872     msg = '\r'.join([
1873             'M-SEARCH * HTTP/1.1',
1874             'HOST: 239.255.255.250:1900',
1875             'MAN: "ssdp:discover"',
1876             'MX: 1',
1877             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1878             '', ''])
1879     sock.sendto(msg, ("239.255.255.250", 1900))
1880
1881     try:
1882         r = sock.recv(1000)
1883         raise Exception("Unexpected M-SEARCH response: " + r)
1884     except socket.timeout:
1885         pass
1886
1887     logger.debug("Valid M-SEARCH")
1888     msg = '\r\n'.join([
1889             'M-SEARCH * HTTP/1.1',
1890             'HOST: 239.255.255.250:1900',
1891             'MAN: "ssdp:discover"',
1892             'MX: 1',
1893             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1894             '', ''])
1895     sock.sendto(msg, ("239.255.255.250", 1900))
1896
1897     try:
1898         r = sock.recv(1000)
1899         pass
1900     except socket.timeout:
1901         raise Exception("No SSDP response")
1902
1903 def test_ap_wps_ssdp_burst(dev, apdev):
1904     """WPS AP and SSDP burst"""
1905     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1906     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1907
1908     msg = '\r\n'.join([
1909             'M-SEARCH * HTTP/1.1',
1910             'HOST: 239.255.255.250:1900',
1911             'MAN: "ssdp:discover"',
1912             'MX: 1',
1913             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1914             '', ''])
1915     socket.setdefaulttimeout(1)
1916     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1917     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1918     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1919     sock.bind(("127.0.0.1", 0))
1920     for i in range(0, 25):
1921         sock.sendto(msg, ("239.255.255.250", 1900))
1922     resp = 0
1923     while True:
1924         try:
1925             r = sock.recv(1000)
1926             if not r.startswith("HTTP/1.1 200 OK\r\n"):
1927                 raise Exception("Unexpected message: " + r)
1928             resp += 1
1929         except socket.timeout:
1930             break
1931     if resp < 20:
1932         raise Exception("Too few SSDP responses")
1933
1934     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1935     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1936     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1937     sock.bind(("127.0.0.1", 0))
1938     for i in range(0, 25):
1939         sock.sendto(msg, ("239.255.255.250", 1900))
1940     while True:
1941         try:
1942             r = sock.recv(1000)
1943             if ap_uuid in r:
1944                 break
1945         except socket.timeout:
1946             raise Exception("No SSDP response")
1947
1948 def ssdp_get_location(uuid):
1949     res = ssdp_send_msearch("uuid:" + uuid)
1950     location = None
1951     for l in res.splitlines():
1952         if l.lower().startswith("location:"):
1953             location = l.split(':', 1)[1].strip()
1954             break
1955     if location is None:
1956         raise Exception("No UPnP location found")
1957     return location
1958
1959 def upnp_get_urls(location):
1960     conn = urllib.urlopen(location)
1961     tree = ET.parse(conn)
1962     root = tree.getroot()
1963     urn = '{urn:schemas-upnp-org:device-1-0}'
1964     service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
1965     res = {}
1966     res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
1967     res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
1968     res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
1969     return res
1970
1971 def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
1972     soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
1973     wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
1974     ET.register_namespace('soapenv', soapns)
1975     ET.register_namespace('wfa', wpsns)
1976     attrib = {}
1977     attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
1978     root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
1979     body = ET.SubElement(root, "{%s}Body" % soapns)
1980     act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
1981     tree = ET.ElementTree(root)
1982     soap = StringIO.StringIO()
1983     tree.write(soap, xml_declaration=True, encoding='utf-8')
1984
1985     headers = { "Content-type": 'text/xml; charset="utf-8"' }
1986     if include_soap_action:
1987         headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
1988     elif soap_action_override:
1989         headers["SOAPAction"] = soap_action_override
1990     conn.request("POST", path, soap.getvalue(), headers)
1991     return conn.getresponse()
1992
1993 def test_ap_wps_upnp(dev, apdev):
1994     """WPS AP and UPnP operations"""
1995     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1996     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1997
1998     location = ssdp_get_location(ap_uuid)
1999     urls = upnp_get_urls(location)
2000
2001     conn = urllib.urlopen(urls['scpd_url'])
2002     scpd = conn.read()
2003
2004     conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
2005     if conn.getcode() != 404:
2006         raise Exception("Unexpected HTTP response to GET unknown URL")
2007
2008     url = urlparse.urlparse(location)
2009     conn = httplib.HTTPConnection(url.netloc)
2010     #conn.set_debuglevel(1)
2011     headers = { "Content-type": 'text/xml; charset="utf-8"',
2012                 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2013     conn.request("POST", "hello", "\r\n\r\n", headers)
2014     resp = conn.getresponse()
2015     if resp.status != 404:
2016         raise Exception("Unexpected HTTP response: %s" % resp.status)
2017
2018     conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2019     resp = conn.getresponse()
2020     if resp.status != 501:
2021         raise Exception("Unexpected HTTP response: %s" % resp.status)
2022
2023     headers = { "Content-type": 'text/xml; charset="utf-8"',
2024                 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2025     ctrlurl = urlparse.urlparse(urls['control_url'])
2026     conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2027     resp = conn.getresponse()
2028     if resp.status != 401:
2029         raise Exception("Unexpected HTTP response: %s" % resp.status)
2030
2031     logger.debug("GetDeviceInfo without SOAPAction header")
2032     resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2033                             include_soap_action=False)
2034     if resp.status != 401:
2035         raise Exception("Unexpected HTTP response: %s" % resp.status)
2036
2037     logger.debug("GetDeviceInfo with invalid SOAPAction header")
2038     for act in [ "foo",
2039                  "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2040                  '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2041                  '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2042         resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2043                                 include_soap_action=False,
2044                                 soap_action_override=act)
2045         if resp.status != 401:
2046             raise Exception("Unexpected HTTP response: %s" % resp.status)
2047
2048     resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2049     if resp.status != 200:
2050         raise Exception("Unexpected HTTP response: %s" % resp.status)
2051     dev = resp.read()
2052     if "NewDeviceInfo" not in dev:
2053         raise Exception("Unexpected GetDeviceInfo response")
2054
2055     logger.debug("PutMessage without required parameters")
2056     resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2057     if resp.status != 600:
2058         raise Exception("Unexpected HTTP response: %s" % resp.status)
2059
2060     logger.debug("PutWLANResponse without required parameters")
2061     resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2062     if resp.status != 600:
2063         raise Exception("Unexpected HTTP response: %s" % resp.status)
2064
2065     logger.debug("SetSelectedRegistrar from unregistered ER")
2066     resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2067     if resp.status != 501:
2068         raise Exception("Unexpected HTTP response: %s" % resp.status)
2069
2070     logger.debug("Unknown action")
2071     resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2072     if resp.status != 401:
2073         raise Exception("Unexpected HTTP response: %s" % resp.status)
2074
2075 def test_ap_wps_upnp_subscribe(dev, apdev):
2076     """WPS AP and UPnP event subscription"""
2077     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2078     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2079
2080     location = ssdp_get_location(ap_uuid)
2081     urls = upnp_get_urls(location)
2082     eventurl = urlparse.urlparse(urls['event_sub_url'])
2083
2084     url = urlparse.urlparse(location)
2085     conn = httplib.HTTPConnection(url.netloc)
2086     #conn.set_debuglevel(1)
2087     headers = { "callback": '<http://127.0.0.1:12345/event>',
2088                 "timeout": "Second-1234" }
2089     conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2090     resp = conn.getresponse()
2091     if resp.status != 412:
2092         raise Exception("Unexpected HTTP response: %s" % resp.status)
2093
2094     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2095     resp = conn.getresponse()
2096     if resp.status != 412:
2097         raise Exception("Unexpected HTTP response: %s" % resp.status)
2098
2099     headers = { "NT": "upnp:event",
2100                 "timeout": "Second-1234" }
2101     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2102     resp = conn.getresponse()
2103     if resp.status != 412:
2104         raise Exception("Unexpected HTTP response: %s" % resp.status)
2105
2106     headers = { "callback": '<http://127.0.0.1:12345/event>',
2107                 "NT": "upnp:foobar",
2108                 "timeout": "Second-1234" }
2109     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2110     resp = conn.getresponse()
2111     if resp.status != 400:
2112         raise Exception("Unexpected HTTP response: %s" % resp.status)
2113
2114     logger.debug("Valid subscription")
2115     headers = { "callback": '<http://127.0.0.1:12345/event>',
2116                 "NT": "upnp:event",
2117                 "timeout": "Second-1234" }
2118     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2119     resp = conn.getresponse()
2120     if resp.status != 200:
2121         raise Exception("Unexpected HTTP response: %s" % resp.status)
2122     sid = resp.getheader("sid")
2123     logger.debug("Subscription SID " + sid)
2124
2125     logger.debug("Invalid re-subscription")
2126     headers = { "NT": "upnp:event",
2127                 "sid": "123456734567854",
2128                 "timeout": "Second-1234" }
2129     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2130     resp = conn.getresponse()
2131     if resp.status != 400:
2132         raise Exception("Unexpected HTTP response: %s" % resp.status)
2133
2134     logger.debug("Invalid re-subscription")
2135     headers = { "NT": "upnp:event",
2136                 "sid": "uuid:123456734567854",
2137                 "timeout": "Second-1234" }
2138     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2139     resp = conn.getresponse()
2140     if resp.status != 400:
2141         raise Exception("Unexpected HTTP response: %s" % resp.status)
2142
2143     logger.debug("Invalid re-subscription")
2144     headers = { "callback": '<http://127.0.0.1:12345/event>',
2145                 "NT": "upnp:event",
2146                 "sid": sid,
2147                 "timeout": "Second-1234" }
2148     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2149     resp = conn.getresponse()
2150     if resp.status != 400:
2151         raise Exception("Unexpected HTTP response: %s" % resp.status)
2152
2153     logger.debug("SID mismatch in re-subscription")
2154     headers = { "NT": "upnp:event",
2155                 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2156                 "timeout": "Second-1234" }
2157     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2158     resp = conn.getresponse()
2159     if resp.status != 412:
2160         raise Exception("Unexpected HTTP response: %s" % resp.status)
2161
2162     logger.debug("Valid re-subscription")
2163     headers = { "NT": "upnp:event",
2164                 "sid": sid,
2165                 "timeout": "Second-1234" }
2166     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2167     resp = conn.getresponse()
2168     if resp.status != 200:
2169         raise Exception("Unexpected HTTP response: %s" % resp.status)
2170     sid2 = resp.getheader("sid")
2171     logger.debug("Subscription SID " + sid2)
2172
2173     if sid != sid2:
2174         raise Exception("Unexpected SID change")
2175
2176     logger.debug("Valid re-subscription")
2177     headers = { "NT": "upnp:event",
2178                 "sid": "uuid: \t \t" + sid.split(':')[1],
2179                 "timeout": "Second-1234" }
2180     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2181     resp = conn.getresponse()
2182     if resp.status != 200:
2183         raise Exception("Unexpected HTTP response: %s" % resp.status)
2184
2185     logger.debug("Invalid unsubscription")
2186     headers = { "sid": sid }
2187     conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
2188     resp = conn.getresponse()
2189     if resp.status != 412:
2190         raise Exception("Unexpected HTTP response: %s" % resp.status)
2191     headers = { "foo": "bar" }
2192     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2193     resp = conn.getresponse()
2194     if resp.status != 412:
2195         raise Exception("Unexpected HTTP response: %s" % resp.status)
2196
2197     logger.debug("Valid unsubscription")
2198     headers = { "sid": sid }
2199     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2200     resp = conn.getresponse()
2201     if resp.status != 200:
2202         raise Exception("Unexpected HTTP response: %s" % resp.status)
2203
2204     logger.debug("Unsubscription for not existing SID")
2205     headers = { "sid": sid }
2206     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2207     resp = conn.getresponse()
2208     if resp.status != 412:
2209         raise Exception("Unexpected HTTP response: %s" % resp.status)
2210
2211     logger.debug("Invalid unsubscription")
2212     headers = { "sid": " \t \tfoo" }
2213     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2214     resp = conn.getresponse()
2215     if resp.status != 400:
2216         raise Exception("Unexpected HTTP response: %s" % resp.status)
2217
2218     logger.debug("Invalid unsubscription")
2219     headers = { "sid": "uuid:\t \tfoo" }
2220     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2221     resp = conn.getresponse()
2222     if resp.status != 400:
2223         raise Exception("Unexpected HTTP response: %s" % resp.status)
2224
2225     logger.debug("Invalid unsubscription")
2226     headers = { "NT": "upnp:event",
2227                 "sid": sid }
2228     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2229     resp = conn.getresponse()
2230     if resp.status != 400:
2231         raise Exception("Unexpected HTTP response: %s" % resp.status)
2232     headers = { "callback": '<http://127.0.0.1:12345/event>',
2233                 "sid": sid }
2234     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2235     resp = conn.getresponse()
2236     if resp.status != 400:
2237         raise Exception("Unexpected HTTP response: %s" % resp.status)
2238
2239     logger.debug("Valid subscription with multiple callbacks")
2240     headers = { "callback": '<http://127.0.0.1:12345/event> <http://127.0.0.1:12345/event>\t<http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event><http://127.0.0.1:12345/event>',
2241                 "NT": "upnp:event",
2242                 "timeout": "Second-1234" }
2243     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2244     resp = conn.getresponse()
2245     if resp.status != 200:
2246         raise Exception("Unexpected HTTP response: %s" % resp.status)
2247     sid = resp.getheader("sid")
2248     logger.debug("Subscription SID " + sid)
2249
2250 def test_ap_wps_disabled(dev, apdev):
2251     """WPS operations while WPS is disabled"""
2252     ssid = "test-wps-disabled"
2253     hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
2254     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2255     if "FAIL" not in hapd.request("WPS_PBC"):
2256         raise Exception("WPS_PBC succeeded unexpectedly")
2257     if "FAIL" not in hapd.request("WPS_CANCEL"):
2258         raise Exception("WPS_CANCEL succeeded unexpectedly")
2259
2260 def test_ap_wps_mixed_cred(dev, apdev):
2261     """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
2262     ssid = "test-wps-wep"
2263     hostapd.add_ap(apdev[0]['ifname'],
2264                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2265                      "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
2266     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2267     hapd.request("WPS_PBC")
2268     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2269     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2270     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
2271     if ev is None:
2272         raise Exception("WPS-SUCCESS event timed out")
2273     nets = dev[0].list_networks()
2274     if len(nets) != 1:
2275         raise Exception("Unexpected number of network blocks")
2276     id = nets[0]['id']
2277     proto = dev[0].get_network(id, "proto")
2278     if proto != "WPA RSN":
2279         raise Exception("Unexpected merged proto field value: " + proto)
2280     pairwise = dev[0].get_network(id, "pairwise")
2281     if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
2282         raise Exception("Unexpected merged pairwise field value: " + pairwise)
2283
2284 def test_ap_wps_while_connected(dev, apdev):
2285     """WPS PBC provisioning while connected to another AP"""
2286     ssid = "test-wps-conf"
2287     hostapd.add_ap(apdev[0]['ifname'],
2288                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2289                      "wpa_passphrase": "12345678", "wpa": "2",
2290                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2291     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2292
2293     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
2294     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
2295
2296     logger.info("WPS provisioning step")
2297     hapd.request("WPS_PBC")
2298     dev[0].dump_monitor()
2299     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2300     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
2301     if ev is None:
2302         raise Exception("Association with the AP timed out")
2303     status = dev[0].get_status()
2304     if status['bssid'] != apdev[0]['bssid']:
2305         raise Exception("Unexpected BSSID")
2306
2307 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
2308     """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
2309     ssid = "test-wps-conf"
2310     hostapd.add_ap(apdev[0]['ifname'],
2311                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2312                      "wpa_passphrase": "12345678", "wpa": "2",
2313                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2314     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2315
2316     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
2317
2318     try:
2319         dev[0].request("STA_AUTOCONNECT 0")
2320         dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
2321
2322         logger.info("WPS provisioning step")
2323         hapd.request("WPS_PBC")
2324         dev[0].dump_monitor()
2325         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2326         ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
2327         if ev is None:
2328             raise Exception("Association with the AP timed out")
2329         status = dev[0].get_status()
2330         if status['bssid'] != apdev[0]['bssid']:
2331             raise Exception("Unexpected BSSID")
2332     finally:
2333         dev[0].request("STA_AUTOCONNECT 1")
2334
2335 def test_ap_wps_from_event(dev, apdev):
2336     """WPS PBC event on AP to enable PBC"""
2337     ssid = "test-wps-conf"
2338     hapd = hostapd.add_ap(apdev[0]['ifname'],
2339                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2340                             "wpa_passphrase": "12345678", "wpa": "2",
2341                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2342     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2343     dev[0].dump_monitor()
2344     hapd.dump_monitor()
2345     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2346
2347     ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
2348     if ev is None:
2349         raise Exception("No WPS-ENROLLEE-SEEN event on AP")
2350     vals = ev.split(' ')
2351     if vals[1] != dev[0].p2p_interface_addr():
2352         raise Exception("Unexpected enrollee address: " + vals[1])
2353     if vals[5] != '4':
2354         raise Exception("Unexpected Device Password Id: " + vals[5])
2355     hapd.request("WPS_PBC")
2356     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
2357     if ev is None:
2358         raise Exception("Association with the AP timed out")
2359
2360 def test_ap_wps_ap_scan_2(dev, apdev):
2361     """AP_SCAN 2 for WPS"""
2362     ssid = "test-wps-conf"
2363     hapd = hostapd.add_ap(apdev[0]['ifname'],
2364                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2365                             "wpa_passphrase": "12345678", "wpa": "2",
2366                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2367     hapd.request("WPS_PBC")
2368
2369     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
2370     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
2371
2372     if "OK" not in wpas.request("AP_SCAN 2"):
2373         raise Exception("Failed to set AP_SCAN 2")
2374
2375     wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
2376     wpas.request("WPS_PBC " + apdev[0]['bssid'])
2377     ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
2378     if ev is None:
2379         raise Exception("WPS-SUCCESS event timed out")
2380     ev = wpas.wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
2381     if ev is None:
2382         raise Exception("Association with the AP timed out")
2383     wpas.request("DISCONNECT")
2384     wpas.request("BSS_FLUSH 0")
2385     wpas.dump_monitor()
2386     wpas.request("REASSOCIATE")
2387     ev = wpas.wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
2388     if ev is None:
2389         raise Exception("Association with the AP timed out")