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