tests: WPS AP and UPnP event subscription and many events
[mech_eap.git] / tests / hwsim / test_ap_wps.py
1 # WPS tests
2 # Copyright (c) 2013-2015, 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 base64
8 import binascii
9 import os
10 import time
11 import stat
12 import subprocess
13 import logging
14 logger = logging.getLogger()
15 import re
16 import socket
17 import httplib
18 import urlparse
19 import urllib
20 import xml.etree.ElementTree as ET
21 import StringIO
22 import SocketServer
23
24 import hwsim_utils
25 import hostapd
26 from wpasupplicant import WpaSupplicant
27 from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
28
29 def wps_start_ap(apdev, ssid="test-wps-conf"):
30     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
31                "wpa_passphrase": "12345678", "wpa": "2",
32                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
33     return hostapd.add_ap(apdev['ifname'], params)
34
35 def test_ap_wps_init(dev, apdev):
36     """Initial AP configuration with first WPS Enrollee"""
37     ssid = "test-wps"
38     hostapd.add_ap(apdev[0]['ifname'],
39                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
40     hapd = hostapd.Hostapd(apdev[0]['ifname'])
41     logger.info("WPS provisioning step")
42     hapd.request("WPS_PBC")
43     if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
44         raise Exception("PBC status not shown correctly")
45
46     id = dev[0].add_network()
47     dev[0].set_network_quoted(id, "ssid", "home")
48     dev[0].set_network_quoted(id, "psk", "12345678")
49     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
50
51     id = dev[0].add_network()
52     dev[0].set_network_quoted(id, "ssid", "home2")
53     dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
54     dev[0].set_network(id, "key_mgmt", "NONE")
55     dev[0].request("ENABLE_NETWORK %s no-connect" % id)
56
57     dev[0].request("WPS_PBC")
58     dev[0].wait_connected(timeout=30)
59     status = dev[0].get_status()
60     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
61         raise Exception("Not fully connected")
62     if status['ssid'] != ssid:
63         raise Exception("Unexpected SSID")
64     if status['pairwise_cipher'] != 'CCMP':
65         raise Exception("Unexpected encryption configuration")
66     if status['key_mgmt'] != 'WPA2-PSK':
67         raise Exception("Unexpected key_mgmt")
68
69     status = hapd.request("WPS_GET_STATUS")
70     if "PBC Status: Disabled" not in status:
71         raise Exception("PBC status not shown correctly")
72     if "Last WPS result: Success" not in status:
73         raise Exception("Last WPS result not shown correctly")
74     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
75         raise Exception("Peer address not shown correctly")
76     conf = hapd.request("GET_CONFIG")
77     if "wps_state=configured" not in conf:
78         raise Exception("AP not in WPS configured state")
79     if "wpa=3" not in conf:
80         raise Exception("AP not in WPA+WPA2 configuration")
81     if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
82         raise Exception("Unexpected rsn_pairwise_cipher")
83     if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
84         raise Exception("Unexpected wpa_pairwise_cipher")
85     if "group_cipher=TKIP" not in conf:
86         raise Exception("Unexpected group_cipher")
87
88     if len(dev[0].list_networks()) != 3:
89         raise Exception("Unexpected number of network blocks")
90
91 def test_ap_wps_init_2ap_pbc(dev, apdev):
92     """Initial two-radio AP configuration with first WPS PBC Enrollee"""
93     ssid = "test-wps"
94     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
95     hostapd.add_ap(apdev[0]['ifname'], params)
96     hostapd.add_ap(apdev[1]['ifname'], params)
97     hapd = hostapd.Hostapd(apdev[0]['ifname'])
98     logger.info("WPS provisioning step")
99     hapd.request("WPS_PBC")
100     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
101     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
102     bss = dev[0].get_bss(apdev[0]['bssid'])
103     if "[WPS-PBC]" not in bss['flags']:
104         raise Exception("WPS-PBC flag missing from AP1")
105     bss = dev[0].get_bss(apdev[1]['bssid'])
106     if "[WPS-PBC]" not in bss['flags']:
107         raise Exception("WPS-PBC flag missing from AP2")
108     dev[0].dump_monitor()
109     dev[0].request("SET wps_cred_processing 2")
110     dev[0].request("WPS_PBC")
111     ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
112     dev[0].request("SET wps_cred_processing 0")
113     if ev is None:
114         raise Exception("WPS cred event not seen")
115     if "100e" not in ev:
116         raise Exception("WPS attributes not included in the cred event")
117     dev[0].wait_connected(timeout=30)
118
119     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
120     dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
121     bss = dev[1].get_bss(apdev[0]['bssid'])
122     if "[WPS-PBC]" in bss['flags']:
123         raise Exception("WPS-PBC flag not cleared from AP1")
124     bss = dev[1].get_bss(apdev[1]['bssid'])
125     if "[WPS-PBC]" in bss['flags']:
126         raise Exception("WPS-PBC flag not cleared from AP2")
127
128 def test_ap_wps_init_2ap_pin(dev, apdev):
129     """Initial two-radio AP configuration with first WPS PIN Enrollee"""
130     ssid = "test-wps"
131     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
132     hostapd.add_ap(apdev[0]['ifname'], params)
133     hostapd.add_ap(apdev[1]['ifname'], params)
134     hapd = hostapd.Hostapd(apdev[0]['ifname'])
135     logger.info("WPS provisioning step")
136     pin = dev[0].wps_read_pin()
137     hapd.request("WPS_PIN any " + pin)
138     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
139     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
140     bss = dev[0].get_bss(apdev[0]['bssid'])
141     if "[WPS-AUTH]" not in bss['flags']:
142         raise Exception("WPS-AUTH flag missing from AP1")
143     bss = dev[0].get_bss(apdev[1]['bssid'])
144     if "[WPS-AUTH]" not in bss['flags']:
145         raise Exception("WPS-AUTH flag missing from AP2")
146     dev[0].dump_monitor()
147     dev[0].request("WPS_PIN any " + pin)
148     dev[0].wait_connected(timeout=30)
149
150     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
151     dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
152     bss = dev[1].get_bss(apdev[0]['bssid'])
153     if "[WPS-AUTH]" in bss['flags']:
154         raise Exception("WPS-AUTH flag not cleared from AP1")
155     bss = dev[1].get_bss(apdev[1]['bssid'])
156     if "[WPS-AUTH]" in bss['flags']:
157         raise Exception("WPS-AUTH flag not cleared from AP2")
158
159 def test_ap_wps_init_through_wps_config(dev, apdev):
160     """Initial AP configuration using wps_config command"""
161     ssid = "test-wps-init-config"
162     hostapd.add_ap(apdev[0]['ifname'],
163                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
164     hapd = hostapd.Hostapd(apdev[0]['ifname'])
165     if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
166         raise Exception("WPS_CONFIG command failed")
167     ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
168     if ev is None:
169         raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
170     # It takes some time for the AP to update Beacon and Probe Response frames,
171     # so wait here before requesting the scan to be started to avoid adding
172     # extra five second wait to the test due to fetching obsolete scan results.
173     hapd.ping()
174     time.sleep(0.2)
175     dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
176                    pairwise="CCMP", group="CCMP")
177
178 def test_ap_wps_init_through_wps_config_2(dev, apdev):
179     """AP configuration using wps_config and wps_cred_processing=2"""
180     ssid = "test-wps-init-config"
181     hostapd.add_ap(apdev[0]['ifname'],
182                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
183                      "wps_cred_processing": "2" })
184     hapd = hostapd.Hostapd(apdev[0]['ifname'])
185     if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
186         raise Exception("WPS_CONFIG command failed")
187     ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
188     if ev is None:
189         raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
190     if "100e" not in ev:
191         raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
192
193 def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
194     """AP configuration using wps_config command with invalid passphrase"""
195     ssid = "test-wps-init-config"
196     hostapd.add_ap(apdev[0]['ifname'],
197                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
198     hapd = hostapd.Hostapd(apdev[0]['ifname'])
199     if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
200         raise Exception("Invalid WPS_CONFIG command accepted")
201
202 def test_ap_wps_conf(dev, apdev):
203     """WPS PBC provisioning with configured AP"""
204     ssid = "test-wps-conf"
205     hostapd.add_ap(apdev[0]['ifname'],
206                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
207                      "wpa_passphrase": "12345678", "wpa": "2",
208                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
209     hapd = hostapd.Hostapd(apdev[0]['ifname'])
210     logger.info("WPS provisioning step")
211     hapd.request("WPS_PBC")
212     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
213     dev[0].dump_monitor()
214     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
215     dev[0].wait_connected(timeout=30)
216     status = dev[0].get_status()
217     if status['wpa_state'] != 'COMPLETED':
218         raise Exception("Not fully connected")
219     if status['bssid'] != apdev[0]['bssid']:
220         raise Exception("Unexpected BSSID")
221     if status['ssid'] != ssid:
222         raise Exception("Unexpected SSID")
223     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
224         raise Exception("Unexpected encryption configuration")
225     if status['key_mgmt'] != 'WPA2-PSK':
226         raise Exception("Unexpected key_mgmt")
227
228     sta = hapd.get_sta(dev[0].p2p_interface_addr())
229     if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
230         raise Exception("Device name not available in STA command")
231
232 def test_ap_wps_conf_5ghz(dev, apdev):
233     """WPS PBC provisioning with configured AP on 5 GHz band"""
234     try:
235         hapd = None
236         ssid = "test-wps-conf"
237         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
238                    "wpa_passphrase": "12345678", "wpa": "2",
239                    "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
240                    "country_code": "FI", "hw_mode": "a", "channel": "36" }
241         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
242         logger.info("WPS provisioning step")
243         hapd.request("WPS_PBC")
244         dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
245         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
246         dev[0].wait_connected(timeout=30)
247
248         sta = hapd.get_sta(dev[0].p2p_interface_addr())
249         if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
250             raise Exception("Device name not available in STA command")
251     finally:
252         dev[0].request("DISCONNECT")
253         if hapd:
254             hapd.request("DISABLE")
255         subprocess.call(['iw', 'reg', 'set', '00'])
256         dev[0].flush_scan_cache()
257
258 def test_ap_wps_conf_chan14(dev, apdev):
259     """WPS PBC provisioning with configured AP on channel 14"""
260     try:
261         hapd = None
262         ssid = "test-wps-conf"
263         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
264                    "wpa_passphrase": "12345678", "wpa": "2",
265                    "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
266                    "country_code": "JP", "hw_mode": "b", "channel": "14" }
267         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
268         logger.info("WPS provisioning step")
269         hapd.request("WPS_PBC")
270         dev[0].request("WPS_PBC")
271         dev[0].wait_connected(timeout=30)
272
273         sta = hapd.get_sta(dev[0].p2p_interface_addr())
274         if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
275             raise Exception("Device name not available in STA command")
276     finally:
277         dev[0].request("DISCONNECT")
278         if hapd:
279             hapd.request("DISABLE")
280         subprocess.call(['iw', 'reg', 'set', '00'])
281         dev[0].flush_scan_cache()
282
283 def test_ap_wps_twice(dev, apdev):
284     """WPS provisioning with twice to change passphrase"""
285     ssid = "test-wps-twice"
286     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
287                "wpa_passphrase": "12345678", "wpa": "2",
288                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
289     hostapd.add_ap(apdev[0]['ifname'], params)
290     hapd = hostapd.Hostapd(apdev[0]['ifname'])
291     logger.info("WPS provisioning step")
292     hapd.request("WPS_PBC")
293     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
294     dev[0].dump_monitor()
295     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
296     dev[0].wait_connected(timeout=30)
297     dev[0].request("DISCONNECT")
298
299     logger.info("Restart AP with different passphrase and re-run WPS")
300     hapd_global = hostapd.HostapdGlobal()
301     hapd_global.remove(apdev[0]['ifname'])
302     params['wpa_passphrase'] = 'another passphrase'
303     hostapd.add_ap(apdev[0]['ifname'], params)
304     hapd = hostapd.Hostapd(apdev[0]['ifname'])
305     logger.info("WPS provisioning step")
306     hapd.request("WPS_PBC")
307     dev[0].dump_monitor()
308     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
309     dev[0].wait_connected(timeout=30)
310     networks = dev[0].list_networks()
311     if len(networks) > 1:
312         raise Exception("Unexpected duplicated network block present")
313
314 def test_ap_wps_incorrect_pin(dev, apdev):
315     """WPS PIN provisioning with incorrect PIN"""
316     ssid = "test-wps-incorrect-pin"
317     hostapd.add_ap(apdev[0]['ifname'],
318                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
319                      "wpa_passphrase": "12345678", "wpa": "2",
320                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
321     hapd = hostapd.Hostapd(apdev[0]['ifname'])
322
323     logger.info("WPS provisioning attempt 1")
324     hapd.request("WPS_PIN any 12345670")
325     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
326     dev[0].dump_monitor()
327     dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
328     ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
329     if ev is None:
330         raise Exception("WPS operation timed out")
331     if "config_error=18" not in ev:
332         raise Exception("Incorrect config_error reported")
333     if "msg=8" not in ev:
334         raise Exception("PIN error detected on incorrect message")
335     dev[0].wait_disconnected(timeout=10)
336     dev[0].request("WPS_CANCEL")
337     # if a scan was in progress, wait for it to complete before trying WPS again
338     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
339
340     status = hapd.request("WPS_GET_STATUS")
341     if "Last WPS result: Failed" not in status:
342         raise Exception("WPS failure result not shown correctly")
343
344     logger.info("WPS provisioning attempt 2")
345     hapd.request("WPS_PIN any 12345670")
346     dev[0].dump_monitor()
347     dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
348     ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
349     if ev is None:
350         raise Exception("WPS operation timed out")
351     if "config_error=18" not in ev:
352         raise Exception("Incorrect config_error reported")
353     if "msg=10" not in ev:
354         raise Exception("PIN error detected on incorrect message")
355     dev[0].wait_disconnected(timeout=10)
356
357 def test_ap_wps_conf_pin(dev, apdev):
358     """WPS PIN provisioning with configured AP"""
359     ssid = "test-wps-conf-pin"
360     hostapd.add_ap(apdev[0]['ifname'],
361                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
362                      "wpa_passphrase": "12345678", "wpa": "2",
363                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
364     hapd = hostapd.Hostapd(apdev[0]['ifname'])
365     logger.info("WPS provisioning step")
366     pin = dev[0].wps_read_pin()
367     hapd.request("WPS_PIN any " + pin)
368     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
369     dev[0].dump_monitor()
370     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
371     dev[0].wait_connected(timeout=30)
372     status = dev[0].get_status()
373     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
374         raise Exception("Not fully connected")
375     if status['ssid'] != ssid:
376         raise Exception("Unexpected SSID")
377     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
378         raise Exception("Unexpected encryption configuration")
379     if status['key_mgmt'] != 'WPA2-PSK':
380         raise Exception("Unexpected key_mgmt")
381
382     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
383     bss = dev[1].get_bss(apdev[0]['bssid'])
384     if "[WPS-AUTH]" in bss['flags']:
385         raise Exception("WPS-AUTH flag not cleared")
386     logger.info("Try to connect from another station using the same PIN")
387     pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
388     ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
389     if ev is None:
390         raise Exception("Operation timed out")
391     if "WPS-M2D" not in ev:
392         raise Exception("Unexpected WPS operation started")
393     hapd.request("WPS_PIN any " + pin)
394     dev[1].wait_connected(timeout=30)
395
396 def test_ap_wps_conf_pin_v1(dev, apdev):
397     """WPS PIN provisioning with configured WPS v1.0 AP"""
398     ssid = "test-wps-conf-pin-v1"
399     hostapd.add_ap(apdev[0]['ifname'],
400                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
401                      "wpa_passphrase": "12345678", "wpa": "2",
402                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
403     hapd = hostapd.Hostapd(apdev[0]['ifname'])
404     logger.info("WPS provisioning step")
405     pin = dev[0].wps_read_pin()
406     hapd.request("SET wps_version_number 0x10")
407     hapd.request("WPS_PIN any " + pin)
408     found = False
409     for i in range(0, 10):
410         dev[0].scan(freq="2412")
411         if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
412             found = True
413             break
414     if not found:
415         hapd.request("SET wps_version_number 0x20")
416         raise Exception("WPS-PIN flag not seen in scan results")
417     dev[0].dump_monitor()
418     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
419     dev[0].wait_connected(timeout=30)
420     hapd.request("SET wps_version_number 0x20")
421
422 def test_ap_wps_conf_pin_2sta(dev, apdev):
423     """Two stations trying to use WPS PIN at the same time"""
424     ssid = "test-wps-conf-pin2"
425     hostapd.add_ap(apdev[0]['ifname'],
426                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
427                      "wpa_passphrase": "12345678", "wpa": "2",
428                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
429     hapd = hostapd.Hostapd(apdev[0]['ifname'])
430     logger.info("WPS provisioning step")
431     pin = "12345670"
432     pin2 = "55554444"
433     hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
434     hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
435     dev[0].dump_monitor()
436     dev[1].dump_monitor()
437     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
438     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
439     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
440     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
441     dev[0].wait_connected(timeout=30)
442     dev[1].wait_connected(timeout=30)
443
444 def test_ap_wps_conf_pin_timeout(dev, apdev):
445     """WPS PIN provisioning with configured AP timing out PIN"""
446     ssid = "test-wps-conf-pin"
447     hostapd.add_ap(apdev[0]['ifname'],
448                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
449                      "wpa_passphrase": "12345678", "wpa": "2",
450                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
451     hapd = hostapd.Hostapd(apdev[0]['ifname'])
452     addr = dev[0].p2p_interface_addr()
453     pin = dev[0].wps_read_pin()
454     if "FAIL" not in hapd.request("WPS_PIN "):
455         raise Exception("Unexpected success on invalid WPS_PIN")
456     hapd.request("WPS_PIN any " + pin + " 1")
457     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
458     time.sleep(1.1)
459     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
460     ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
461     if ev is None:
462         raise Exception("WPS-PIN-NEEDED event timed out")
463     ev = dev[0].wait_event(["WPS-M2D"])
464     if ev is None:
465         raise Exception("M2D not reported")
466     dev[0].request("WPS_CANCEL")
467
468     hapd.request("WPS_PIN any " + pin + " 20 " + addr)
469     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
470     dev[0].wait_connected(timeout=30)
471
472 def test_ap_wps_reg_connect(dev, apdev):
473     """WPS registrar using AP PIN to connect"""
474     ssid = "test-wps-reg-ap-pin"
475     appin = "12345670"
476     hostapd.add_ap(apdev[0]['ifname'],
477                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
478                      "wpa_passphrase": "12345678", "wpa": "2",
479                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
480                      "ap_pin": appin})
481     logger.info("WPS provisioning step")
482     dev[0].dump_monitor()
483     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
484     dev[0].wps_reg(apdev[0]['bssid'], appin)
485     status = dev[0].get_status()
486     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
487         raise Exception("Not fully connected")
488     if status['ssid'] != ssid:
489         raise Exception("Unexpected SSID")
490     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
491         raise Exception("Unexpected encryption configuration")
492     if status['key_mgmt'] != 'WPA2-PSK':
493         raise Exception("Unexpected key_mgmt")
494
495 def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
496     """WPS registrar using AP PIN to connect (WPA+WPA2)"""
497     ssid = "test-wps-reg-ap-pin"
498     appin = "12345670"
499     hostapd.add_ap(apdev[0]['ifname'],
500                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
501                      "wpa_passphrase": "12345678", "wpa": "3",
502                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
503                      "wpa_pairwise": "TKIP", "ap_pin": appin})
504     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
505     dev[0].wps_reg(apdev[0]['bssid'], appin)
506     status = dev[0].get_status()
507     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
508         raise Exception("Not fully connected")
509     if status['ssid'] != ssid:
510         raise Exception("Unexpected SSID")
511     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
512         raise Exception("Unexpected encryption configuration")
513     if status['key_mgmt'] != 'WPA2-PSK':
514         raise Exception("Unexpected key_mgmt")
515
516 def check_wps_reg_failure(dev, ap, appin):
517     dev.request("WPS_REG " + ap['bssid'] + " " + appin)
518     ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
519     if ev is None:
520         raise Exception("WPS operation timed out")
521     if "WPS-SUCCESS" in ev:
522         raise Exception("WPS operation succeeded unexpectedly")
523     if "config_error=15" not in ev:
524         raise Exception("WPS setup locked state was not reported correctly")
525
526 def test_ap_wps_random_ap_pin(dev, apdev):
527     """WPS registrar using random AP PIN"""
528     ssid = "test-wps-reg-random-ap-pin"
529     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
530     hostapd.add_ap(apdev[0]['ifname'],
531                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
532                      "wpa_passphrase": "12345678", "wpa": "2",
533                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
534                      "device_name": "Wireless AP", "manufacturer": "Company",
535                      "model_name": "WAP", "model_number": "123",
536                      "serial_number": "12345", "device_type": "6-0050F204-1",
537                      "os_version": "01020300",
538                      "config_methods": "label push_button",
539                      "uuid": ap_uuid, "upnp_iface": "lo" })
540     hapd = hostapd.Hostapd(apdev[0]['ifname'])
541     appin = hapd.request("WPS_AP_PIN random")
542     if "FAIL" in appin:
543         raise Exception("Could not generate random AP PIN")
544     if appin not in hapd.request("WPS_AP_PIN get"):
545         raise Exception("Could not fetch current AP PIN")
546     logger.info("WPS provisioning step")
547     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
548     dev[0].wps_reg(apdev[0]['bssid'], appin)
549
550     hapd.request("WPS_AP_PIN disable")
551     logger.info("WPS provisioning step with AP PIN disabled")
552     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
553     check_wps_reg_failure(dev[1], apdev[0], appin)
554
555     logger.info("WPS provisioning step with AP PIN reset")
556     appin = "12345670"
557     hapd.request("WPS_AP_PIN set " + appin)
558     dev[1].wps_reg(apdev[0]['bssid'], appin)
559     dev[0].request("REMOVE_NETWORK all")
560     dev[1].request("REMOVE_NETWORK all")
561     dev[0].wait_disconnected(timeout=10)
562     dev[1].wait_disconnected(timeout=10)
563
564     logger.info("WPS provisioning step after AP PIN timeout")
565     hapd.request("WPS_AP_PIN disable")
566     appin = hapd.request("WPS_AP_PIN random 1")
567     time.sleep(1.1)
568     if "FAIL" not in hapd.request("WPS_AP_PIN get"):
569         raise Exception("AP PIN unexpectedly still enabled")
570     check_wps_reg_failure(dev[0], apdev[0], appin)
571
572     logger.info("WPS provisioning step after AP PIN timeout(2)")
573     hapd.request("WPS_AP_PIN disable")
574     appin = "12345670"
575     hapd.request("WPS_AP_PIN set " + appin + " 1")
576     time.sleep(1.1)
577     if "FAIL" not in hapd.request("WPS_AP_PIN get"):
578         raise Exception("AP PIN unexpectedly still enabled")
579     check_wps_reg_failure(dev[1], apdev[0], appin)
580
581     with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
582         if "FAIL" in hapd.request("WPS_AP_PIN random 1"):
583             raise Exception("Failed to generate PIN during OOM")
584         hapd.request("WPS_AP_PIN disable")
585
586     with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
587         hapd.request("WPS_AP_PIN set 12345670")
588         hapd.request("WPS_AP_PIN disable")
589
590 def test_ap_wps_reg_config(dev, apdev):
591     """WPS registrar configuring an AP using AP PIN"""
592     ssid = "test-wps-init-ap-pin"
593     appin = "12345670"
594     hostapd.add_ap(apdev[0]['ifname'],
595                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
596                      "ap_pin": appin})
597     logger.info("WPS configuration step")
598     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
599     dev[0].dump_monitor()
600     new_ssid = "wps-new-ssid"
601     new_passphrase = "1234567890"
602     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
603                    new_passphrase)
604     status = dev[0].get_status()
605     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
606         raise Exception("Not fully connected")
607     if status['ssid'] != new_ssid:
608         raise Exception("Unexpected SSID")
609     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
610         raise Exception("Unexpected encryption configuration")
611     if status['key_mgmt'] != 'WPA2-PSK':
612         raise Exception("Unexpected key_mgmt")
613
614     logger.info("Re-configure back to open")
615     dev[0].request("REMOVE_NETWORK all")
616     dev[0].flush_scan_cache()
617     dev[0].dump_monitor()
618     dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
619     status = dev[0].get_status()
620     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
621         raise Exception("Not fully connected")
622     if status['ssid'] != "wps-open":
623         raise Exception("Unexpected SSID")
624     if status['key_mgmt'] != 'NONE':
625         raise Exception("Unexpected key_mgmt")
626
627 def test_ap_wps_reg_config_ext_processing(dev, apdev):
628     """WPS registrar configuring an AP with external config processing"""
629     ssid = "test-wps-init-ap-pin"
630     appin = "12345670"
631     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
632                "wps_cred_processing": "1", "ap_pin": appin}
633     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
634     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
635     new_ssid = "wps-new-ssid"
636     new_passphrase = "1234567890"
637     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
638                    new_passphrase, no_wait=True)
639     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
640     if ev is None:
641         raise Exception("WPS registrar operation timed out")
642     ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
643     if ev is None:
644         raise Exception("WPS configuration timed out")
645     if "1026" not in ev:
646         raise Exception("AP Settings missing from event")
647     hapd.request("SET wps_cred_processing 0")
648     if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
649         raise Exception("WPS_CONFIG command failed")
650     dev[0].wait_connected(timeout=15)
651
652 def test_ap_wps_reg_config_tkip(dev, apdev):
653     """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
654     skip_with_fips(dev[0])
655     ssid = "test-wps-init-ap"
656     appin = "12345670"
657     hostapd.add_ap(apdev[0]['ifname'],
658                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
659                      "ap_pin": appin})
660     logger.info("WPS configuration step")
661     dev[0].request("SET wps_version_number 0x10")
662     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
663     dev[0].dump_monitor()
664     new_ssid = "wps-new-ssid-with-tkip"
665     new_passphrase = "1234567890"
666     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
667                    new_passphrase)
668     logger.info("Re-connect to verify WPA2 mixed mode")
669     dev[0].request("DISCONNECT")
670     id = 0
671     dev[0].set_network(id, "pairwise", "CCMP")
672     dev[0].set_network(id, "proto", "RSN")
673     dev[0].connect_network(id)
674     status = dev[0].get_status()
675     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
676         raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
677     if status['ssid'] != new_ssid:
678         raise Exception("Unexpected SSID")
679     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
680         raise Exception("Unexpected encryption configuration")
681     if status['key_mgmt'] != 'WPA2-PSK':
682         raise Exception("Unexpected key_mgmt")
683
684 def test_ap_wps_setup_locked(dev, apdev):
685     """WPS registrar locking up AP setup on AP PIN failures"""
686     ssid = "test-wps-incorrect-ap-pin"
687     appin = "12345670"
688     hostapd.add_ap(apdev[0]['ifname'],
689                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
690                      "wpa_passphrase": "12345678", "wpa": "2",
691                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
692                      "ap_pin": appin})
693     new_ssid = "wps-new-ssid-test"
694     new_passphrase = "1234567890"
695
696     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
697     ap_setup_locked=False
698     for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
699         dev[0].dump_monitor()
700         logger.info("Try incorrect AP PIN - attempt " + pin)
701         dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
702                        "CCMP", new_passphrase, no_wait=True)
703         ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
704         if ev is None:
705             raise Exception("Timeout on receiving WPS operation failure event")
706         if "CTRL-EVENT-CONNECTED" in ev:
707             raise Exception("Unexpected connection")
708         if "config_error=15" in ev:
709             logger.info("AP Setup Locked")
710             ap_setup_locked=True
711         elif "config_error=18" not in ev:
712             raise Exception("config_error=18 not reported")
713         dev[0].wait_disconnected(timeout=10)
714         time.sleep(0.1)
715     if not ap_setup_locked:
716         raise Exception("AP setup was not locked")
717     dev[0].request("WPS_CANCEL")
718     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
719                         only_new=True)
720     bss = dev[0].get_bss(apdev[0]['bssid'])
721     if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
722         logger.info("BSS: " + str(bss))
723         raise Exception("AP Setup Locked not indicated in scan results")
724
725     hapd = hostapd.Hostapd(apdev[0]['ifname'])
726     status = hapd.request("WPS_GET_STATUS")
727     if "Last WPS result: Failed" not in status:
728         raise Exception("WPS failure result not shown correctly")
729     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
730         raise Exception("Peer address not shown correctly")
731
732     time.sleep(0.5)
733     dev[0].dump_monitor()
734     logger.info("WPS provisioning step")
735     pin = dev[0].wps_read_pin()
736     hapd = hostapd.Hostapd(apdev[0]['ifname'])
737     hapd.request("WPS_PIN any " + pin)
738     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
739     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
740     if ev is None:
741         raise Exception("WPS success was not reported")
742     dev[0].wait_connected(timeout=30)
743
744     appin = hapd.request("WPS_AP_PIN random")
745     if "FAIL" in appin:
746         raise Exception("Could not generate random AP PIN")
747     ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
748     if ev is None:
749         raise Exception("Failed to unlock AP PIN")
750
751 def test_ap_wps_setup_locked_timeout(dev, apdev):
752     """WPS re-enabling AP PIN after timeout"""
753     ssid = "test-wps-incorrect-ap-pin"
754     appin = "12345670"
755     hostapd.add_ap(apdev[0]['ifname'],
756                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
757                      "wpa_passphrase": "12345678", "wpa": "2",
758                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
759                      "ap_pin": appin})
760     new_ssid = "wps-new-ssid-test"
761     new_passphrase = "1234567890"
762
763     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
764     ap_setup_locked=False
765     for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
766         dev[0].dump_monitor()
767         logger.info("Try incorrect AP PIN - attempt " + pin)
768         dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
769                        "CCMP", new_passphrase, no_wait=True)
770         ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
771         if ev is None:
772             raise Exception("Timeout on receiving WPS operation failure event")
773         if "CTRL-EVENT-CONNECTED" in ev:
774             raise Exception("Unexpected connection")
775         if "config_error=15" in ev:
776             logger.info("AP Setup Locked")
777             ap_setup_locked=True
778             break
779         elif "config_error=18" not in ev:
780             raise Exception("config_error=18 not reported")
781         dev[0].wait_disconnected(timeout=10)
782         time.sleep(0.1)
783     if not ap_setup_locked:
784         raise Exception("AP setup was not locked")
785     hapd = hostapd.Hostapd(apdev[0]['ifname'])
786     ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
787     if ev is None:
788         raise Exception("AP PIN did not get unlocked on 60 second timeout")
789
790 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
791     """WPS PBC session overlap with two active APs"""
792     hostapd.add_ap(apdev[0]['ifname'],
793                    { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
794                      "wpa_passphrase": "12345678", "wpa": "2",
795                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
796                      "wps_independent": "1"})
797     hostapd.add_ap(apdev[1]['ifname'],
798                    { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
799                      "wpa_passphrase": "123456789", "wpa": "2",
800                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
801                      "wps_independent": "1"})
802     hapd = hostapd.Hostapd(apdev[0]['ifname'])
803     hapd.request("WPS_PBC")
804     hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
805     hapd2.request("WPS_PBC")
806     logger.info("WPS provisioning step")
807     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
808     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
809     dev[0].request("WPS_PBC")
810     ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
811     if ev is None:
812         raise Exception("PBC session overlap not detected")
813     hapd.request("DISABLE")
814     hapd2.request("DISABLE")
815     dev[0].flush_scan_cache()
816
817 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
818     """WPS PBC session overlap with two active STAs"""
819     ssid = "test-wps-pbc-overlap"
820     hostapd.add_ap(apdev[0]['ifname'],
821                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
822                      "wpa_passphrase": "12345678", "wpa": "2",
823                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
824     hapd = hostapd.Hostapd(apdev[0]['ifname'])
825     logger.info("WPS provisioning step")
826     hapd.request("WPS_PBC")
827     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
828     dev[0].dump_monitor()
829     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
830     dev[1].dump_monitor()
831     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
832     dev[1].request("WPS_PBC " + apdev[0]['bssid'])
833     ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
834     if ev is None:
835         raise Exception("PBC session overlap not detected (dev0)")
836     if "config_error=12" not in ev:
837         raise Exception("PBC session overlap not correctly reported (dev0)")
838     dev[0].request("WPS_CANCEL")
839     dev[0].request("DISCONNECT")
840     ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
841     if ev is None:
842         raise Exception("PBC session overlap not detected (dev1)")
843     if "config_error=12" not in ev:
844         raise Exception("PBC session overlap not correctly reported (dev1)")
845     dev[1].request("WPS_CANCEL")
846     dev[1].request("DISCONNECT")
847     hapd.request("WPS_CANCEL")
848     ret = hapd.request("WPS_PBC")
849     if "FAIL" not in ret:
850         raise Exception("PBC mode allowed to be started while PBC overlap still active")
851     hapd.request("DISABLE")
852     dev[0].flush_scan_cache()
853     dev[1].flush_scan_cache()
854
855 def test_ap_wps_cancel(dev, apdev):
856     """WPS AP cancelling enabled config method"""
857     ssid = "test-wps-ap-cancel"
858     hostapd.add_ap(apdev[0]['ifname'],
859                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
860                      "wpa_passphrase": "12345678", "wpa": "2",
861                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
862     bssid = apdev[0]['bssid']
863     hapd = hostapd.Hostapd(apdev[0]['ifname'])
864
865     logger.info("Verify PBC enable/cancel")
866     hapd.request("WPS_PBC")
867     dev[0].scan(freq="2412")
868     dev[0].scan(freq="2412")
869     bss = dev[0].get_bss(apdev[0]['bssid'])
870     if "[WPS-PBC]" not in bss['flags']:
871         raise Exception("WPS-PBC flag missing")
872     if "FAIL" in hapd.request("WPS_CANCEL"):
873         raise Exception("WPS_CANCEL failed")
874     dev[0].scan(freq="2412")
875     dev[0].scan(freq="2412")
876     bss = dev[0].get_bss(apdev[0]['bssid'])
877     if "[WPS-PBC]" in bss['flags']:
878         raise Exception("WPS-PBC flag not cleared")
879
880     logger.info("Verify PIN enable/cancel")
881     hapd.request("WPS_PIN any 12345670")
882     dev[0].scan(freq="2412")
883     dev[0].scan(freq="2412")
884     bss = dev[0].get_bss(apdev[0]['bssid'])
885     if "[WPS-AUTH]" not in bss['flags']:
886         raise Exception("WPS-AUTH flag missing")
887     if "FAIL" in hapd.request("WPS_CANCEL"):
888         raise Exception("WPS_CANCEL failed")
889     dev[0].scan(freq="2412")
890     dev[0].scan(freq="2412")
891     bss = dev[0].get_bss(apdev[0]['bssid'])
892     if "[WPS-AUTH]" in bss['flags']:
893         raise Exception("WPS-AUTH flag not cleared")
894
895 def test_ap_wps_er_add_enrollee(dev, apdev):
896     """WPS ER configuring AP and adding a new enrollee using PIN"""
897     try:
898         _test_ap_wps_er_add_enrollee(dev, apdev)
899     finally:
900         dev[0].request("WPS_ER_STOP")
901
902 def _test_ap_wps_er_add_enrollee(dev, apdev):
903     ssid = "wps-er-add-enrollee"
904     ap_pin = "12345670"
905     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
906     hostapd.add_ap(apdev[0]['ifname'],
907                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
908                      "device_name": "Wireless AP", "manufacturer": "Company",
909                      "model_name": "WAP", "model_number": "123",
910                      "serial_number": "12345", "device_type": "6-0050F204-1",
911                      "os_version": "01020300",
912                      'friendly_name': "WPS AP - <>&'\" - TEST",
913                      "config_methods": "label push_button",
914                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
915     logger.info("WPS configuration step")
916     new_passphrase = "1234567890"
917     dev[0].dump_monitor()
918     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
919     dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
920                    new_passphrase)
921     status = dev[0].get_status()
922     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
923         raise Exception("Not fully connected")
924     if status['ssid'] != ssid:
925         raise Exception("Unexpected SSID")
926     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
927         raise Exception("Unexpected encryption configuration")
928     if status['key_mgmt'] != 'WPA2-PSK':
929         raise Exception("Unexpected key_mgmt")
930
931     logger.info("Start ER")
932     dev[0].request("WPS_ER_START ifname=lo")
933     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
934     if ev is None:
935         raise Exception("AP discovery timed out")
936     if ap_uuid not in ev:
937         raise Exception("Expected AP UUID not found")
938     if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
939         raise Exception("Expected friendly name not found")
940
941     logger.info("Learn AP configuration through UPnP")
942     dev[0].dump_monitor()
943     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
944     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
945     if ev is None:
946         raise Exception("AP learn timed out")
947     if ap_uuid not in ev:
948         raise Exception("Expected AP UUID not in settings")
949     if "ssid=" + ssid not in ev:
950         raise Exception("Expected SSID not in settings")
951     if "key=" + new_passphrase not in ev:
952         raise Exception("Expected passphrase not in settings")
953     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
954     if ev is None:
955         raise Exception("WPS-FAIL after AP learn timed out")
956     time.sleep(0.1)
957
958     logger.info("Add Enrollee using ER")
959     pin = dev[1].wps_read_pin()
960     dev[0].dump_monitor()
961     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
962     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
963     dev[1].dump_monitor()
964     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
965     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
966     if ev is None:
967         raise Exception("Enrollee did not report success")
968     dev[1].wait_connected(timeout=15)
969     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
970     if ev is None:
971         raise Exception("WPS ER did not report success")
972     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
973
974     logger.info("Add a specific Enrollee using ER")
975     pin = dev[2].wps_read_pin()
976     addr2 = dev[2].p2p_interface_addr()
977     dev[0].dump_monitor()
978     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
979     dev[2].dump_monitor()
980     dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
981     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
982     if ev is None:
983         raise Exception("Enrollee not seen")
984     if addr2 not in ev:
985         raise Exception("Unexpected Enrollee MAC address")
986     dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
987     dev[2].wait_connected(timeout=30)
988     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
989     if ev is None:
990         raise Exception("WPS ER did not report success")
991
992     logger.info("Verify registrar selection behavior")
993     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
994     dev[1].request("DISCONNECT")
995     dev[1].wait_disconnected(timeout=10)
996     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
997     dev[1].scan(freq="2412")
998     bss = dev[1].get_bss(apdev[0]['bssid'])
999     if "[WPS-AUTH]" not in bss['flags']:
1000         # It is possible for scan to miss an update especially when running
1001         # tests under load with multiple VMs, so allow another attempt.
1002         dev[1].scan(freq="2412")
1003         bss = dev[1].get_bss(apdev[0]['bssid'])
1004         if "[WPS-AUTH]" not in bss['flags']:
1005             raise Exception("WPS-AUTH flag missing")
1006
1007     logger.info("Stop ER")
1008     dev[0].dump_monitor()
1009     dev[0].request("WPS_ER_STOP")
1010     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1011     if ev is None:
1012         raise Exception("WPS ER unsubscription timed out")
1013     # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
1014     # a bit before verifying that the scan results have changed.
1015     time.sleep(0.2)
1016
1017     for i in range(0, 10):
1018         dev[1].request("BSS_FLUSH 0")
1019         dev[1].scan(freq="2412", only_new=True)
1020         bss = dev[1].get_bss(apdev[0]['bssid'])
1021         if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1022             break
1023         logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1024         time.sleep(0.1)
1025     if "[WPS-AUTH]" in bss['flags']:
1026         raise Exception("WPS-AUTH flag not removed")
1027
1028 def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1029     """WPS ER adding a new enrollee identified by UUID"""
1030     try:
1031         _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1032     finally:
1033         dev[0].request("WPS_ER_STOP")
1034
1035 def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1036     ssid = "wps-er-add-enrollee"
1037     ap_pin = "12345670"
1038     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1039     hostapd.add_ap(apdev[0]['ifname'],
1040                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1041                      "wpa_passphrase": "12345678", "wpa": "2",
1042                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1043                      "device_name": "Wireless AP", "manufacturer": "Company",
1044                      "model_name": "WAP", "model_number": "123",
1045                      "serial_number": "12345", "device_type": "6-0050F204-1",
1046                      "os_version": "01020300",
1047                      "config_methods": "label push_button",
1048                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1049     logger.info("WPS configuration step")
1050     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1051     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1052
1053     logger.info("Start ER")
1054     dev[0].request("WPS_ER_START ifname=lo")
1055     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1056     if ev is None:
1057         raise Exception("AP discovery timed out")
1058     if ap_uuid not in ev:
1059         raise Exception("Expected AP UUID not found")
1060
1061     logger.info("Learn AP configuration through UPnP")
1062     dev[0].dump_monitor()
1063     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1064     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1065     if ev is None:
1066         raise Exception("AP learn timed out")
1067     if ap_uuid not in ev:
1068         raise Exception("Expected AP UUID not in settings")
1069     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1070     if ev is None:
1071         raise Exception("WPS-FAIL after AP learn timed out")
1072     time.sleep(0.1)
1073
1074     logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1075     addr1 = dev[1].p2p_interface_addr()
1076     dev[0].dump_monitor()
1077     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1078     dev[1].dump_monitor()
1079     dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1080     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1081     if ev is None:
1082         raise Exception("Enrollee not seen")
1083     if addr1 not in ev:
1084         raise Exception("Unexpected Enrollee MAC address")
1085     uuid = ev.split(' ')[1]
1086     dev[0].request("WPS_ER_PBC " + uuid)
1087     dev[1].wait_connected(timeout=30)
1088     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1089     if ev is None:
1090         raise Exception("WPS ER did not report success")
1091
1092     logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1093     pin = dev[2].wps_read_pin()
1094     addr2 = dev[2].p2p_interface_addr()
1095     dev[0].dump_monitor()
1096     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1097     dev[2].dump_monitor()
1098     dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1099     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1100     if ev is None:
1101         raise Exception("Enrollee not seen")
1102     if addr2 not in ev:
1103         raise Exception("Unexpected Enrollee MAC address")
1104     uuid = ev.split(' ')[1]
1105     dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1106     dev[2].wait_connected(timeout=30)
1107     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1108     if ev is None:
1109         raise Exception("WPS ER did not report success")
1110
1111     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1112     if ev is None:
1113         raise Exception("No Enrollee STA entry timeout seen")
1114
1115     logger.info("Stop ER")
1116     dev[0].dump_monitor()
1117     dev[0].request("WPS_ER_STOP")
1118
1119 def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1120     """Multiple WPS ERs adding a new enrollee using PIN"""
1121     try:
1122         _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1123     finally:
1124         dev[0].request("WPS_ER_STOP")
1125
1126 def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1127     ssid = "wps-er-add-enrollee"
1128     ap_pin = "12345670"
1129     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1130     hostapd.add_ap(apdev[0]['ifname'],
1131                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1132                      "wpa_passphrase": "12345678", "wpa": "2",
1133                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1134                      "device_name": "Wireless AP", "manufacturer": "Company",
1135                      "model_name": "WAP", "model_number": "123",
1136                      "serial_number": "12345", "device_type": "6-0050F204-1",
1137                      "os_version": "01020300",
1138                      'friendly_name': "WPS AP",
1139                      "config_methods": "label push_button",
1140                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1141
1142     for i in range(2):
1143         dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1144         dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
1145         dev[i].request("WPS_ER_START ifname=lo")
1146     for i in range(2):
1147         ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1148         if ev is None:
1149             raise Exception("AP discovery timed out")
1150         dev[i].dump_monitor()
1151         dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1152         ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1153         if ev is None:
1154             raise Exception("AP learn timed out")
1155         ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1156         if ev is None:
1157             raise Exception("WPS-FAIL after AP learn timed out")
1158
1159     time.sleep(0.1)
1160
1161     pin = dev[2].wps_read_pin()
1162     addr = dev[2].own_addr()
1163     dev[0].dump_monitor()
1164     dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1165     dev[1].dump_monitor()
1166     dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1167
1168     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1169     dev[2].dump_monitor()
1170     dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1171     ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1172     if ev is None:
1173         raise Exception("Enrollee did not report success")
1174     dev[2].wait_connected(timeout=15)
1175
1176 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1177     """WPS ER connected to AP and adding a new enrollee using PBC"""
1178     try:
1179         _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1180     finally:
1181         dev[0].request("WPS_ER_STOP")
1182
1183 def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1184     ssid = "wps-er-add-enrollee-pbc"
1185     ap_pin = "12345670"
1186     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1187     hostapd.add_ap(apdev[0]['ifname'],
1188                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1189                      "wpa_passphrase": "12345678", "wpa": "2",
1190                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1191                      "device_name": "Wireless AP", "manufacturer": "Company",
1192                      "model_name": "WAP", "model_number": "123",
1193                      "serial_number": "12345", "device_type": "6-0050F204-1",
1194                      "os_version": "01020300",
1195                      "config_methods": "label push_button",
1196                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1197     logger.info("Learn AP configuration")
1198     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1199     dev[0].dump_monitor()
1200     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1201     status = dev[0].get_status()
1202     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1203         raise Exception("Not fully connected")
1204
1205     logger.info("Start ER")
1206     dev[0].request("WPS_ER_START ifname=lo")
1207     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1208     if ev is None:
1209         raise Exception("AP discovery timed out")
1210     if ap_uuid not in ev:
1211         raise Exception("Expected AP UUID not found")
1212
1213     enrollee = dev[1].p2p_interface_addr()
1214
1215     if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1216         raise Exception("Unknown UUID not reported")
1217
1218     logger.info("Add Enrollee using ER and PBC")
1219     dev[0].dump_monitor()
1220     dev[1].dump_monitor()
1221     dev[1].request("WPS_PBC")
1222
1223     for i in range(0, 2):
1224         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1225         if ev is None:
1226             raise Exception("Enrollee discovery timed out")
1227         if enrollee in ev:
1228             break
1229         if i == 1:
1230             raise Exception("Expected Enrollee not found")
1231     if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1232         raise Exception("Unknown UUID not reported")
1233     logger.info("Use learned network configuration on ER")
1234     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1235     if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1236         raise Exception("WPS_ER_PBC failed")
1237
1238     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1239     if ev is None:
1240         raise Exception("Enrollee did not report success")
1241     dev[1].wait_connected(timeout=15)
1242     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1243     if ev is None:
1244         raise Exception("WPS ER did not report success")
1245     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1246
1247 def test_ap_wps_er_pbc_overlap(dev, apdev):
1248     """WPS ER connected to AP and PBC session overlap"""
1249     try:
1250         _test_ap_wps_er_pbc_overlap(dev, apdev)
1251     finally:
1252         dev[0].request("WPS_ER_STOP")
1253
1254 def _test_ap_wps_er_pbc_overlap(dev, apdev):
1255     ssid = "wps-er-add-enrollee-pbc"
1256     ap_pin = "12345670"
1257     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1258     hostapd.add_ap(apdev[0]['ifname'],
1259                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1260                      "wpa_passphrase": "12345678", "wpa": "2",
1261                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1262                      "device_name": "Wireless AP", "manufacturer": "Company",
1263                      "model_name": "WAP", "model_number": "123",
1264                      "serial_number": "12345", "device_type": "6-0050F204-1",
1265                      "os_version": "01020300",
1266                      "config_methods": "label push_button",
1267                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1268     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1269     dev[0].dump_monitor()
1270     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1271
1272     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1273     dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1274     # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1275     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1276
1277     dev[0].dump_monitor()
1278     dev[0].request("WPS_ER_START ifname=lo")
1279
1280     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1281     if ev is None:
1282         raise Exception("AP discovery timed out")
1283     if ap_uuid not in ev:
1284         raise Exception("Expected AP UUID not found")
1285
1286     # verify BSSID selection of the AP instead of UUID
1287     if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1288         raise Exception("Could not select AP based on BSSID")
1289
1290     dev[0].dump_monitor()
1291     dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1292     dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1293     ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1294     if ev is None:
1295         raise Exception("PBC scan failed")
1296     ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1297     if ev is None:
1298         raise Exception("PBC scan failed")
1299     found1 = False
1300     found2 = False
1301     addr1 = dev[1].own_addr()
1302     addr2 = dev[2].own_addr()
1303     for i in range(3):
1304         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1305         if ev is None:
1306             raise Exception("Enrollee discovery timed out")
1307         if addr1 in ev:
1308             found1 = True
1309             if found2:
1310                 break
1311         if addr2 in ev:
1312             found2 = True
1313             if found1:
1314                 break
1315     if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1316         raise Exception("PBC overlap not reported")
1317     dev[1].request("WPS_CANCEL")
1318     dev[2].request("WPS_CANCEL")
1319     if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1320         raise Exception("Invalid WPS_ER_PBC accepted")
1321
1322 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1323     """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
1324     try:
1325         _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1326     finally:
1327         dev[0].request("WPS_ER_STOP")
1328
1329 def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1330     ssid = "wps-er-add-enrollee-pbc"
1331     ap_pin = "12345670"
1332     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1333     hostapd.add_ap(apdev[0]['ifname'],
1334                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1335                      "wpa_passphrase": "12345678", "wpa": "2",
1336                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1337                      "device_name": "Wireless AP", "manufacturer": "Company",
1338                      "model_name": "WAP", "model_number": "123",
1339                      "serial_number": "12345", "device_type": "6-0050F204-1",
1340                      "os_version": "01020300",
1341                      "config_methods": "label push_button",
1342                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1343     logger.info("Learn AP configuration")
1344     dev[0].request("SET wps_version_number 0x10")
1345     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1346     dev[0].dump_monitor()
1347     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1348     status = dev[0].get_status()
1349     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1350         raise Exception("Not fully connected")
1351
1352     logger.info("Start ER")
1353     dev[0].request("WPS_ER_START ifname=lo")
1354     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1355     if ev is None:
1356         raise Exception("AP discovery timed out")
1357     if ap_uuid not in ev:
1358         raise Exception("Expected AP UUID not found")
1359
1360     logger.info("Use learned network configuration on ER")
1361     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1362
1363     logger.info("Add Enrollee using ER and PIN")
1364     enrollee = dev[1].p2p_interface_addr()
1365     pin = dev[1].wps_read_pin()
1366     dev[0].dump_monitor()
1367     dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1368     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1369     dev[1].dump_monitor()
1370     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1371     dev[1].wait_connected(timeout=30)
1372     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1373     if ev is None:
1374         raise Exception("WPS ER did not report success")
1375
1376 def test_ap_wps_er_config_ap(dev, apdev):
1377     """WPS ER configuring AP over UPnP"""
1378     try:
1379         _test_ap_wps_er_config_ap(dev, apdev)
1380     finally:
1381         dev[0].request("WPS_ER_STOP")
1382
1383 def _test_ap_wps_er_config_ap(dev, apdev):
1384     ssid = "wps-er-ap-config"
1385     ap_pin = "12345670"
1386     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1387     hostapd.add_ap(apdev[0]['ifname'],
1388                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1389                      "wpa_passphrase": "12345678", "wpa": "2",
1390                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1391                      "device_name": "Wireless AP", "manufacturer": "Company",
1392                      "model_name": "WAP", "model_number": "123",
1393                      "serial_number": "12345", "device_type": "6-0050F204-1",
1394                      "os_version": "01020300",
1395                      "config_methods": "label push_button",
1396                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1397
1398     logger.info("Connect ER to the AP")
1399     dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1400
1401     logger.info("WPS configuration step")
1402     dev[0].request("WPS_ER_START ifname=lo")
1403     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1404     if ev is None:
1405         raise Exception("AP discovery timed out")
1406     if ap_uuid not in ev:
1407         raise Exception("Expected AP UUID not found")
1408     new_passphrase = "1234567890"
1409     dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1410                    ssid.encode("hex") + " WPA2PSK CCMP " +
1411                    new_passphrase.encode("hex"))
1412     ev = dev[0].wait_event(["WPS-SUCCESS"])
1413     if ev is None:
1414         raise Exception("WPS ER configuration operation timed out")
1415     dev[0].wait_disconnected(timeout=10)
1416     dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1417
1418     logger.info("WPS ER restart")
1419     dev[0].request("WPS_ER_START")
1420     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1421     if ev is None:
1422         raise Exception("AP discovery timed out on ER restart")
1423     if ap_uuid not in ev:
1424         raise Exception("Expected AP UUID not found on ER restart")
1425     if "OK" not in dev[0].request("WPS_ER_STOP"):
1426         raise Exception("WPS_ER_STOP failed")
1427     if "OK" not in dev[0].request("WPS_ER_STOP"):
1428         raise Exception("WPS_ER_STOP failed")
1429
1430 def test_ap_wps_er_cache_ap_settings(dev, apdev):
1431     """WPS ER caching AP settings"""
1432     try:
1433         _test_ap_wps_er_cache_ap_settings(dev, apdev)
1434     finally:
1435         dev[0].request("WPS_ER_STOP")
1436
1437 def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1438     ssid = "wps-er-add-enrollee"
1439     ap_pin = "12345670"
1440     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1441     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1442                "wpa_passphrase": "12345678", "wpa": "2",
1443                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1444                "device_name": "Wireless AP", "manufacturer": "Company",
1445                "model_name": "WAP", "model_number": "123",
1446                "serial_number": "12345", "device_type": "6-0050F204-1",
1447                "os_version": "01020300",
1448                "config_methods": "label push_button",
1449                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1450     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1451     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1452     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1453     id = int(dev[0].list_networks()[0]['id'])
1454     dev[0].set_network(id, "scan_freq", "2412")
1455
1456     dev[0].request("WPS_ER_START ifname=lo")
1457     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1458     if ev is None:
1459         raise Exception("AP discovery timed out")
1460     if ap_uuid not in ev:
1461         raise Exception("Expected AP UUID not found")
1462
1463     dev[0].dump_monitor()
1464     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1465     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1466     if ev is None:
1467         raise Exception("AP learn timed out")
1468     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1469     if ev is None:
1470         raise Exception("WPS-FAIL after AP learn timed out")
1471     time.sleep(0.1)
1472
1473     hapd.disable()
1474
1475     for i in range(2):
1476         ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1477                                  "CTRL-EVENT-DISCONNECTED" ],
1478                                timeout=15)
1479         if ev is None:
1480             raise Exception("AP removal or disconnection timed out")
1481
1482     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1483     for i in range(2):
1484         ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1485                                timeout=15)
1486         if ev is None:
1487             raise Exception("AP discovery or connection timed out")
1488
1489     pin = dev[1].wps_read_pin()
1490     dev[0].dump_monitor()
1491     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1492
1493     time.sleep(0.2)
1494
1495     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1496     dev[1].dump_monitor()
1497     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1498     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1499     if ev is None:
1500         raise Exception("Enrollee did not report success")
1501     dev[1].wait_connected(timeout=15)
1502     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1503     if ev is None:
1504         raise Exception("WPS ER did not report success")
1505
1506     dev[0].dump_monitor()
1507     dev[0].request("WPS_ER_STOP")
1508
1509 def test_ap_wps_fragmentation(dev, apdev):
1510     """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1511     ssid = "test-wps-fragmentation"
1512     appin = "12345670"
1513     hostapd.add_ap(apdev[0]['ifname'],
1514                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1515                      "wpa_passphrase": "12345678", "wpa": "3",
1516                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1517                      "wpa_pairwise": "TKIP", "ap_pin": appin,
1518                      "fragment_size": "50" })
1519     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1520     logger.info("WPS provisioning step (PBC)")
1521     hapd.request("WPS_PBC")
1522     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1523     dev[0].dump_monitor()
1524     dev[0].request("SET wps_fragment_size 50")
1525     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1526     dev[0].wait_connected(timeout=30)
1527     status = dev[0].get_status()
1528     if status['wpa_state'] != 'COMPLETED':
1529         raise Exception("Not fully connected")
1530     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1531         raise Exception("Unexpected encryption configuration")
1532     if status['key_mgmt'] != 'WPA2-PSK':
1533         raise Exception("Unexpected key_mgmt")
1534
1535     logger.info("WPS provisioning step (PIN)")
1536     pin = dev[1].wps_read_pin()
1537     hapd.request("WPS_PIN any " + pin)
1538     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1539     dev[1].request("SET wps_fragment_size 50")
1540     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1541     dev[1].wait_connected(timeout=30)
1542     status = dev[1].get_status()
1543     if status['wpa_state'] != 'COMPLETED':
1544         raise Exception("Not fully connected")
1545     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1546         raise Exception("Unexpected encryption configuration")
1547     if status['key_mgmt'] != 'WPA2-PSK':
1548         raise Exception("Unexpected key_mgmt")
1549
1550     logger.info("WPS connection as registrar")
1551     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1552     dev[2].request("SET wps_fragment_size 50")
1553     dev[2].wps_reg(apdev[0]['bssid'], appin)
1554     status = dev[2].get_status()
1555     if status['wpa_state'] != 'COMPLETED':
1556         raise Exception("Not fully connected")
1557     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1558         raise Exception("Unexpected encryption configuration")
1559     if status['key_mgmt'] != 'WPA2-PSK':
1560         raise Exception("Unexpected key_mgmt")
1561
1562 def test_ap_wps_new_version_sta(dev, apdev):
1563     """WPS compatibility with new version number on the station"""
1564     ssid = "test-wps-ver"
1565     hostapd.add_ap(apdev[0]['ifname'],
1566                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1567                      "wpa_passphrase": "12345678", "wpa": "2",
1568                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1569     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1570     logger.info("WPS provisioning step")
1571     hapd.request("WPS_PBC")
1572     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1573     dev[0].dump_monitor()
1574     dev[0].request("SET wps_version_number 0x43")
1575     dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
1576     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1577     dev[0].wait_connected(timeout=30)
1578
1579 def test_ap_wps_new_version_ap(dev, apdev):
1580     """WPS compatibility with new version number on the AP"""
1581     ssid = "test-wps-ver"
1582     hostapd.add_ap(apdev[0]['ifname'],
1583                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1584                      "wpa_passphrase": "12345678", "wpa": "2",
1585                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1586     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1587     logger.info("WPS provisioning step")
1588     if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1589         raise Exception("Failed to enable test functionality")
1590     hapd.request("WPS_PBC")
1591     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1592     dev[0].dump_monitor()
1593     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1594     dev[0].wait_connected(timeout=30)
1595     hapd.request("SET wps_version_number 0x20")
1596
1597 def test_ap_wps_check_pin(dev, apdev):
1598     """Verify PIN checking through control interface"""
1599     hostapd.add_ap(apdev[0]['ifname'],
1600                    { "ssid": "wps", "eap_server": "1", "wps_state": "2",
1601                      "wpa_passphrase": "12345678", "wpa": "2",
1602                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1603     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1604     for t in [ ("12345670", "12345670"),
1605                ("12345678", "FAIL-CHECKSUM"),
1606                ("12345", "FAIL"),
1607                ("123456789", "FAIL"),
1608                ("1234-5670", "12345670"),
1609                ("1234 5670", "12345670"),
1610                ("1-2.3:4 5670", "12345670") ]:
1611         res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1612         res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1613         if res != res2:
1614             raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
1615         if res != t[1]:
1616             raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
1617
1618     if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
1619         raise Exception("Unexpected WPS_CHECK_PIN success")
1620     if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
1621         raise Exception("Unexpected WPS_CHECK_PIN success")
1622
1623     for i in range(0, 10):
1624         pin = dev[0].request("WPS_PIN get")
1625         rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
1626         if pin != rpin:
1627             raise Exception("Random PIN validation failed for " + pin)
1628
1629 def test_ap_wps_wep_config(dev, apdev):
1630     """WPS 2.0 AP rejecting WEP configuration"""
1631     ssid = "test-wps-config"
1632     appin = "12345670"
1633     hostapd.add_ap(apdev[0]['ifname'],
1634                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1635                      "ap_pin": appin})
1636     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1637     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1638     dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
1639                    "hello", no_wait=True)
1640     ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
1641     if ev is None:
1642         raise Exception("WPS-FAIL timed out")
1643     if "reason=2" not in ev:
1644         raise Exception("Unexpected reason code in WPS-FAIL")
1645     status = hapd.request("WPS_GET_STATUS")
1646     if "Last WPS result: Failed" not in status:
1647         raise Exception("WPS failure result not shown correctly")
1648     if "Failure Reason: WEP Prohibited" not in status:
1649         raise Exception("Failure reason not reported correctly")
1650     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
1651         raise Exception("Peer address not shown correctly")
1652
1653 def test_ap_wps_wep_enroll(dev, apdev):
1654     """WPS 2.0 STA rejecting WEP configuration"""
1655     ssid = "test-wps-wep"
1656     hostapd.add_ap(apdev[0]['ifname'],
1657                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1658                      "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
1659     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1660     hapd.request("WPS_PBC")
1661     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1662     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1663     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1664     if ev is None:
1665         raise Exception("WPS-FAIL event timed out")
1666     if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
1667         raise Exception("Unexpected WPS-FAIL event: " + ev)
1668
1669 def test_ap_wps_ie_fragmentation(dev, apdev):
1670     """WPS AP using fragmented WPS IE"""
1671     ssid = "test-wps-ie-fragmentation"
1672     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1673                "wpa_passphrase": "12345678", "wpa": "2",
1674                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1675                "device_name": "1234567890abcdef1234567890abcdef",
1676                "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1677                "model_name": "1234567890abcdef1234567890abcdef",
1678                "model_number": "1234567890abcdef1234567890abcdef",
1679                "serial_number": "1234567890abcdef1234567890abcdef" }
1680     hostapd.add_ap(apdev[0]['ifname'], params)
1681     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1682     hapd.request("WPS_PBC")
1683     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1684     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1685     dev[0].wait_connected(timeout=30)
1686     bss = dev[0].get_bss(apdev[0]['bssid'])
1687     if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1688         logger.info("Device Name not received correctly")
1689         logger.info(bss)
1690         # This can fail if Probe Response frame is missed and Beacon frame was
1691         # used to fill in the BSS entry. This can happen, e.g., during heavy
1692         # load every now and then and is not really an error, so try to
1693         # workaround by runnign another scan.
1694         dev[0].scan(freq="2412", only_new=True)
1695         bss = dev[0].get_bss(apdev[0]['bssid'])
1696         if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1697             logger.info(bss)
1698             raise Exception("Device Name not received correctly")
1699     if len(re.findall("dd..0050f204", bss['ie'])) != 2:
1700         raise Exception("Unexpected number of WPS IEs")
1701
1702 def get_psk(pskfile):
1703     psks = {}
1704     with open(pskfile, "r") as f:
1705         lines = f.read().splitlines()
1706         for l in lines:
1707             if l == "# WPA PSKs":
1708                 continue
1709             (addr,psk) = l.split(' ')
1710             psks[addr] = psk
1711     return psks
1712
1713 def test_ap_wps_per_station_psk(dev, apdev):
1714     """WPS PBC provisioning with per-station PSK"""
1715     addr0 = dev[0].own_addr()
1716     addr1 = dev[1].own_addr()
1717     addr2 = dev[2].own_addr()
1718     ssid = "wps"
1719     appin = "12345670"
1720     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1721     try:
1722         os.remove(pskfile)
1723     except:
1724         pass
1725
1726     try:
1727         with open(pskfile, "w") as f:
1728             f.write("# WPA PSKs\n")
1729
1730         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1731                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1732                    "rsn_pairwise": "CCMP", "ap_pin": appin,
1733                    "wpa_psk_file": pskfile }
1734         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1735
1736         logger.info("First enrollee")
1737         hapd.request("WPS_PBC")
1738         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1739         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1740         dev[0].wait_connected(timeout=30)
1741
1742         logger.info("Second enrollee")
1743         hapd.request("WPS_PBC")
1744         dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1745         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1746         dev[1].wait_connected(timeout=30)
1747
1748         logger.info("External registrar")
1749         dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1750         dev[2].wps_reg(apdev[0]['bssid'], appin)
1751
1752         logger.info("Verifying PSK results")
1753         psks = get_psk(pskfile)
1754         if addr0 not in psks:
1755             raise Exception("No PSK recorded for sta0")
1756         if addr1 not in psks:
1757             raise Exception("No PSK recorded for sta1")
1758         if addr2 not in psks:
1759             raise Exception("No PSK recorded for sta2")
1760         if psks[addr0] == psks[addr1]:
1761             raise Exception("Same PSK recorded for sta0 and sta1")
1762         if psks[addr0] == psks[addr2]:
1763             raise Exception("Same PSK recorded for sta0 and sta2")
1764         if psks[addr1] == psks[addr2]:
1765             raise Exception("Same PSK recorded for sta1 and sta2")
1766
1767         dev[0].request("REMOVE_NETWORK all")
1768         logger.info("Second external registrar")
1769         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1770         dev[0].wps_reg(apdev[0]['bssid'], appin)
1771         psks2 = get_psk(pskfile)
1772         if addr0 not in psks2:
1773             raise Exception("No PSK recorded for sta0(reg)")
1774         if psks[addr0] == psks2[addr0]:
1775             raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
1776     finally:
1777         os.remove(pskfile)
1778
1779 def test_ap_wps_per_station_psk_failure(dev, apdev):
1780     """WPS PBC provisioning with per-station PSK (file not writable)"""
1781     addr0 = dev[0].p2p_dev_addr()
1782     addr1 = dev[1].p2p_dev_addr()
1783     addr2 = dev[2].p2p_dev_addr()
1784     ssid = "wps"
1785     appin = "12345670"
1786     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1787     try:
1788         os.remove(pskfile)
1789     except:
1790         pass
1791
1792     try:
1793         with open(pskfile, "w") as f:
1794             f.write("# WPA PSKs\n")
1795
1796         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1797                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1798                    "rsn_pairwise": "CCMP", "ap_pin": appin,
1799                    "wpa_psk_file": pskfile }
1800         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1801         if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
1802             raise Exception("Failed to set wpa_psk_file")
1803
1804         logger.info("First enrollee")
1805         hapd.request("WPS_PBC")
1806         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1807         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1808         dev[0].wait_connected(timeout=30)
1809
1810         logger.info("Second enrollee")
1811         hapd.request("WPS_PBC")
1812         dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1813         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1814         dev[1].wait_connected(timeout=30)
1815
1816         logger.info("External registrar")
1817         dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1818         dev[2].wps_reg(apdev[0]['bssid'], appin)
1819
1820         logger.info("Verifying PSK results")
1821         psks = get_psk(pskfile)
1822         if len(psks) > 0:
1823             raise Exception("PSK recorded unexpectedly")
1824     finally:
1825         os.remove(pskfile)
1826
1827 def test_ap_wps_pin_request_file(dev, apdev):
1828     """WPS PIN provisioning with configured AP"""
1829     ssid = "wps"
1830     pinfile = "/tmp/ap_wps_pin_request_file.log"
1831     if os.path.exists(pinfile):
1832         os.remove(pinfile)
1833     hostapd.add_ap(apdev[0]['ifname'],
1834                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1835                      "wps_pin_requests": pinfile,
1836                      "wpa_passphrase": "12345678", "wpa": "2",
1837                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1838     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1839     uuid = dev[0].get_status_field("uuid")
1840     pin = dev[0].wps_read_pin()
1841     try:
1842         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1843         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1844         ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
1845         if ev is None:
1846             raise Exception("PIN needed event not shown")
1847         if uuid not in ev:
1848             raise Exception("UUID mismatch")
1849         dev[0].request("WPS_CANCEL")
1850         success = False
1851         with open(pinfile, "r") as f:
1852             lines = f.readlines()
1853             for l in lines:
1854                 if uuid in l:
1855                     success = True
1856                     break
1857         if not success:
1858             raise Exception("PIN request entry not in the log file")
1859     finally:
1860         try:
1861             os.remove(pinfile)
1862         except:
1863             pass
1864
1865 def test_ap_wps_auto_setup_with_config_file(dev, apdev):
1866     """WPS auto-setup with configuration file"""
1867     conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
1868     ifname = apdev[0]['ifname']
1869     try:
1870         with open(conffile, "w") as f:
1871             f.write("driver=nl80211\n")
1872             f.write("hw_mode=g\n")
1873             f.write("channel=1\n")
1874             f.write("ieee80211n=1\n")
1875             f.write("interface=%s\n" % ifname)
1876             f.write("ctrl_interface=/var/run/hostapd\n")
1877             f.write("ssid=wps\n")
1878             f.write("eap_server=1\n")
1879             f.write("wps_state=1\n")
1880         hostapd.add_bss('phy3', ifname, conffile)
1881         hapd = hostapd.Hostapd(ifname)
1882         hapd.request("WPS_PBC")
1883         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1884         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1885         dev[0].wait_connected(timeout=30)
1886         with open(conffile, "r") as f:
1887             lines = f.read().splitlines()
1888             vals = dict()
1889             for l in lines:
1890                 try:
1891                     [name,value] = l.split('=', 1)
1892                     vals[name] = value
1893                 except ValueError, e:
1894                     if "# WPS configuration" in l:
1895                         pass
1896                     else:
1897                         raise Exception("Unexpected configuration line: " + l)
1898         if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
1899             raise Exception("Incorrect configuration: " + str(vals))
1900     finally:
1901         try:
1902             os.remove(conffile)
1903         except:
1904             pass
1905
1906 def test_ap_wps_pbc_timeout(dev, apdev, params):
1907     """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
1908     if not params['long']:
1909         raise HwsimSkip("Skip test case with long duration due to --long not specified")
1910     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1911     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1912
1913     location = ssdp_get_location(ap_uuid)
1914     urls = upnp_get_urls(location)
1915     eventurl = urlparse.urlparse(urls['event_sub_url'])
1916     ctrlurl = urlparse.urlparse(urls['control_url'])
1917
1918     url = urlparse.urlparse(location)
1919     conn = httplib.HTTPConnection(url.netloc)
1920
1921     class WPSERHTTPServer(SocketServer.StreamRequestHandler):
1922         def handle(self):
1923             data = self.rfile.readline().strip()
1924             logger.debug(data)
1925             self.wfile.write(gen_wps_event())
1926
1927     server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
1928     server.timeout = 1
1929
1930     headers = { "callback": '<http://127.0.0.1:12345/event>',
1931                 "NT": "upnp:event",
1932                 "timeout": "Second-1234" }
1933     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1934     resp = conn.getresponse()
1935     if resp.status != 200:
1936         raise Exception("Unexpected HTTP response: %d" % resp.status)
1937     sid = resp.getheader("sid")
1938     logger.debug("Subscription SID " + sid)
1939
1940     msg = '''<?xml version="1.0"?>
1941 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
1942 <s:Body>
1943 <u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
1944 <NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
1945 VFi5hrLk
1946 </NewMessage>
1947 </u:SetSelectedRegistrar>
1948 </s:Body>
1949 </s:Envelope>'''
1950     headers = { "Content-type": 'text/xml; charset="utf-8"' }
1951     headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
1952     conn.request("POST", ctrlurl.path, msg, headers)
1953     resp = conn.getresponse()
1954     if resp.status != 200:
1955         raise Exception("Unexpected HTTP response: %d" % resp.status)
1956
1957     server.handle_request()
1958
1959     logger.info("Start WPS_PBC and wait for PBC walk time expiration")
1960     if "OK" not in dev[0].request("WPS_PBC"):
1961         raise Exception("WPS_PBC failed")
1962
1963     start = os.times()[4]
1964
1965     server.handle_request()
1966     dev[1].request("BSS_FLUSH 0")
1967     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
1968                         only_new=True)
1969     bss = dev[1].get_bss(apdev[0]['bssid'])
1970     logger.debug("BSS: " + str(bss))
1971     if '[WPS-AUTH]' not in bss['flags']:
1972         raise Exception("WPS not indicated authorized")
1973
1974     server.handle_request()
1975
1976     wps_timeout_seen = False
1977
1978     while True:
1979         hapd.dump_monitor()
1980         dev[1].dump_monitor()
1981         if not wps_timeout_seen:
1982             ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
1983             if ev is not None:
1984                 logger.info("PBC timeout seen")
1985                 wps_timeout_seen = True
1986         else:
1987             dev[0].dump_monitor()
1988         now = os.times()[4]
1989         if now - start > 130:
1990             raise Exception("Selected registration information not removed")
1991         dev[1].request("BSS_FLUSH 0")
1992         dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
1993                             only_new=True)
1994         bss = dev[1].get_bss(apdev[0]['bssid'])
1995         logger.debug("BSS: " + str(bss))
1996         if '[WPS-AUTH]' not in bss['flags']:
1997             break
1998         server.handle_request()
1999
2000     server.server_close()
2001
2002     if wps_timeout_seen:
2003         return
2004
2005     now = os.times()[4]
2006     if now < start + 150:
2007         dur = start + 150 - now
2008     else:
2009         dur = 1
2010     logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2011     ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
2012     if ev is None:
2013         raise Exception("WPS-TIMEOUT not reported")
2014
2015 def add_ssdp_ap(ifname, ap_uuid):
2016     ssid = "wps-ssdp"
2017     ap_pin = "12345670"
2018     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2019                "wpa_passphrase": "12345678", "wpa": "2",
2020                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2021                "device_name": "Wireless AP", "manufacturer": "Company",
2022                "model_name": "WAP", "model_number": "123",
2023                "serial_number": "12345", "device_type": "6-0050F204-1",
2024                "os_version": "01020300",
2025                "config_methods": "label push_button",
2026                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2027                "friendly_name": "WPS Access Point",
2028                "manufacturer_url": "http://www.example.com/",
2029                "model_description": "Wireless Access Point",
2030                "model_url": "http://www.example.com/model/",
2031                "upc": "123456789012" }
2032     return hostapd.add_ap(ifname, params)
2033
2034 def ssdp_send(msg, no_recv=False):
2035     socket.setdefaulttimeout(1)
2036     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2037     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2038     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2039     sock.bind(("127.0.0.1", 0))
2040     sock.sendto(msg, ("239.255.255.250", 1900))
2041     if no_recv:
2042         return None
2043     return sock.recv(1000)
2044
2045 def ssdp_send_msearch(st, no_recv=False):
2046     msg = '\r\n'.join([
2047             'M-SEARCH * HTTP/1.1',
2048             'HOST: 239.255.255.250:1900',
2049             'MX: 1',
2050             'MAN: "ssdp:discover"',
2051             'ST: ' + st,
2052             '', ''])
2053     return ssdp_send(msg, no_recv=no_recv)
2054
2055 def test_ap_wps_ssdp_msearch(dev, apdev):
2056     """WPS AP and SSDP M-SEARCH messages"""
2057     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2058     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2059
2060     msg = '\r\n'.join([
2061             'M-SEARCH * HTTP/1.1',
2062             'Host: 239.255.255.250:1900',
2063             'Mx: 1',
2064             'Man: "ssdp:discover"',
2065             'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2066             '', ''])
2067     ssdp_send(msg)
2068
2069     msg = '\r\n'.join([
2070             'M-SEARCH * HTTP/1.1',
2071             'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2072             'mx: \t1\t\t   ',
2073             'man: \t \t "ssdp:discover"   ',
2074             'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2075             '', ''])
2076     ssdp_send(msg)
2077
2078     ssdp_send_msearch("ssdp:all")
2079     ssdp_send_msearch("upnp:rootdevice")
2080     ssdp_send_msearch("uuid:" + ap_uuid)
2081     ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2082     ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
2083
2084     msg = '\r\n'.join([
2085             'M-SEARCH * HTTP/1.1',
2086             'HOST:\t239.255.255.250:1900',
2087             'MAN: "ssdp:discover"',
2088             'MX: 130',
2089             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2090             '', ''])
2091     ssdp_send(msg, no_recv=True)
2092
2093 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2094     """WPS AP and invalid SSDP M-SEARCH messages"""
2095     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2096     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2097
2098     socket.setdefaulttimeout(1)
2099     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2100     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2101     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2102     sock.bind(("127.0.0.1", 0))
2103
2104     logger.debug("Missing MX")
2105     msg = '\r\n'.join([
2106             'M-SEARCH * HTTP/1.1',
2107             'HOST: 239.255.255.250:1900',
2108             'MAN: "ssdp:discover"',
2109             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2110             '', ''])
2111     sock.sendto(msg, ("239.255.255.250", 1900))
2112
2113     logger.debug("Negative MX")
2114     msg = '\r\n'.join([
2115             'M-SEARCH * HTTP/1.1',
2116             'HOST: 239.255.255.250:1900',
2117             'MX: -1',
2118             'MAN: "ssdp:discover"',
2119             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2120             '', ''])
2121     sock.sendto(msg, ("239.255.255.250", 1900))
2122
2123     logger.debug("Invalid MX")
2124     msg = '\r\n'.join([
2125             'M-SEARCH * HTTP/1.1',
2126             'HOST: 239.255.255.250:1900',
2127             'MX; 1',
2128             'MAN: "ssdp:discover"',
2129             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2130             '', ''])
2131     sock.sendto(msg, ("239.255.255.250", 1900))
2132
2133     logger.debug("Missing MAN")
2134     msg = '\r\n'.join([
2135             'M-SEARCH * HTTP/1.1',
2136             'HOST: 239.255.255.250:1900',
2137             'MX: 1',
2138             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2139             '', ''])
2140     sock.sendto(msg, ("239.255.255.250", 1900))
2141
2142     logger.debug("Invalid MAN")
2143     msg = '\r\n'.join([
2144             'M-SEARCH * HTTP/1.1',
2145             'HOST: 239.255.255.250:1900',
2146             'MX: 1',
2147             'MAN: foo',
2148             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2149             '', ''])
2150     sock.sendto(msg, ("239.255.255.250", 1900))
2151     msg = '\r\n'.join([
2152             'M-SEARCH * HTTP/1.1',
2153             'HOST: 239.255.255.250:1900',
2154             'MX: 1',
2155             'MAN; "ssdp:discover"',
2156             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2157             '', ''])
2158     sock.sendto(msg, ("239.255.255.250", 1900))
2159
2160     logger.debug("Missing HOST")
2161     msg = '\r\n'.join([
2162             'M-SEARCH * HTTP/1.1',
2163             'MAN: "ssdp:discover"',
2164             'MX: 1',
2165             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2166             '', ''])
2167     sock.sendto(msg, ("239.255.255.250", 1900))
2168
2169     logger.debug("Missing ST")
2170     msg = '\r\n'.join([
2171             'M-SEARCH * HTTP/1.1',
2172             'HOST: 239.255.255.250:1900',
2173             'MAN: "ssdp:discover"',
2174             'MX: 1',
2175             '', ''])
2176     sock.sendto(msg, ("239.255.255.250", 1900))
2177
2178     logger.debug("Mismatching ST")
2179     msg = '\r\n'.join([
2180             'M-SEARCH * HTTP/1.1',
2181             'HOST: 239.255.255.250:1900',
2182             'MAN: "ssdp:discover"',
2183             'MX: 1',
2184             'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2185             '', ''])
2186     sock.sendto(msg, ("239.255.255.250", 1900))
2187     msg = '\r\n'.join([
2188             'M-SEARCH * HTTP/1.1',
2189             'HOST: 239.255.255.250:1900',
2190             'MAN: "ssdp:discover"',
2191             'MX: 1',
2192             'ST: foo:bar',
2193             '', ''])
2194     sock.sendto(msg, ("239.255.255.250", 1900))
2195     msg = '\r\n'.join([
2196             'M-SEARCH * HTTP/1.1',
2197             'HOST: 239.255.255.250:1900',
2198             'MAN: "ssdp:discover"',
2199             'MX: 1',
2200             'ST: foobar',
2201             '', ''])
2202     sock.sendto(msg, ("239.255.255.250", 1900))
2203
2204     logger.debug("Invalid ST")
2205     msg = '\r\n'.join([
2206             'M-SEARCH * HTTP/1.1',
2207             'HOST: 239.255.255.250:1900',
2208             'MAN: "ssdp:discover"',
2209             'MX: 1',
2210             'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2211             '', ''])
2212     sock.sendto(msg, ("239.255.255.250", 1900))
2213
2214     logger.debug("Invalid M-SEARCH")
2215     msg = '\r\n'.join([
2216             'M+SEARCH * HTTP/1.1',
2217             'HOST: 239.255.255.250:1900',
2218             'MAN: "ssdp:discover"',
2219             'MX: 1',
2220             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2221             '', ''])
2222     sock.sendto(msg, ("239.255.255.250", 1900))
2223     msg = '\r\n'.join([
2224             'M-SEARCH-* HTTP/1.1',
2225             'HOST: 239.255.255.250:1900',
2226             'MAN: "ssdp:discover"',
2227             'MX: 1',
2228             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2229             '', ''])
2230     sock.sendto(msg, ("239.255.255.250", 1900))
2231
2232     logger.debug("Invalid message format")
2233     sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2234     msg = '\r'.join([
2235             'M-SEARCH * HTTP/1.1',
2236             'HOST: 239.255.255.250:1900',
2237             'MAN: "ssdp:discover"',
2238             'MX: 1',
2239             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2240             '', ''])
2241     sock.sendto(msg, ("239.255.255.250", 1900))
2242
2243     try:
2244         r = sock.recv(1000)
2245         raise Exception("Unexpected M-SEARCH response: " + r)
2246     except socket.timeout:
2247         pass
2248
2249     logger.debug("Valid M-SEARCH")
2250     msg = '\r\n'.join([
2251             'M-SEARCH * HTTP/1.1',
2252             'HOST: 239.255.255.250:1900',
2253             'MAN: "ssdp:discover"',
2254             'MX: 1',
2255             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2256             '', ''])
2257     sock.sendto(msg, ("239.255.255.250", 1900))
2258
2259     try:
2260         r = sock.recv(1000)
2261         pass
2262     except socket.timeout:
2263         raise Exception("No SSDP response")
2264
2265 def test_ap_wps_ssdp_burst(dev, apdev):
2266     """WPS AP and SSDP burst"""
2267     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2268     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2269
2270     msg = '\r\n'.join([
2271             'M-SEARCH * HTTP/1.1',
2272             'HOST: 239.255.255.250:1900',
2273             'MAN: "ssdp:discover"',
2274             'MX: 1',
2275             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2276             '', ''])
2277     socket.setdefaulttimeout(1)
2278     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2279     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2280     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2281     sock.bind(("127.0.0.1", 0))
2282     for i in range(0, 25):
2283         sock.sendto(msg, ("239.255.255.250", 1900))
2284     resp = 0
2285     while True:
2286         try:
2287             r = sock.recv(1000)
2288             if not r.startswith("HTTP/1.1 200 OK\r\n"):
2289                 raise Exception("Unexpected message: " + r)
2290             resp += 1
2291         except socket.timeout:
2292             break
2293     if resp < 20:
2294         raise Exception("Too few SSDP responses")
2295
2296     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2297     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2298     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2299     sock.bind(("127.0.0.1", 0))
2300     for i in range(0, 25):
2301         sock.sendto(msg, ("239.255.255.250", 1900))
2302     while True:
2303         try:
2304             r = sock.recv(1000)
2305             if ap_uuid in r:
2306                 break
2307         except socket.timeout:
2308             raise Exception("No SSDP response")
2309
2310 def ssdp_get_location(uuid):
2311     res = ssdp_send_msearch("uuid:" + uuid)
2312     location = None
2313     for l in res.splitlines():
2314         if l.lower().startswith("location:"):
2315             location = l.split(':', 1)[1].strip()
2316             break
2317     if location is None:
2318         raise Exception("No UPnP location found")
2319     return location
2320
2321 def upnp_get_urls(location):
2322     conn = urllib.urlopen(location)
2323     tree = ET.parse(conn)
2324     root = tree.getroot()
2325     urn = '{urn:schemas-upnp-org:device-1-0}'
2326     service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2327     res = {}
2328     res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
2329     res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
2330     res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
2331     return res
2332
2333 def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
2334     soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2335     wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2336     ET.register_namespace('soapenv', soapns)
2337     ET.register_namespace('wfa', wpsns)
2338     attrib = {}
2339     attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2340     root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2341     body = ET.SubElement(root, "{%s}Body" % soapns)
2342     act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
2343     tree = ET.ElementTree(root)
2344     soap = StringIO.StringIO()
2345     tree.write(soap, xml_declaration=True, encoding='utf-8')
2346
2347     headers = { "Content-type": 'text/xml; charset="utf-8"' }
2348     if include_soap_action:
2349         headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2350     elif soap_action_override:
2351         headers["SOAPAction"] = soap_action_override
2352     conn.request("POST", path, soap.getvalue(), headers)
2353     return conn.getresponse()
2354
2355 def test_ap_wps_upnp(dev, apdev):
2356     """WPS AP and UPnP operations"""
2357     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2358     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2359
2360     location = ssdp_get_location(ap_uuid)
2361     urls = upnp_get_urls(location)
2362
2363     conn = urllib.urlopen(urls['scpd_url'])
2364     scpd = conn.read()
2365
2366     conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
2367     if conn.getcode() != 404:
2368         raise Exception("Unexpected HTTP response to GET unknown URL")
2369
2370     url = urlparse.urlparse(location)
2371     conn = httplib.HTTPConnection(url.netloc)
2372     #conn.set_debuglevel(1)
2373     headers = { "Content-type": 'text/xml; charset="utf-8"',
2374                 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2375     conn.request("POST", "hello", "\r\n\r\n", headers)
2376     resp = conn.getresponse()
2377     if resp.status != 404:
2378         raise Exception("Unexpected HTTP response: %d" % resp.status)
2379
2380     conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2381     resp = conn.getresponse()
2382     if resp.status != 501:
2383         raise Exception("Unexpected HTTP response: %d" % resp.status)
2384
2385     headers = { "Content-type": 'text/xml; charset="utf-8"',
2386                 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2387     ctrlurl = urlparse.urlparse(urls['control_url'])
2388     conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2389     resp = conn.getresponse()
2390     if resp.status != 401:
2391         raise Exception("Unexpected HTTP response: %d" % resp.status)
2392
2393     logger.debug("GetDeviceInfo without SOAPAction header")
2394     resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2395                             include_soap_action=False)
2396     if resp.status != 401:
2397         raise Exception("Unexpected HTTP response: %d" % resp.status)
2398
2399     logger.debug("GetDeviceInfo with invalid SOAPAction header")
2400     for act in [ "foo",
2401                  "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2402                  '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2403                  '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2404         resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2405                                 include_soap_action=False,
2406                                 soap_action_override=act)
2407         if resp.status != 401:
2408             raise Exception("Unexpected HTTP response: %d" % resp.status)
2409
2410     resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2411     if resp.status != 200:
2412         raise Exception("Unexpected HTTP response: %d" % resp.status)
2413     dev = resp.read()
2414     if "NewDeviceInfo" not in dev:
2415         raise Exception("Unexpected GetDeviceInfo response")
2416
2417     logger.debug("PutMessage without required parameters")
2418     resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2419     if resp.status != 600:
2420         raise Exception("Unexpected HTTP response: %d" % resp.status)
2421
2422     logger.debug("PutWLANResponse without required parameters")
2423     resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2424     if resp.status != 600:
2425         raise Exception("Unexpected HTTP response: %d" % resp.status)
2426
2427     logger.debug("SetSelectedRegistrar from unregistered ER")
2428     resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2429     if resp.status != 501:
2430         raise Exception("Unexpected HTTP response: %d" % resp.status)
2431
2432     logger.debug("Unknown action")
2433     resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2434     if resp.status != 401:
2435         raise Exception("Unexpected HTTP response: %d" % resp.status)
2436
2437 def test_ap_wps_upnp_subscribe(dev, apdev):
2438     """WPS AP and UPnP event subscription"""
2439     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2440     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2441
2442     location = ssdp_get_location(ap_uuid)
2443     urls = upnp_get_urls(location)
2444     eventurl = urlparse.urlparse(urls['event_sub_url'])
2445
2446     url = urlparse.urlparse(location)
2447     conn = httplib.HTTPConnection(url.netloc)
2448     #conn.set_debuglevel(1)
2449     headers = { "callback": '<http://127.0.0.1:12345/event>',
2450                 "timeout": "Second-1234" }
2451     conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2452     resp = conn.getresponse()
2453     if resp.status != 412:
2454         raise Exception("Unexpected HTTP response: %d" % resp.status)
2455
2456     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2457     resp = conn.getresponse()
2458     if resp.status != 412:
2459         raise Exception("Unexpected HTTP response: %d" % resp.status)
2460
2461     headers = { "NT": "upnp:event",
2462                 "timeout": "Second-1234" }
2463     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2464     resp = conn.getresponse()
2465     if resp.status != 412:
2466         raise Exception("Unexpected HTTP response: %d" % resp.status)
2467
2468     headers = { "callback": '<http://127.0.0.1:12345/event>',
2469                 "NT": "upnp:foobar",
2470                 "timeout": "Second-1234" }
2471     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2472     resp = conn.getresponse()
2473     if resp.status != 400:
2474         raise Exception("Unexpected HTTP response: %d" % resp.status)
2475
2476     logger.debug("Valid subscription")
2477     headers = { "callback": '<http://127.0.0.1:12345/event>',
2478                 "NT": "upnp:event",
2479                 "timeout": "Second-1234" }
2480     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2481     resp = conn.getresponse()
2482     if resp.status != 200:
2483         raise Exception("Unexpected HTTP response: %d" % resp.status)
2484     sid = resp.getheader("sid")
2485     logger.debug("Subscription SID " + sid)
2486
2487     logger.debug("Invalid re-subscription")
2488     headers = { "NT": "upnp:event",
2489                 "sid": "123456734567854",
2490                 "timeout": "Second-1234" }
2491     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2492     resp = conn.getresponse()
2493     if resp.status != 400:
2494         raise Exception("Unexpected HTTP response: %d" % resp.status)
2495
2496     logger.debug("Invalid re-subscription")
2497     headers = { "NT": "upnp:event",
2498                 "sid": "uuid:123456734567854",
2499                 "timeout": "Second-1234" }
2500     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2501     resp = conn.getresponse()
2502     if resp.status != 400:
2503         raise Exception("Unexpected HTTP response: %d" % resp.status)
2504
2505     logger.debug("Invalid re-subscription")
2506     headers = { "callback": '<http://127.0.0.1:12345/event>',
2507                 "NT": "upnp:event",
2508                 "sid": sid,
2509                 "timeout": "Second-1234" }
2510     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2511     resp = conn.getresponse()
2512     if resp.status != 400:
2513         raise Exception("Unexpected HTTP response: %d" % resp.status)
2514
2515     logger.debug("SID mismatch in re-subscription")
2516     headers = { "NT": "upnp:event",
2517                 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2518                 "timeout": "Second-1234" }
2519     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2520     resp = conn.getresponse()
2521     if resp.status != 412:
2522         raise Exception("Unexpected HTTP response: %d" % resp.status)
2523
2524     logger.debug("Valid re-subscription")
2525     headers = { "NT": "upnp:event",
2526                 "sid": sid,
2527                 "timeout": "Second-1234" }
2528     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2529     resp = conn.getresponse()
2530     if resp.status != 200:
2531         raise Exception("Unexpected HTTP response: %d" % resp.status)
2532     sid2 = resp.getheader("sid")
2533     logger.debug("Subscription SID " + sid2)
2534
2535     if sid != sid2:
2536         raise Exception("Unexpected SID change")
2537
2538     logger.debug("Valid re-subscription")
2539     headers = { "NT": "upnp:event",
2540                 "sid": "uuid: \t \t" + sid.split(':')[1],
2541                 "timeout": "Second-1234" }
2542     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2543     resp = conn.getresponse()
2544     if resp.status != 200:
2545         raise Exception("Unexpected HTTP response: %d" % resp.status)
2546
2547     logger.debug("Invalid unsubscription")
2548     headers = { "sid": sid }
2549     conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
2550     resp = conn.getresponse()
2551     if resp.status != 412:
2552         raise Exception("Unexpected HTTP response: %d" % resp.status)
2553     headers = { "foo": "bar" }
2554     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2555     resp = conn.getresponse()
2556     if resp.status != 412:
2557         raise Exception("Unexpected HTTP response: %d" % resp.status)
2558
2559     logger.debug("Valid unsubscription")
2560     headers = { "sid": sid }
2561     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2562     resp = conn.getresponse()
2563     if resp.status != 200:
2564         raise Exception("Unexpected HTTP response: %d" % resp.status)
2565
2566     logger.debug("Unsubscription for not existing SID")
2567     headers = { "sid": sid }
2568     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2569     resp = conn.getresponse()
2570     if resp.status != 412:
2571         raise Exception("Unexpected HTTP response: %d" % resp.status)
2572
2573     logger.debug("Invalid unsubscription")
2574     headers = { "sid": " \t \tfoo" }
2575     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2576     resp = conn.getresponse()
2577     if resp.status != 400:
2578         raise Exception("Unexpected HTTP response: %d" % resp.status)
2579
2580     logger.debug("Invalid unsubscription")
2581     headers = { "sid": "uuid:\t \tfoo" }
2582     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2583     resp = conn.getresponse()
2584     if resp.status != 400:
2585         raise Exception("Unexpected HTTP response: %d" % resp.status)
2586
2587     logger.debug("Invalid unsubscription")
2588     headers = { "NT": "upnp:event",
2589                 "sid": sid }
2590     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2591     resp = conn.getresponse()
2592     if resp.status != 400:
2593         raise Exception("Unexpected HTTP response: %d" % resp.status)
2594     headers = { "callback": '<http://127.0.0.1:12345/event>',
2595                 "sid": sid }
2596     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2597     resp = conn.getresponse()
2598     if resp.status != 400:
2599         raise Exception("Unexpected HTTP response: %d" % resp.status)
2600
2601     logger.debug("Valid subscription with multiple callbacks")
2602     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>',
2603                 "NT": "upnp:event",
2604                 "timeout": "Second-1234" }
2605     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2606     resp = conn.getresponse()
2607     if resp.status != 200:
2608         raise Exception("Unexpected HTTP response: %d" % resp.status)
2609     sid = resp.getheader("sid")
2610     logger.debug("Subscription SID " + sid)
2611
2612     # Force subscription to be deleted due to errors
2613     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2614     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2615     with alloc_fail(hapd, 1, "event_build_message"):
2616         for i in range(10):
2617             dev[1].dump_monitor()
2618             dev[2].dump_monitor()
2619             dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2620             dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2621             dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2622             dev[1].request("WPS_CANCEL")
2623             dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2624             dev[2].request("WPS_CANCEL")
2625             if i % 4 == 1:
2626                 time.sleep(1)
2627             else:
2628                 time.sleep(0.1)
2629     time.sleep(0.2)
2630
2631     headers = { "sid": sid }
2632     conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
2633     resp = conn.getresponse()
2634     if resp.status != 200 and resp.status != 412:
2635         raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
2636
2637     headers = { "callback": '<http://127.0.0.1:12345/event>',
2638                 "NT": "upnp:event",
2639                 "timeout": "Second-1234" }
2640     with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
2641         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2642         resp = conn.getresponse()
2643         if resp.status != 200:
2644             raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
2645         sid = resp.getheader("sid")
2646         logger.debug("Subscription SID " + sid)
2647
2648     headers = { "sid": sid }
2649     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2650     resp = conn.getresponse()
2651     if resp.status != 200:
2652         raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
2653
2654     headers = { "callback": '<http://127.0.0.1:12345/event>',
2655                 "NT": "upnp:event",
2656                 "timeout": "Second-1234" }
2657     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2658     resp = conn.getresponse()
2659     if resp.status != 200:
2660         raise Exception("Unexpected HTTP response: %d" % resp.status)
2661     sid = resp.getheader("sid")
2662     logger.debug("Subscription SID " + sid)
2663
2664     with alloc_fail(hapd, 1, "=event_add"):
2665         for i in range(2):
2666             dev[1].dump_monitor()
2667             dev[2].dump_monitor()
2668             dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2669             dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2670             dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2671             dev[1].request("WPS_CANCEL")
2672             dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2673             dev[2].request("WPS_CANCEL")
2674             if i == 0:
2675                 time.sleep(1)
2676             else:
2677                 time.sleep(0.1)
2678
2679     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2680     resp = conn.getresponse()
2681     if resp.status != 200:
2682         raise Exception("Unexpected HTTP response: %d" % resp.status)
2683
2684     with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
2685         dev[1].dump_monitor()
2686         dev[2].dump_monitor()
2687         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2688         dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2689         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2690         dev[1].request("WPS_CANCEL")
2691         dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2692         dev[2].request("WPS_CANCEL")
2693         time.sleep(0.1)
2694
2695     with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
2696         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2697         resp = conn.getresponse()
2698         if resp.status != 500:
2699             raise Exception("Unexpected HTTP response: %d" % resp.status)
2700
2701     with alloc_fail(hapd, 1, "=subscription_start"):
2702         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2703         resp = conn.getresponse()
2704         if resp.status != 500:
2705             raise Exception("Unexpected HTTP response: %d" % resp.status)
2706
2707     headers = { "callback": '',
2708                 "NT": "upnp:event",
2709                 "timeout": "Second-1234" }
2710     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2711     resp = conn.getresponse()
2712     if resp.status != 500:
2713         raise Exception("Unexpected HTTP response: %d" % resp.status)
2714
2715     headers = { "callback": ' <',
2716                 "NT": "upnp:event",
2717                 "timeout": "Second-1234" }
2718     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2719     resp = conn.getresponse()
2720     if resp.status != 500:
2721         raise Exception("Unexpected HTTP response: %d" % resp.status)
2722
2723     headers = { "callback": '<http://127.0.0.1:12345/event>',
2724                 "NT": "upnp:event",
2725                 "timeout": "Second-1234" }
2726     with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
2727         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2728         resp = conn.getresponse()
2729         if resp.status != 500:
2730             raise Exception("Unexpected HTTP response: %d" % resp.status)
2731
2732     with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
2733         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2734         resp = conn.getresponse()
2735         if resp.status != 500:
2736             raise Exception("Unexpected HTTP response: %d" % resp.status)
2737
2738     with alloc_fail(hapd, 1, "subscr_addr_add_url"):
2739         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2740         resp = conn.getresponse()
2741         if resp.status != 500:
2742             raise Exception("Unexpected HTTP response: %d" % resp.status)
2743
2744     with alloc_fail(hapd, 2, "subscr_addr_add_url"):
2745         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2746         resp = conn.getresponse()
2747         if resp.status != 500:
2748             raise Exception("Unexpected HTTP response: %d" % resp.status)
2749
2750     for i in range(6):
2751         headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
2752                     "NT": "upnp:event",
2753                     "timeout": "Second-1234" }
2754         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2755         resp = conn.getresponse()
2756         if resp.status != 200:
2757             raise Exception("Unexpected HTTP response: %d" % resp.status)
2758
2759     with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
2760         dev[1].dump_monitor()
2761         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2762         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2763         dev[1].request("WPS_CANCEL")
2764         time.sleep(0.1)
2765
2766     with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
2767         dev[1].dump_monitor()
2768         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2769         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2770         dev[1].request("WPS_CANCEL")
2771         time.sleep(0.1)
2772
2773     with alloc_fail(hapd, 1, "base64_encode;upnp_wps_device_send_wlan_event"):
2774         dev[1].dump_monitor()
2775         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2776         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2777         dev[1].request("WPS_CANCEL")
2778         time.sleep(0.1)
2779
2780     hapd.disable()
2781     with alloc_fail(hapd, 1, "get_netif_info"):
2782         if "FAIL" not in hapd.request("ENABLE"):
2783             raise Exception("ENABLE succeeded during OOM")
2784
2785 def test_ap_wps_upnp_subscribe_events(dev, apdev):
2786     """WPS AP and UPnP event subscription and many events"""
2787     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2788     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2789
2790     location = ssdp_get_location(ap_uuid)
2791     urls = upnp_get_urls(location)
2792     eventurl = urlparse.urlparse(urls['event_sub_url'])
2793
2794     class WPSERHTTPServer(SocketServer.StreamRequestHandler):
2795         def handle(self):
2796             data = self.rfile.readline().strip()
2797             logger.debug(data)
2798             self.wfile.write(gen_wps_event())
2799
2800     server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2801     server.timeout = 1
2802
2803     url = urlparse.urlparse(location)
2804     conn = httplib.HTTPConnection(url.netloc)
2805
2806     headers = { "callback": '<http://127.0.0.1:12345/event>',
2807                 "NT": "upnp:event",
2808                 "timeout": "Second-1234" }
2809     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2810     resp = conn.getresponse()
2811     if resp.status != 200:
2812         raise Exception("Unexpected HTTP response: %d" % resp.status)
2813     sid = resp.getheader("sid")
2814     logger.debug("Subscription SID " + sid)
2815
2816     # Fetch the first event message
2817     server.handle_request()
2818
2819     # Force subscription event queue to reach the maximum length by generating
2820     # new proxied events without the ER fetching any of the pending events.
2821     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2822     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2823     for i in range(16):
2824         dev[1].dump_monitor()
2825         dev[2].dump_monitor()
2826         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2827         dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2828         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2829         dev[1].request("WPS_CANCEL")
2830         dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2831         dev[2].request("WPS_CANCEL")
2832         if i % 4 == 1:
2833             time.sleep(1)
2834         else:
2835             time.sleep(0.1)
2836
2837     hapd.request("WPS_PIN any 12345670")
2838     dev[1].dump_monitor()
2839     dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2840     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
2841     if ev is None:
2842         raise Exception("WPS success not reported")
2843
2844     # Close the WPS ER HTTP server without fetching all the pending events.
2845     # This tests hostapd code path that clears subscription and the remaining
2846     # event queue when the interface is deinitialized.
2847     server.handle_request()
2848     server.server_close()
2849
2850     dev[1].wait_connected()
2851
2852 def test_ap_wps_upnp_http_proto(dev, apdev):
2853     """WPS AP and UPnP/HTTP protocol testing"""
2854     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2855     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2856
2857     location = ssdp_get_location(ap_uuid)
2858
2859     url = urlparse.urlparse(location)
2860     conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
2861     #conn.set_debuglevel(1)
2862
2863     conn.request("HEAD", "hello")
2864     resp = conn.getresponse()
2865     if resp.status != 501:
2866         raise Exception("Unexpected response to HEAD: " + str(resp.status))
2867     conn.close()
2868
2869     for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
2870         try:
2871             conn.request(cmd, "hello")
2872             resp = conn.getresponse()
2873         except Exception, e:
2874             pass
2875         conn.close()
2876
2877     headers = { "Content-Length": 'abc' }
2878     conn.request("HEAD", "hello", "\r\n\r\n", headers)
2879     try:
2880         resp = conn.getresponse()
2881     except Exception, e:
2882         pass
2883     conn.close()
2884
2885     headers = { "Content-Length": '-10' }
2886     conn.request("HEAD", "hello", "\r\n\r\n", headers)
2887     try:
2888         resp = conn.getresponse()
2889     except Exception, e:
2890         pass
2891     conn.close()
2892
2893     headers = { "Content-Length": '10000000000000' }
2894     conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
2895     try:
2896         resp = conn.getresponse()
2897     except Exception, e:
2898         pass
2899     conn.close()
2900
2901     headers = { "Transfer-Encoding": 'abc' }
2902     conn.request("HEAD", "hello", "\r\n\r\n", headers)
2903     resp = conn.getresponse()
2904     if resp.status != 501:
2905         raise Exception("Unexpected response to HEAD: " + str(resp.status))
2906     conn.close()
2907
2908     headers = { "Transfer-Encoding": 'chunked' }
2909     conn.request("HEAD", "hello", "\r\n\r\n", headers)
2910     resp = conn.getresponse()
2911     if resp.status != 501:
2912         raise Exception("Unexpected response to HEAD: " + str(resp.status))
2913     conn.close()
2914
2915     # Too long a header
2916     conn.request("HEAD", 5000 * 'A')
2917     try:
2918         resp = conn.getresponse()
2919     except Exception, e:
2920         pass
2921     conn.close()
2922
2923     # Long URL but within header length limits
2924     conn.request("HEAD", 3000 * 'A')
2925     resp = conn.getresponse()
2926     if resp.status != 501:
2927         raise Exception("Unexpected response to HEAD: " + str(resp.status))
2928     conn.close()
2929
2930     headers = { "Content-Length": '20' }
2931     conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
2932     try:
2933         resp = conn.getresponse()
2934     except Exception, e:
2935         pass
2936     conn.close()
2937
2938     conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
2939     resp = conn.getresponse()
2940     if resp.status != 404:
2941         raise Exception("Unexpected HTTP response: %d" % resp.status)
2942     conn.close()
2943
2944     conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
2945     try:
2946         resp = conn.getresponse()
2947     except Exception, e:
2948         pass
2949     conn.close()
2950
2951 def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
2952     """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
2953     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2954     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2955
2956     location = ssdp_get_location(ap_uuid)
2957
2958     url = urlparse.urlparse(location)
2959     conn = httplib.HTTPConnection(url.netloc)
2960     #conn.set_debuglevel(1)
2961
2962     headers = { "Transfer-Encoding": 'chunked' }
2963     conn.request("POST", "hello",
2964                  "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
2965                  headers)
2966     resp = conn.getresponse()
2967     if resp.status != 404:
2968         raise Exception("Unexpected HTTP response: %d" % resp.status)
2969     conn.close()
2970
2971     conn.putrequest("POST", "hello")
2972     conn.putheader('Transfer-Encoding', 'chunked')
2973     conn.endheaders()
2974     conn.send("a\r\nabcdefghij\r\n")
2975     time.sleep(0.1)
2976     conn.send("2\r\nkl\r\n")
2977     conn.send("0\r\n\r\n")
2978     resp = conn.getresponse()
2979     if resp.status != 404:
2980         raise Exception("Unexpected HTTP response: %d" % resp.status)
2981     conn.close()
2982
2983     conn.putrequest("POST", "hello")
2984     conn.putheader('Transfer-Encoding', 'chunked')
2985     conn.endheaders()
2986     completed = False
2987     try:
2988         for i in range(20000):
2989             conn.send("1\r\nZ\r\n")
2990         conn.send("0\r\n\r\n")
2991         resp = conn.getresponse()
2992         completed = True
2993     except Exception, e:
2994         pass
2995     conn.close()
2996     if completed:
2997         raise Exception("Too long chunked request did not result in connection reset")
2998
2999     headers = { "Transfer-Encoding": 'chunked' }
3000     conn.request("POST", "hello", "80000000\r\na", headers)
3001     try:
3002         resp = conn.getresponse()
3003     except Exception, e:
3004         pass
3005     conn.close()
3006
3007     conn.request("POST", "hello", "10000000\r\na", headers)
3008     try:
3009         resp = conn.getresponse()
3010     except Exception, e:
3011         pass
3012     conn.close()
3013
3014 def test_ap_wps_disabled(dev, apdev):
3015     """WPS operations while WPS is disabled"""
3016     ssid = "test-wps-disabled"
3017     hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
3018     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3019     if "FAIL" not in hapd.request("WPS_PBC"):
3020         raise Exception("WPS_PBC succeeded unexpectedly")
3021     if "FAIL" not in hapd.request("WPS_CANCEL"):
3022         raise Exception("WPS_CANCEL succeeded unexpectedly")
3023
3024 def test_ap_wps_mixed_cred(dev, apdev):
3025     """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3026     ssid = "test-wps-wep"
3027     hostapd.add_ap(apdev[0]['ifname'],
3028                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3029                      "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
3030     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3031     hapd.request("WPS_PBC")
3032     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3033     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3034     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
3035     if ev is None:
3036         raise Exception("WPS-SUCCESS event timed out")
3037     nets = dev[0].list_networks()
3038     if len(nets) != 1:
3039         raise Exception("Unexpected number of network blocks")
3040     id = nets[0]['id']
3041     proto = dev[0].get_network(id, "proto")
3042     if proto != "WPA RSN":
3043         raise Exception("Unexpected merged proto field value: " + proto)
3044     pairwise = dev[0].get_network(id, "pairwise")
3045     if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
3046         raise Exception("Unexpected merged pairwise field value: " + pairwise)
3047
3048 def test_ap_wps_while_connected(dev, apdev):
3049     """WPS PBC provisioning while connected to another AP"""
3050     ssid = "test-wps-conf"
3051     hostapd.add_ap(apdev[0]['ifname'],
3052                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3053                      "wpa_passphrase": "12345678", "wpa": "2",
3054                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3055     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3056
3057     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
3058     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3059
3060     logger.info("WPS provisioning step")
3061     hapd.request("WPS_PBC")
3062     dev[0].dump_monitor()
3063     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3064     dev[0].wait_connected(timeout=30)
3065     status = dev[0].get_status()
3066     if status['bssid'] != apdev[0]['bssid']:
3067         raise Exception("Unexpected BSSID")
3068
3069 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3070     """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3071     ssid = "test-wps-conf"
3072     hostapd.add_ap(apdev[0]['ifname'],
3073                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3074                      "wpa_passphrase": "12345678", "wpa": "2",
3075                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3076     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3077
3078     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
3079
3080     try:
3081         dev[0].request("STA_AUTOCONNECT 0")
3082         dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3083
3084         logger.info("WPS provisioning step")
3085         hapd.request("WPS_PBC")
3086         dev[0].dump_monitor()
3087         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3088         dev[0].wait_connected(timeout=30)
3089         status = dev[0].get_status()
3090         if status['bssid'] != apdev[0]['bssid']:
3091             raise Exception("Unexpected BSSID")
3092     finally:
3093         dev[0].request("STA_AUTOCONNECT 1")
3094
3095 def test_ap_wps_from_event(dev, apdev):
3096     """WPS PBC event on AP to enable PBC"""
3097     ssid = "test-wps-conf"
3098     hapd = hostapd.add_ap(apdev[0]['ifname'],
3099                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3100                             "wpa_passphrase": "12345678", "wpa": "2",
3101                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3102     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3103     dev[0].dump_monitor()
3104     hapd.dump_monitor()
3105     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3106
3107     ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3108     if ev is None:
3109         raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3110     vals = ev.split(' ')
3111     if vals[1] != dev[0].p2p_interface_addr():
3112         raise Exception("Unexpected enrollee address: " + vals[1])
3113     if vals[5] != '4':
3114         raise Exception("Unexpected Device Password Id: " + vals[5])
3115     hapd.request("WPS_PBC")
3116     dev[0].wait_connected(timeout=30)
3117
3118 def test_ap_wps_ap_scan_2(dev, apdev):
3119     """AP_SCAN 2 for WPS"""
3120     ssid = "test-wps-conf"
3121     hapd = hostapd.add_ap(apdev[0]['ifname'],
3122                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3123                             "wpa_passphrase": "12345678", "wpa": "2",
3124                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3125     hapd.request("WPS_PBC")
3126
3127     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3128     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
3129
3130     if "OK" not in wpas.request("AP_SCAN 2"):
3131         raise Exception("Failed to set AP_SCAN 2")
3132
3133     wpas.flush_scan_cache()
3134     wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
3135     wpas.request("WPS_PBC " + apdev[0]['bssid'])
3136     ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3137     if ev is None:
3138         raise Exception("WPS-SUCCESS event timed out")
3139     wpas.wait_connected(timeout=30)
3140     wpas.request("DISCONNECT")
3141     wpas.request("BSS_FLUSH 0")
3142     wpas.dump_monitor()
3143     wpas.request("REASSOCIATE")
3144     wpas.wait_connected(timeout=30)
3145
3146 def test_ap_wps_eapol_workaround(dev, apdev):
3147     """EAPOL workaround code path for 802.1X header length mismatch"""
3148     ssid = "test-wps"
3149     hostapd.add_ap(apdev[0]['ifname'],
3150                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
3151     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3152     bssid = apdev[0]['bssid']
3153     hapd.request("SET ext_eapol_frame_io 1")
3154     dev[0].request("SET ext_eapol_frame_io 1")
3155     hapd.request("WPS_PBC")
3156     dev[0].request("WPS_PBC")
3157
3158     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3159     if ev is None:
3160         raise Exception("Timeout on EAPOL-TX from hostapd")
3161
3162     res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3163     if "OK" not in res:
3164         raise Exception("EAPOL_RX to wpa_supplicant failed")
3165
3166 def test_ap_wps_iteration(dev, apdev):
3167     """WPS PIN and iterate through APs without selected registrar"""
3168     ssid = "test-wps-conf"
3169     hapd = hostapd.add_ap(apdev[0]['ifname'],
3170                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3171                             "wpa_passphrase": "12345678", "wpa": "2",
3172                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3173
3174     ssid2 = "test-wps-conf2"
3175     hapd2 = hostapd.add_ap(apdev[1]['ifname'],
3176                            { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
3177                              "wpa_passphrase": "12345678", "wpa": "2",
3178                              "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3179
3180     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3181     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3182     dev[0].dump_monitor()
3183     pin = dev[0].request("WPS_PIN any")
3184
3185     # Wait for iteration through all WPS APs to happen before enabling any
3186     # Registrar.
3187     for i in range(2):
3188         ev = dev[0].wait_event(["Associated with"], timeout=30)
3189         if ev is None:
3190             raise Exception("No association seen")
3191         ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3192         if ev is None:
3193             raise Exception("No M2D from AP")
3194         dev[0].wait_disconnected()
3195
3196     # Verify that each AP requested PIN
3197     ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3198     if ev is None:
3199         raise Exception("No WPS-PIN-NEEDED event from AP")
3200     ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3201     if ev is None:
3202         raise Exception("No WPS-PIN-NEEDED event from AP2")
3203
3204     # Provide PIN to one of the APs and verify that connection gets formed
3205     hapd.request("WPS_PIN any " + pin)
3206     dev[0].wait_connected(timeout=30)
3207
3208 def test_ap_wps_iteration_error(dev, apdev):
3209     """WPS AP iteration on no Selected Registrar and error case with an AP"""
3210     ssid = "test-wps-conf-pin"
3211     hapd = hostapd.add_ap(apdev[0]['ifname'],
3212                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3213                             "wpa_passphrase": "12345678", "wpa": "2",
3214                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3215                             "wps_independent": "1" })
3216     hapd.request("SET ext_eapol_frame_io 1")
3217     bssid = apdev[0]['bssid']
3218     pin = dev[0].wps_read_pin()
3219     dev[0].request("WPS_PIN any " + pin)
3220
3221     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3222     if ev is None:
3223         raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3224     dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3225
3226     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3227     if ev is None:
3228         raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3229     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3230     if ev is None:
3231         raise Exception("No CTRL-EVENT-EAP-STARTED")
3232
3233     # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3234     # a case with an incorrectly behaving WPS AP.
3235
3236     # Start the real target AP and activate registrar on it.
3237     hapd2 = hostapd.add_ap(apdev[1]['ifname'],
3238                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3239                             "wpa_passphrase": "12345678", "wpa": "2",
3240                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3241                             "wps_independent": "1" })
3242     hapd2.request("WPS_PIN any " + pin)
3243
3244     dev[0].wait_disconnected(timeout=15)
3245     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3246     if ev is None:
3247         raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3248     ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3249     if ev is None:
3250         raise Exception("No WPS-CRED-RECEIVED for the second AP")
3251     dev[0].wait_connected(timeout=15)
3252
3253 def test_ap_wps_priority(dev, apdev):
3254     """WPS PIN provisioning with configured AP and wps_priority"""
3255     ssid = "test-wps-conf-pin"
3256     hostapd.add_ap(apdev[0]['ifname'],
3257                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3258                      "wpa_passphrase": "12345678", "wpa": "2",
3259                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3260     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3261     logger.info("WPS provisioning step")
3262     pin = dev[0].wps_read_pin()
3263     hapd.request("WPS_PIN any " + pin)
3264     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3265     dev[0].dump_monitor()
3266     try:
3267         dev[0].request("SET wps_priority 6")
3268         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3269         dev[0].wait_connected(timeout=30)
3270         netw = dev[0].list_networks()
3271         prio = dev[0].get_network(netw[0]['id'], 'priority')
3272         if prio != '6':
3273             raise Exception("Unexpected network priority: " + prio)
3274     finally:
3275         dev[0].request("SET wps_priority 0")
3276
3277 def test_ap_wps_and_non_wps(dev, apdev):
3278     """WPS and non-WPS AP in single hostapd process"""
3279     params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
3280     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3281
3282     params = { "ssid": "no wps" }
3283     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
3284
3285     appin = hapd.request("WPS_AP_PIN random")
3286     if "FAIL" in appin:
3287         raise Exception("Could not generate random AP PIN")
3288     if appin not in hapd.request("WPS_AP_PIN get"):
3289         raise Exception("Could not fetch current AP PIN")
3290
3291     if "FAIL" in hapd.request("WPS_PBC"):
3292         raise Exception("WPS_PBC failed")
3293     if "FAIL" in hapd.request("WPS_CANCEL"):
3294         raise Exception("WPS_CANCEL failed")
3295
3296 def test_ap_wps_init_oom(dev, apdev):
3297     """Initial AP configuration and OOM during PSK generation"""
3298     ssid = "test-wps"
3299     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
3300     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3301
3302     with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
3303         pin = dev[0].wps_read_pin()
3304         hapd.request("WPS_PIN any " + pin)
3305         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3306         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3307         dev[0].wait_disconnected()
3308
3309     hapd.request("WPS_PIN any " + pin)
3310     dev[0].wait_connected(timeout=30)
3311
3312 def test_ap_wps_er_oom(dev, apdev):
3313     """WPS ER OOM in XML processing"""
3314     try:
3315         _test_ap_wps_er_oom(dev, apdev)
3316     finally:
3317         dev[0].request("WPS_ER_STOP")
3318         dev[1].request("WPS_CANCEL")
3319         dev[0].request("DISCONNECT")
3320
3321 def _test_ap_wps_er_oom(dev, apdev):
3322     ssid = "wps-er-ap-config"
3323     ap_pin = "12345670"
3324     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3325     hostapd.add_ap(apdev[0]['ifname'],
3326                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3327                      "wpa_passphrase": "12345678", "wpa": "2",
3328                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3329                      "device_name": "Wireless AP", "manufacturer": "Company",
3330                      "model_name": "WAP", "model_number": "123",
3331                      "serial_number": "12345", "device_type": "6-0050F204-1",
3332                      "os_version": "01020300",
3333                      "config_methods": "label push_button",
3334                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3335
3336     dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3337
3338     with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3339         dev[0].request("WPS_ER_START ifname=lo")
3340         ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3341         if ev is not None:
3342             raise Exception("Unexpected AP discovery")
3343
3344     dev[0].request("WPS_ER_STOP")
3345     dev[0].request("WPS_ER_START ifname=lo")
3346     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3347     if ev is None:
3348         raise Exception("AP discovery timed out")
3349
3350     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3351     with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3352         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3353         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3354         if ev is None:
3355             raise Exception("PBC scan failed")
3356         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3357         if ev is None:
3358             raise Exception("Enrollee discovery timed out")
3359
3360 def test_ap_wps_er_init_oom(dev, apdev):
3361     """WPS ER and OOM during init"""
3362     try:
3363         _test_ap_wps_er_init_oom(dev, apdev)
3364     finally:
3365         dev[0].request("WPS_ER_STOP")
3366
3367 def _test_ap_wps_er_init_oom(dev, apdev):
3368     with alloc_fail(dev[0], 1, "wps_er_init"):
3369         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3370             raise Exception("WPS_ER_START succeeded during OOM")
3371     with alloc_fail(dev[0], 1, "http_server_init"):
3372         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3373             raise Exception("WPS_ER_START succeeded during OOM")
3374     with alloc_fail(dev[0], 2, "http_server_init"):
3375         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3376             raise Exception("WPS_ER_START succeeded during OOM")
3377     with alloc_fail(dev[0], 1, "eloop_register_sock;wps_er_ssdp_init"):
3378         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3379             raise Exception("WPS_ER_START succeeded during OOM")
3380     with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3381         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3382             raise Exception("WPS_ER_START succeeded during os_get_random failure")
3383
3384 def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3385     """WPS events and wpa_cli action script"""
3386     logdir = os.path.abspath(test_params['logdir'])
3387     pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3388     logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3389     actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
3390
3391     with open(actionfile, 'w') as f:
3392         f.write('#!/bin/sh\n')
3393         f.write('echo $* >> %s\n' % logfile)
3394         # Kill the process and wait some time before returning to allow all the
3395         # pending events to be processed with some of this happening after the
3396         # eloop SIGALRM signal has been scheduled.
3397         f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3398
3399     os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3400              stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
3401
3402     ssid = "test-wps-conf"
3403     hostapd.add_ap(apdev[0]['ifname'],
3404                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3405                      "wpa_passphrase": "12345678", "wpa": "2",
3406                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3407     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3408
3409     prg = os.path.join(test_params['logdir'],
3410                        'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3411     if not os.path.exists(prg):
3412         prg = '../../wpa_supplicant/wpa_cli'
3413     arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
3414     subprocess.call(arg)
3415
3416     arg = [ 'ps', 'ax' ]
3417     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3418     out = cmd.communicate()[0]
3419     cmd.wait()
3420     logger.debug("Processes:\n" + out)
3421     if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3422         raise Exception("Did not see wpa_cli running")
3423
3424     hapd.request("WPS_PIN any 12345670")
3425     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3426     dev[0].dump_monitor()
3427     dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3428     dev[0].wait_connected(timeout=30)
3429
3430     for i in range(30):
3431         if not os.path.exists(pidfile):
3432             break
3433         time.sleep(0.1)
3434
3435     if not os.path.exists(logfile):
3436         raise Exception("wpa_cli action results file not found")
3437     with open(logfile, 'r') as f:
3438         res = f.read()
3439     if "WPS-SUCCESS" not in res:
3440         raise Exception("WPS-SUCCESS event not seen in action file")
3441
3442     arg = [ 'ps', 'ax' ]
3443     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3444     out = cmd.communicate()[0]
3445     cmd.wait()
3446     logger.debug("Remaining processes:\n" + out)
3447     if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3448         raise Exception("wpa_cli still running")
3449
3450     if os.path.exists(pidfile):
3451         raise Exception("PID file not removed")
3452
3453 def test_ap_wps_er_ssdp_proto(dev, apdev):
3454     """WPS ER SSDP protocol testing"""
3455     try:
3456         _test_ap_wps_er_ssdp_proto(dev, apdev)
3457     finally:
3458         dev[0].request("WPS_ER_STOP")
3459
3460 def _test_ap_wps_er_ssdp_proto(dev, apdev):
3461     socket.setdefaulttimeout(1)
3462     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3463     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3464     sock.bind(("239.255.255.250", 1900))
3465     if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3466         raise Exception("Invalid filter accepted")
3467     if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3468         raise Exception("WPS_ER_START with filter failed")
3469     (msg,addr) = sock.recvfrom(1000)
3470     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3471     if "M-SEARCH" not in msg:
3472         raise Exception("Not an M-SEARCH")
3473     sock.sendto("FOO", addr)
3474     time.sleep(0.1)
3475     dev[0].request("WPS_ER_STOP")
3476
3477     dev[0].request("WPS_ER_START ifname=lo")
3478     (msg,addr) = sock.recvfrom(1000)
3479     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3480     if "M-SEARCH" not in msg:
3481         raise Exception("Not an M-SEARCH")
3482     sock.sendto("FOO", addr)
3483     sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3484     sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3485     sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3486     sock.sendto("HTTP/1.1 200 OK\r\ncache-control:   foo=1\r\n\r\n", addr)
3487     sock.sendto("HTTP/1.1 200 OK\r\ncache-control:   max-age=1\r\n\r\n", addr)
3488     sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3489     sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3490     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:\r\n\r\n", addr)
3491     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:     \r\n\r\n", addr)
3492     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:     foo\r\n\r\n", addr)
3493     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3494     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3495     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
3496     with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3497         sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
3498         time.sleep(0.1)
3499     with alloc_fail(dev[0], 2, "wps_er_ap_add"):
3500         sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
3501         time.sleep(0.1)
3502
3503     # Add an AP with bogus URL
3504     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
3505     # Update timeout on AP without updating URL
3506     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
3507     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3508     if ev is None:
3509         raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3510
3511     # Add an AP with a valid URL (but no server listing to it)
3512     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
3513     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3514     if ev is None:
3515         raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3516
3517     sock.close()
3518
3519 wps_event_url = None
3520
3521 def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
3522                   udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
3523     payload = '''<?xml version="1.0"?>
3524 <root xmlns="urn:schemas-upnp-org:device-1-0">
3525 <specVersion>
3526 <major>1</major>
3527 <minor>0</minor>
3528 </specVersion>
3529 <device>
3530 <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
3531 <friendlyName>WPS Access Point</friendlyName>
3532 <manufacturer>Company</manufacturer>
3533 <modelName>WAP</modelName>
3534 <modelNumber>123</modelNumber>
3535 <serialNumber>12345</serialNumber>
3536 '''
3537     if udn:
3538         payload += '<UDN>' + udn + '</UDN>'
3539     payload += '''<serviceList>
3540 <service>
3541 <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
3542 <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
3543 <SCPDURL>wps_scpd.xml</SCPDURL>
3544 '''
3545     if controlURL:
3546         payload += '<controlURL>' + controlURL + '</controlURL>\n'
3547     if eventSubURL:
3548         payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
3549     payload += '''</service>
3550 </serviceList>
3551 </device>
3552 </root>
3553 '''
3554     hdr = 'HTTP/1.1 200 OK\r\n' + \
3555           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3556           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3557           'Connection: close\r\n' + \
3558           'Content-Length: ' + str(len(payload)) + '\r\n' + \
3559           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3560     return hdr + payload
3561
3562 def gen_wps_control(payload_override=None):
3563     payload = '''<?xml version="1.0"?>
3564 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
3565 <s:Body>
3566 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
3567 <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
3568 Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
3569 +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
3570 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
3571 KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
3572 AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
3573 AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
3574 AAYANyoAASA=
3575 </NewDeviceInfo>
3576 </u:GetDeviceInfoResponse>
3577 </s:Body>
3578 </s:Envelope>
3579 '''
3580     if payload_override:
3581         payload = payload_override
3582     hdr = 'HTTP/1.1 200 OK\r\n' + \
3583           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3584           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3585           'Connection: close\r\n' + \
3586           'Content-Length: ' + str(len(payload)) + '\r\n' + \
3587           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3588     return hdr + payload
3589
3590 def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
3591     payload = ""
3592     hdr = 'HTTP/1.1 200 OK\r\n' + \
3593           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3594           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3595           'Connection: close\r\n' + \
3596           'Content-Length: ' + str(len(payload)) + '\r\n'
3597     if sid:
3598         hdr += 'SID: ' + sid + '\r\n'
3599     hdr += 'Timeout: Second-1801\r\n' + \
3600           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3601     return hdr + payload
3602
3603 class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
3604     def handle(self):
3605         data = self.rfile.readline().strip()
3606         logger.info("HTTP server received: " + data)
3607         while True:
3608             hdr = self.rfile.readline().strip()
3609             if len(hdr) == 0:
3610                 break
3611             logger.info("HTTP header: " + hdr)
3612             if "CALLBACK:" in hdr:
3613                 global wps_event_url
3614                 wps_event_url = hdr.split(' ')[1].strip('<>')
3615
3616         if "GET /foo.xml" in data:
3617             self.handle_upnp_info()
3618         elif "POST /wps_control" in data:
3619             self.handle_wps_control()
3620         elif "SUBSCRIBE /wps_event" in data:
3621             self.handle_wps_event()
3622         else:
3623             self.handle_others(data)
3624
3625     def handle_upnp_info(self):
3626         self.wfile.write(gen_upnp_info())
3627
3628     def handle_wps_control(self):
3629         self.wfile.write(gen_wps_control())
3630
3631     def handle_wps_event(self):
3632         self.wfile.write(gen_wps_event())
3633
3634     def handle_others(self, data):
3635         logger.info("Ignore HTTP request: " + data)
3636
3637 class MyTCPServer(SocketServer.TCPServer):
3638     def __init__(self, addr, handler):
3639         self.allow_reuse_address = True
3640         SocketServer.TCPServer.__init__(self, addr, handler)
3641
3642 def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
3643                  location_url=None):
3644     socket.setdefaulttimeout(1)
3645     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3646     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3647     sock.bind(("239.255.255.250", 1900))
3648     dev.request("WPS_ER_START ifname=lo")
3649     for i in range(100):
3650         (msg,addr) = sock.recvfrom(1000)
3651         logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3652         if "M-SEARCH" in msg:
3653             break
3654         if not wait_m_search:
3655             raise Exception("Not an M-SEARCH")
3656         if i == 99:
3657             raise Exception("No M-SEARCH seen")
3658
3659     # Add an AP with a valid URL and server listing to it
3660     server = MyTCPServer(("127.0.0.1", 12345), http_server)
3661     if not location_url:
3662         location_url = 'http://127.0.0.1:12345/foo.xml'
3663     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:%s\r\ncache-control:max-age=%d\r\n\r\n" % (location_url, max_age), addr)
3664     server.timeout = 1
3665     return server,sock
3666
3667 def wps_er_stop(dev, sock, server, on_alloc_fail=False):
3668     sock.close()
3669     server.server_close()
3670
3671     if on_alloc_fail:
3672         done = False
3673         for i in range(50):
3674             res = dev.request("GET_ALLOC_FAIL")
3675             if res.startswith("0:"):
3676                 done = True
3677                 break
3678             time.sleep(0.1)
3679         if not done:
3680             raise Exception("No allocation failure reported")
3681     else:
3682         ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3683         if ev is None:
3684             raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3685     dev.request("WPS_ER_STOP")
3686
3687 def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
3688     try:
3689         uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
3690         server,sock = wps_er_start(dev, handler, location_url=location_url)
3691         global wps_event_url
3692         wps_event_url = None
3693         server.handle_request()
3694         server.handle_request()
3695         server.handle_request()
3696         server.server_close()
3697         if no_event_url:
3698             if wps_event_url:
3699                 raise Exception("Received event URL unexpectedly")
3700             return
3701         if wps_event_url is None:
3702             raise Exception("Did not get event URL")
3703         logger.info("Event URL: " + wps_event_url)
3704     finally:
3705             dev.request("WPS_ER_STOP")
3706
3707 def send_wlanevent(url, uuid, data):
3708     conn = httplib.HTTPConnection(url.netloc)
3709     payload = '''<?xml version="1.0" encoding="utf-8"?>
3710 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
3711 <e:property><STAStatus>1</STAStatus></e:property>
3712 <e:property><APStatus>1</APStatus></e:property>
3713 <e:property><WLANEvent>'''
3714     payload += base64.b64encode(data)
3715     payload += '</WLANEvent></e:property></e:propertyset>'
3716     headers = { "Content-type": 'text/xml; charset="utf-8"',
3717                 "Server": "Unspecified, UPnP/1.0, Unspecified",
3718                 "HOST": url.netloc,
3719                 "NT": "upnp:event",
3720                 "SID": "uuid:" + uuid,
3721                 "SEQ": "0",
3722                 "Content-Length": str(len(payload)) }
3723     conn.request("NOTIFY", url.path, payload, headers)
3724     resp = conn.getresponse()
3725     if resp.status != 200:
3726         raise Exception("Unexpected HTTP response: %d" % resp.status)
3727
3728 def test_ap_wps_er_http_proto(dev, apdev):
3729     """WPS ER HTTP protocol testing"""
3730     try:
3731         _test_ap_wps_er_http_proto(dev, apdev)
3732     finally:
3733         dev[0].request("WPS_ER_STOP")
3734
3735 def _test_ap_wps_er_http_proto(dev, apdev):
3736     uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
3737     server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
3738     global wps_event_url
3739     wps_event_url = None
3740     server.handle_request()
3741     server.handle_request()
3742     server.handle_request()
3743     server.server_close()
3744     if wps_event_url is None:
3745         raise Exception("Did not get event URL")
3746     logger.info("Event URL: " + wps_event_url)
3747
3748     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3749     if ev is None:
3750         raise Exception("No WPS-ER-AP-ADD event")
3751     if uuid not in ev:
3752         raise Exception("UUID mismatch")
3753
3754     sock.close()
3755
3756     logger.info("Valid Probe Request notification")
3757     url = urlparse.urlparse(wps_event_url)
3758     conn = httplib.HTTPConnection(url.netloc)
3759     payload = '''<?xml version="1.0" encoding="utf-8"?>
3760 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
3761 <e:property><STAStatus>1</STAStatus></e:property>
3762 <e:property><APStatus>1</APStatus></e:property>
3763 <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
3764 EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
3765 RGV2aWNlIEEQSQAGADcqAAEg
3766 </WLANEvent></e:property>
3767 </e:propertyset>
3768 '''
3769     headers = { "Content-type": 'text/xml; charset="utf-8"',
3770                 "Server": "Unspecified, UPnP/1.0, Unspecified",
3771                 "HOST": url.netloc,
3772                 "NT": "upnp:event",
3773                 "SID": "uuid:" + uuid,
3774                 "SEQ": "0",
3775                 "Content-Length": str(len(payload)) }
3776     conn.request("NOTIFY", url.path, payload, headers)
3777     resp = conn.getresponse()
3778     if resp.status != 200:
3779         raise Exception("Unexpected HTTP response: %d" % resp.status)
3780
3781     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
3782     if ev is None:
3783         raise Exception("No WPS-ER-ENROLLEE-ADD event")
3784     if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
3785         raise Exception("No Enrollee UUID match")
3786
3787     logger.info("Incorrect event URL AP id")
3788     conn = httplib.HTTPConnection(url.netloc)
3789     conn.request("NOTIFY", url.path + '123', payload, headers)
3790     resp = conn.getresponse()
3791     if resp.status != 404:
3792         raise Exception("Unexpected HTTP response: %d" % resp.status)
3793
3794     logger.info("Missing AP id")
3795     conn = httplib.HTTPConnection(url.netloc)
3796     conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
3797                  payload, headers)
3798     time.sleep(0.1)
3799
3800     logger.info("Incorrect event URL event id")
3801     conn = httplib.HTTPConnection(url.netloc)
3802     conn.request("NOTIFY", '/event/123456789/123', payload, headers)
3803     time.sleep(0.1)
3804
3805     logger.info("Incorrect event URL prefix")
3806     conn = httplib.HTTPConnection(url.netloc)
3807     conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
3808     resp = conn.getresponse()
3809     if resp.status != 404:
3810         raise Exception("Unexpected HTTP response: %d" % resp.status)
3811
3812     logger.info("Unsupported request")
3813     conn = httplib.HTTPConnection(url.netloc)
3814     conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
3815     resp = conn.getresponse()
3816     if resp.status != 501:
3817         raise Exception("Unexpected HTTP response: %d" % resp.status)
3818
3819     logger.info("Unsupported request and OOM")
3820     with alloc_fail(dev[0], 1, "wps_er_http_req"):
3821         conn = httplib.HTTPConnection(url.netloc)
3822         conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
3823         time.sleep(0.5)
3824
3825     logger.info("Too short WLANEvent")
3826     data = '\x00'
3827     send_wlanevent(url, uuid, data)
3828
3829     logger.info("Invalid WLANEventMAC")
3830     data = '\x00qwertyuiopasdfghjklzxcvbnm'
3831     send_wlanevent(url, uuid, data)
3832
3833     logger.info("Unknown WLANEventType")
3834     data = '\xff02:00:00:00:00:00'
3835     send_wlanevent(url, uuid, data)
3836
3837     logger.info("Probe Request notification without any attributes")
3838     data = '\x0102:00:00:00:00:00'
3839     send_wlanevent(url, uuid, data)
3840
3841     logger.info("Probe Request notification with invalid attribute")
3842     data = '\x0102:00:00:00:00:00\xff'
3843     send_wlanevent(url, uuid, data)
3844
3845     logger.info("EAP message without any attributes")
3846     data = '\x0202:00:00:00:00:00'
3847     send_wlanevent(url, uuid, data)
3848
3849     logger.info("EAP message with invalid attribute")
3850     data = '\x0202:00:00:00:00:00\xff'
3851     send_wlanevent(url, uuid, data)
3852
3853     logger.info("EAP message from new STA and not M1")
3854     data = '\x0202:ff:ff:ff:ff:ff' + '\x10\x22\x00\x01\x05'
3855     send_wlanevent(url, uuid, data)
3856
3857     logger.info("EAP message: M1")
3858     data = '\x0202:00:00:00:00:00'
3859     data += '\x10\x22\x00\x01\x04'
3860     data += '\x10\x47\x00\x10' + 16*'\x00'
3861     data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
3862     data += '\x10\x1a\x00\x10' + 16*'\x00'
3863     data += '\x10\x32\x00\xc0' + 192*'\x00'
3864     data += '\x10\x04\x00\x02\x00\x00'
3865     data += '\x10\x10\x00\x02\x00\x00'
3866     data += '\x10\x0d\x00\x01\x00'
3867     data += '\x10\x08\x00\x02\x00\x00'
3868     data += '\x10\x44\x00\x01\x00'
3869     data += '\x10\x21\x00\x00'
3870     data += '\x10\x23\x00\x00'
3871     data += '\x10\x24\x00\x00'
3872     data += '\x10\x42\x00\x00'
3873     data += '\x10\x54\x00\x08' + 8*'\x00'
3874     data += '\x10\x11\x00\x00'
3875     data += '\x10\x3c\x00\x01\x00'
3876     data += '\x10\x02\x00\x02\x00\x00'
3877     data += '\x10\x12\x00\x02\x00\x00'
3878     data += '\x10\x09\x00\x02\x00\x00'
3879     data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
3880     m1 = data
3881     send_wlanevent(url, uuid, data)
3882
3883     logger.info("EAP message: WSC_ACK")
3884     data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0d'
3885     send_wlanevent(url, uuid, data)
3886
3887     logger.info("EAP message: M1")
3888     send_wlanevent(url, uuid, m1)
3889
3890     logger.info("EAP message: WSC_NACK")
3891     data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0e'
3892     send_wlanevent(url, uuid, data)
3893
3894     logger.info("EAP message: M1 - Too long attribute values")
3895     data = '\x0202:00:00:00:00:00'
3896     data += '\x10\x11\x00\x21' + 33*'\x00'
3897     data += '\x10\x45\x00\x21' + 33*'\x00'
3898     data += '\x10\x42\x00\x21' + 33*'\x00'
3899     data += '\x10\x24\x00\x21' + 33*'\x00'
3900     data += '\x10\x23\x00\x21' + 33*'\x00'
3901     data += '\x10\x21\x00\x41' + 65*'\x00'
3902     data += '\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
3903     send_wlanevent(url, uuid, data)
3904
3905     logger.info("EAP message: M1 missing UUID-E")
3906     data = '\x0202:00:00:00:00:00'
3907     data += '\x10\x22\x00\x01\x04'
3908     send_wlanevent(url, uuid, data)
3909
3910     logger.info("EAP message: M1 missing MAC Address")
3911     data += '\x10\x47\x00\x10' + 16*'\x00'
3912     send_wlanevent(url, uuid, data)
3913
3914     logger.info("EAP message: M1 missing Enrollee Nonce")
3915     data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
3916     send_wlanevent(url, uuid, data)
3917
3918     logger.info("EAP message: M1 missing Public Key")
3919     data += '\x10\x1a\x00\x10' + 16*'\x00'
3920     send_wlanevent(url, uuid, data)
3921
3922     logger.info("EAP message: M1 missing Authentication Type flags")
3923     data += '\x10\x32\x00\xc0' + 192*'\x00'
3924     send_wlanevent(url, uuid, data)
3925
3926     logger.info("EAP message: M1 missing Encryption Type Flags")
3927     data += '\x10\x04\x00\x02\x00\x00'
3928     send_wlanevent(url, uuid, data)
3929
3930     logger.info("EAP message: M1 missing Connection Type flags")
3931     data += '\x10\x10\x00\x02\x00\x00'
3932     send_wlanevent(url, uuid, data)
3933
3934     logger.info("EAP message: M1 missing Config Methods")
3935     data += '\x10\x0d\x00\x01\x00'
3936     send_wlanevent(url, uuid, data)
3937
3938     logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
3939     data += '\x10\x08\x00\x02\x00\x00'
3940     send_wlanevent(url, uuid, data)
3941
3942     logger.info("EAP message: M1 missing Manufacturer")
3943     data += '\x10\x44\x00\x01\x00'
3944     send_wlanevent(url, uuid, data)
3945
3946     logger.info("EAP message: M1 missing Model Name")
3947     data += '\x10\x21\x00\x00'
3948     send_wlanevent(url, uuid, data)
3949
3950     logger.info("EAP message: M1 missing Model Number")
3951     data += '\x10\x23\x00\x00'
3952     send_wlanevent(url, uuid, data)
3953
3954     logger.info("EAP message: M1 missing Serial Number")
3955     data += '\x10\x24\x00\x00'
3956     send_wlanevent(url, uuid, data)
3957
3958     logger.info("EAP message: M1 missing Primary Device Type")
3959     data += '\x10\x42\x00\x00'
3960     send_wlanevent(url, uuid, data)
3961
3962     logger.info("EAP message: M1 missing Device Name")
3963     data += '\x10\x54\x00\x08' + 8*'\x00'
3964     send_wlanevent(url, uuid, data)
3965
3966     logger.info("EAP message: M1 missing RF Bands")
3967     data += '\x10\x11\x00\x00'
3968     send_wlanevent(url, uuid, data)
3969
3970     logger.info("EAP message: M1 missing Association State")
3971     data += '\x10\x3c\x00\x01\x00'
3972     send_wlanevent(url, uuid, data)
3973
3974     logger.info("EAP message: M1 missing Device Password ID")
3975     data += '\x10\x02\x00\x02\x00\x00'
3976     send_wlanevent(url, uuid, data)
3977
3978     logger.info("EAP message: M1 missing Configuration Error")
3979     data += '\x10\x12\x00\x02\x00\x00'
3980     send_wlanevent(url, uuid, data)
3981
3982     logger.info("EAP message: M1 missing OS Version")
3983     data += '\x10\x09\x00\x02\x00\x00'
3984     send_wlanevent(url, uuid, data)
3985
3986     logger.info("Check max concurrent requests")
3987     addr = (url.hostname, url.port)
3988     socks = {}
3989     for i in range(20):
3990         socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
3991                                  socket.IPPROTO_TCP)
3992         socks[i].connect(addr)
3993     for i in range(20):
3994         socks[i].send("GET / HTTP/1.1\r\n\r\n")
3995     count = 0
3996     for i in range(20):
3997         try:
3998             res = socks[i].recv(100)
3999             if "HTTP/1" in res:
4000                 count += 1
4001         except:
4002             pass
4003         socks[i].close()
4004     logger.info("%d concurrent HTTP GET operations returned response" % count)
4005     if count < 10:
4006         raise Exception("Too few concurrent HTTP connections accepted")
4007
4008     logger.info("OOM in HTTP server")
4009     for func in [ "http_request_init", "httpread_create",
4010                   "eloop_register_timeout;httpread_create",
4011                   "eloop_register_sock;httpread_create",
4012                   "httpread_hdr_analyze" ]:
4013         with alloc_fail(dev[0], 1, func):
4014             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4015                                  socket.IPPROTO_TCP)
4016             sock.connect(addr)
4017             sock.send("GET / HTTP/1.1\r\n\r\n")
4018             try:
4019                 sock.recv(100)
4020             except:
4021                 pass
4022             sock.close()
4023
4024     logger.info("Invalid HTTP header")
4025     for req in [ " GET / HTTP/1.1\r\n\r\n",
4026                  "HTTP/1.1 200 OK\r\n\r\n",
4027                  "HTTP/\r\n\r\n",
4028                  "GET %%a%aa% HTTP/1.1\r\n\r\n",
4029                  "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4030                  "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4031                  "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4032                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4033                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4034                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4035                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
4036         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4037                              socket.IPPROTO_TCP)
4038         sock.settimeout(0.1)
4039         sock.connect(addr)
4040         sock.send(req)
4041         try:
4042             sock.recv(100)
4043         except:
4044             pass
4045         sock.close()
4046
4047     with alloc_fail(dev[0], 2, "httpread_read_handler"):
4048         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4049                              socket.IPPROTO_TCP)
4050         sock.connect(addr)
4051         sock.send("NOTIFY / HTTP/1.1\r\n\r\n" + 4500*'a')
4052         try:
4053             sock.recv(100)
4054         except:
4055             pass
4056         sock.close()
4057
4058     conn = httplib.HTTPConnection(url.netloc)
4059     payload = '<foo'
4060     headers = { "Content-type": 'text/xml; charset="utf-8"',
4061                 "Server": "Unspecified, UPnP/1.0, Unspecified",
4062                 "HOST": url.netloc,
4063                 "NT": "upnp:event",
4064                 "SID": "uuid:" + uuid,
4065                 "SEQ": "0",
4066                 "Content-Length": str(len(payload)) }
4067     conn.request("NOTIFY", url.path, payload, headers)
4068     resp = conn.getresponse()
4069     if resp.status != 200:
4070         raise Exception("Unexpected HTTP response: %d" % resp.status)
4071
4072     conn = httplib.HTTPConnection(url.netloc)
4073     payload = '<WLANEvent foo></WLANEvent>'
4074     headers = { "Content-type": 'text/xml; charset="utf-8"',
4075                 "Server": "Unspecified, UPnP/1.0, Unspecified",
4076                 "HOST": url.netloc,
4077                 "NT": "upnp:event",
4078                 "SID": "uuid:" + uuid,
4079                 "SEQ": "0",
4080                 "Content-Length": str(len(payload)) }
4081     conn.request("NOTIFY", url.path, payload, headers)
4082     resp = conn.getresponse()
4083     if resp.status != 200:
4084         raise Exception("Unexpected HTTP response: %d" % resp.status)
4085
4086     with alloc_fail(dev[0], 1, "xml_get_first_item"):
4087         send_wlanevent(url, uuid, '')
4088
4089     with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4090         send_wlanevent(url, uuid, 'foo')
4091
4092     for func in [ "wps_init",
4093                   "wps_process_manufacturer",
4094                   "wps_process_model_name",
4095                   "wps_process_model_number",
4096                   "wps_process_serial_number",
4097                   "wps_process_dev_name" ]:
4098         with alloc_fail(dev[0], 1, func):
4099             send_wlanevent(url, uuid, m1)
4100
4101 def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4102     """WPS ER HTTP protocol testing - no eventSubURL"""
4103     class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4104         def handle_upnp_info(self):
4105             self.wfile.write(gen_upnp_info(eventSubURL=None))
4106     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4107                           no_event_url=True)
4108
4109 def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4110     """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
4111     class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4112         def handle_upnp_info(self):
4113             self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4114     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4115                           no_event_url=True)
4116
4117 def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4118     """WPS ER HTTP protocol testing - subscribe OOM"""
4119     try:
4120         _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4121     finally:
4122         dev[0].request("WPS_ER_STOP")
4123
4124 def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4125     tests = [ (1, "http_client_url_parse"),
4126               (1, "wpabuf_alloc;wps_er_subscribe"),
4127               (1, "http_client_addr"),
4128               (1, "eloop_register_sock;http_client_addr"),
4129               (1, "eloop_register_timeout;http_client_addr") ]
4130     for count,func in tests:
4131         with alloc_fail(dev[0], count, func):
4132             server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
4133             server.handle_request()
4134             server.handle_request()
4135             wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
4136
4137 def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4138     """WPS ER HTTP protocol testing - no SID"""
4139     class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4140         def handle_wps_event(self):
4141             self.wfile.write(gen_wps_event(sid=None))
4142     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4143
4144 def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4145     """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4146     class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4147         def handle_wps_event(self):
4148             self.wfile.write(gen_wps_event(sid='FOO'))
4149     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4150
4151 def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4152     """WPS ER HTTP protocol testing - invalid SID UUID"""
4153     class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4154         def handle_wps_event(self):
4155             self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4156     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4157
4158 def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4159     """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4160     class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4161         def handle_wps_event(self):
4162             payload = ""
4163             hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4164                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4165                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4166                   'Connection: close\r\n' + \
4167                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4168                   'Timeout: Second-1801\r\n' + \
4169                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4170             self.wfile.write(hdr + payload)
4171     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4172
4173 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4174     """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4175     class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4176         def handle_wps_event(self):
4177             payload = ""
4178             hdr = 'HTTP/1.1 FOO\r\n' + \
4179                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4180                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4181                   'Connection: close\r\n' + \
4182                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4183                   'Timeout: Second-1801\r\n' + \
4184                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4185             self.wfile.write(hdr + payload)
4186     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4187
4188 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4189     """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4190     class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4191         def handle_wps_control(self):
4192             payload = '''<?xml version="1.0"?>
4193 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4194 <s:Body>
4195 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4196 <NewDeviceInfo>Rk9P</NewDeviceInfo>
4197 </u:GetDeviceInfoResponse>
4198 </s:Body>
4199 </s:Envelope>
4200 '''
4201             self.wfile.write(gen_wps_control(payload_override=payload))
4202     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4203
4204 def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4205     """WPS ER HTTP protocol testing - No device in UPnP info"""
4206     class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4207         def handle_upnp_info(self):
4208             payload = '''<?xml version="1.0"?>
4209 <root xmlns="urn:schemas-upnp-org:device-1-0">
4210 <specVersion>
4211 <major>1</major>
4212 <minor>0</minor>
4213 </specVersion>
4214 </root>
4215 '''
4216             hdr = 'HTTP/1.1 200 OK\r\n' + \
4217                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4218                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4219                   'Connection: close\r\n' + \
4220                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4221                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4222             self.wfile.write(hdr + payload)
4223     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4224
4225 def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4226     """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4227     class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4228         def handle_upnp_info(self):
4229             payload = '''<?xml version="1.0"?>
4230 <root xmlns="urn:schemas-upnp-org:device-1-0">
4231 <specVersion>
4232 <major>1</major>
4233 <minor>0</minor>
4234 </specVersion>
4235 <device>
4236 </device>
4237 </root>
4238 '''
4239             hdr = 'HTTP/1.1 200 OK\r\n' + \
4240                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4241                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4242                   'Connection: close\r\n' + \
4243                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4244                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4245             self.wfile.write(hdr + payload)
4246     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4247
4248 def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4249     """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4250     class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4251         def handle_upnp_info(self):
4252             self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4253     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4254
4255 def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4256     """WPS ER HTTP protocol testing - no controlURL"""
4257     class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4258         def handle_upnp_info(self):
4259             self.wfile.write(gen_upnp_info(controlURL=None))
4260     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4261                           no_event_url=True)
4262
4263 def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4264     """WPS ER HTTP protocol testing - DNS name in controlURL"""
4265     class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4266         def handle_upnp_info(self):
4267             self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4268     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4269                           no_event_url=True)
4270
4271 def test_ap_wps_http_timeout(dev, apdev):
4272     """WPS AP/ER and HTTP timeout"""
4273     try:
4274         _test_ap_wps_http_timeout(dev, apdev)
4275     finally:
4276         dev[0].request("WPS_ER_STOP")
4277
4278 def _test_ap_wps_http_timeout(dev, apdev):
4279     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4280     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
4281
4282     location = ssdp_get_location(ap_uuid)
4283     url = urlparse.urlparse(location)
4284     addr = (url.hostname, url.port)
4285     logger.debug("Open HTTP connection to hostapd, but do not complete request")
4286     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4287                          socket.IPPROTO_TCP)
4288     sock.connect(addr)
4289     sock.send("G")
4290
4291     class DummyServer(SocketServer.StreamRequestHandler):
4292         def handle(self):
4293             logger.debug("DummyServer - start 31 sec wait")
4294             time.sleep(31)
4295             logger.debug("DummyServer - wait done")
4296
4297     logger.debug("Start WPS ER")
4298     server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4299                                 wait_m_search=True)
4300
4301     logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4302     # This will wait for 31 seconds..
4303     server.handle_request()
4304
4305     logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4306     try:
4307         sock.send("ET / HTTP/1.1\r\n\r\n")
4308         res = sock.recv(100)
4309         sock.close()
4310     except:
4311         pass
4312
4313 def test_ap_wps_er_url_parse(dev, apdev):
4314     """WPS ER and URL parsing special cases"""
4315     try:
4316         _test_ap_wps_er_url_parse(dev, apdev)
4317     finally:
4318         dev[0].request("WPS_ER_STOP")
4319
4320 def _test_ap_wps_er_url_parse(dev, apdev):
4321     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4322     sock.settimeout(1)
4323     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4324     sock.bind(("239.255.255.250", 1900))
4325     dev[0].request("WPS_ER_START ifname=lo")
4326     (msg,addr) = sock.recvfrom(1000)
4327     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4328     if "M-SEARCH" not in msg:
4329         raise Exception("Not an M-SEARCH")
4330     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1\r\ncache-control:max-age=1\r\n\r\n", addr)
4331     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4332     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1/:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
4333     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4334     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://255.255.255.255:0/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
4335     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4336
4337     sock.close()
4338
4339 def test_ap_wps_er_link_update(dev, apdev):
4340     """WPS ER and link update special cases"""
4341     class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4342         def handle_upnp_info(self):
4343             self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4344     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4345
4346     class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4347         def handle_others(self, data):
4348             if "GET / " in data:
4349                 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4350     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4351                           location_url='http://127.0.0.1:12345')
4352
4353 def test_ap_wps_er_http_client(dev, apdev):
4354     """WPS ER and HTTP client special cases"""
4355     with alloc_fail(dev[0], 1, "http_link_update"):
4356         run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4357
4358     with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4359         run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4360
4361     with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4362         run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4363
4364     class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4365         def handle_upnp_info(self):
4366             self.wfile.write("GET / HTTP/1.1\r\n\r\n")
4367     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4368                           no_event_url=True)
4369
4370 def test_ap_wps_init_oom(dev, apdev):
4371     """wps_init OOM cases"""
4372     ssid = "test-wps"
4373     appin = "12345670"
4374     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4375                "ap_pin": appin }
4376     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4377     pin = dev[0].wps_read_pin()
4378
4379     with alloc_fail(hapd, 1, "wps_init"):
4380         hapd.request("WPS_PIN any " + pin)
4381         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4382         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4383         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4384         if ev is None:
4385             raise Exception("No EAP failure reported")
4386         dev[0].request("WPS_CANCEL")
4387
4388     with alloc_fail(dev[0], 2, "wps_init"):
4389         hapd.request("WPS_PIN any " + pin)
4390         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4391         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4392         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4393         if ev is None:
4394             raise Exception("No EAP failure reported")
4395         dev[0].request("WPS_CANCEL")
4396
4397     with alloc_fail(dev[0], 2, "wps_init"):
4398         hapd.request("WPS_PBC")
4399         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4400         dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4401         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4402         if ev is None:
4403             raise Exception("No EAP failure reported")
4404         dev[0].request("WPS_CANCEL")
4405
4406     dev[0].dump_monitor()
4407     new_ssid = "wps-new-ssid"
4408     new_passphrase = "1234567890"
4409     with alloc_fail(dev[0], 3, "wps_init"):
4410         dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4411                        new_passphrase, no_wait=True)
4412         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4413         if ev is None:
4414             raise Exception("No EAP failure reported")
4415
4416     dev[0].flush_scan_cache()
4417
4418 def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4419     """WPS and invalid IE in Association Request frame"""
4420     ssid = "test-wps"
4421     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4422     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4423     pin = "12345670"
4424     hapd.request("WPS_PIN any " + pin)
4425     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4426     try:
4427         dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4428         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4429         for i in range(5):
4430             ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4431             if ev and "vendor=14122" in ev:
4432                 break
4433         if ev is None or "vendor=14122" not in ev:
4434             raise Exception("EAP-WSC not started")
4435         dev[0].request("WPS_CANCEL")
4436     finally:
4437         dev[0].request("VENDOR_ELEM_REMOVE 13 *")
4438
4439 def test_ap_wps_pbc_pin_mismatch(dev, apdev):
4440     """WPS PBC/PIN mismatch"""
4441     ssid = "test-wps"
4442     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4443     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4444     hapd.request("SET wps_version_number 0x10")
4445     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4446     hapd.request("WPS_PBC")
4447     pin = dev[0].wps_read_pin()
4448     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4449     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4450     if ev is None:
4451         raise Exception("Scan did not complete")
4452     dev[0].request("WPS_CANCEL")
4453
4454     hapd.request("WPS_CANCEL")
4455     dev[0].flush_scan_cache()
4456
4457 def test_ap_wps_ie_invalid(dev, apdev):
4458     """WPS PIN attempt with AP that has invalid WSC IE"""
4459     ssid = "test-wps"
4460     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4461                "vendor_elements": "dd050050f20410" }
4462     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4463     params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
4464     hostapd.add_ap(apdev[1]['ifname'], params)
4465     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4466     pin = dev[0].wps_read_pin()
4467     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4468     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4469     if ev is None:
4470         raise Exception("Scan did not complete")
4471     dev[0].request("WPS_CANCEL")
4472
4473 def test_ap_wps_scan_prio_order(dev, apdev):
4474     """WPS scan priority ordering"""
4475     ssid = "test-wps"
4476     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4477     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4478     params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
4479     hostapd.add_ap(apdev[1]['ifname'], params)
4480     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4481     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4482     pin = dev[0].wps_read_pin()
4483     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4484     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4485     if ev is None:
4486         raise Exception("Scan did not complete")
4487     dev[0].request("WPS_CANCEL")
4488
4489 def test_ap_wps_probe_req_ie_oom(dev, apdev):
4490     """WPS ProbeReq IE OOM"""
4491     ssid = "test-wps"
4492     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4493     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4494     pin = dev[0].wps_read_pin()
4495     hapd.request("WPS_PIN any " + pin)
4496     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4497     with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
4498         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4499         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4500         if ev is None:
4501             raise Exception("Association not seen")
4502     dev[0].request("WPS_CANCEL")
4503
4504     with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
4505         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4506         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4507         if ev is None:
4508             raise Exception("Association not seen")
4509     dev[0].request("WPS_CANCEL")
4510
4511 def test_ap_wps_assoc_req_ie_oom(dev, apdev):
4512     """WPS AssocReq IE OOM"""
4513     ssid = "test-wps"
4514     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4515     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4516     pin = dev[0].wps_read_pin()
4517     hapd.request("WPS_PIN any " + pin)
4518     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4519     with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
4520         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4521         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4522         if ev is None:
4523             raise Exception("Association not seen")
4524     dev[0].request("WPS_CANCEL")
4525
4526 def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
4527     """WPS AssocResp IE OOM"""
4528     ssid = "test-wps"
4529     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4530     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4531     pin = dev[0].wps_read_pin()
4532     hapd.request("WPS_PIN any " + pin)
4533     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4534     with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
4535         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4536         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4537         if ev is None:
4538             raise Exception("Association not seen")
4539     dev[0].request("WPS_CANCEL")
4540
4541 def test_ap_wps_bss_info_errors(dev, apdev):
4542     """WPS BSS info errors"""
4543     params = { "ssid": "1",
4544                "vendor_elements": "dd0e0050f20410440001ff101100010a" }
4545     hostapd.add_ap(apdev[0]['ifname'], params)
4546     params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
4547     hostapd.add_ap(apdev[1]['ifname'], params)
4548     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4549     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4550     bss = dev[0].get_bss(apdev[0]['bssid'])
4551     logger.info("BSS: " + str(bss))
4552     if "wps_state" in bss:
4553         raise Exception("Unexpected wps_state in BSS info")
4554     if 'wps_device_name' not in bss:
4555         raise Exception("No wps_device_name in BSS info")
4556     if bss['wps_device_name'] != '_':
4557         raise Exception("Unexpected wps_device_name value")
4558     bss = dev[0].get_bss(apdev[1]['bssid'])
4559     logger.info("BSS: " + str(bss))
4560
4561     with alloc_fail(dev[0], 1, "=wps_attr_text"):
4562         bss = dev[0].get_bss(apdev[0]['bssid'])
4563         logger.info("BSS(OOM): " + str(bss))
4564
4565 def wps_run_pbc_fail_ap(apdev, dev, hapd):
4566     hapd.request("WPS_PBC")
4567     dev.scan_for_bss(apdev['bssid'], freq="2412")
4568     dev.request("WPS_PBC " + apdev['bssid'])
4569     ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4570     if ev is None:
4571         raise Exception("No EAP failure reported")
4572     dev.request("WPS_CANCEL")
4573     dev.wait_disconnected()
4574     for i in range(5):
4575         try:
4576             dev.flush_scan_cache()
4577             break
4578         except Exception, e:
4579             if str(e).startswith("Failed to trigger scan"):
4580                 # Try again
4581                 time.sleep(1)
4582             else:
4583                 raise
4584
4585 def wps_run_pbc_fail(apdev, dev):
4586     hapd = wps_start_ap(apdev)
4587     wps_run_pbc_fail_ap(apdev, dev, hapd)
4588
4589 def test_ap_wps_pk_oom(dev, apdev):
4590     """WPS and public key OOM"""
4591     with alloc_fail(dev[0], 1, "wps_build_public_key"):
4592         wps_run_pbc_fail(apdev[0], dev[0])
4593
4594 def test_ap_wps_pk_oom_ap(dev, apdev):
4595     """WPS and public key OOM on AP"""
4596     hapd = wps_start_ap(apdev[0])
4597     with alloc_fail(hapd, 1, "wps_build_public_key"):
4598         wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4599
4600 def test_ap_wps_encr_oom_ap(dev, apdev):
4601     """WPS and encrypted settings decryption OOM on AP"""
4602     hapd = wps_start_ap(apdev[0])
4603     pin = dev[0].wps_read_pin()
4604     hapd.request("WPS_PIN any " + pin)
4605     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4606     with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
4607         dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
4608         ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
4609         if ev is None:
4610             raise Exception("No WPS-FAIL reported")
4611         dev[0].request("WPS_CANCEL")
4612     dev[0].wait_disconnected()
4613
4614 def test_ap_wps_encr_no_random_ap(dev, apdev):
4615     """WPS and no random data available for encryption on AP"""
4616     hapd = wps_start_ap(apdev[0])
4617     with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
4618         wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4619
4620 def test_ap_wps_e_hash_no_random_sta(dev, apdev):
4621     """WPS and no random data available for e-hash on STA"""
4622     with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
4623         wps_run_pbc_fail(apdev[0], dev[0])
4624
4625 def test_ap_wps_m1_no_random(dev, apdev):
4626     """WPS and no random for M1 on STA"""
4627     with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
4628         wps_run_pbc_fail(apdev[0], dev[0])
4629
4630 def test_ap_wps_m1_oom(dev, apdev):
4631     """WPS and OOM for M1 on STA"""
4632     with alloc_fail(dev[0], 1, "wps_build_m1"):
4633         wps_run_pbc_fail(apdev[0], dev[0])
4634
4635 def test_ap_wps_m3_oom(dev, apdev):
4636     """WPS and OOM for M3 on STA"""
4637     with alloc_fail(dev[0], 1, "wps_build_m3"):
4638         wps_run_pbc_fail(apdev[0], dev[0])
4639
4640 def test_ap_wps_m5_oom(dev, apdev):
4641     """WPS and OOM for M5 on STA"""
4642     hapd = wps_start_ap(apdev[0])
4643     hapd.request("WPS_PBC")
4644     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4645     for i in range(1, 3):
4646         with alloc_fail(dev[0], i, "wps_build_m5"):
4647             dev[0].request("WPS_PBC " + apdev[0]['bssid'])
4648             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4649             if ev is None:
4650                 raise Exception("No EAP failure reported")
4651             dev[0].request("WPS_CANCEL")
4652             dev[0].wait_disconnected()
4653     dev[0].flush_scan_cache()
4654
4655 def test_ap_wps_m5_no_random(dev, apdev):
4656     """WPS and no random for M5 on STA"""
4657     with fail_test(dev[0], 1,
4658                    "os_get_random;wps_build_encr_settings;wps_build_m5"):
4659         wps_run_pbc_fail(apdev[0], dev[0])
4660
4661 def test_ap_wps_m7_oom(dev, apdev):
4662     """WPS and OOM for M7 on STA"""
4663     hapd = wps_start_ap(apdev[0])
4664     hapd.request("WPS_PBC")
4665     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4666     for i in range(1, 3):
4667         with alloc_fail(dev[0], i, "wps_build_m7"):
4668             dev[0].request("WPS_PBC " + apdev[0]['bssid'])
4669             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4670             if ev is None:
4671                 raise Exception("No EAP failure reported")
4672             dev[0].request("WPS_CANCEL")
4673             dev[0].wait_disconnected()
4674     dev[0].flush_scan_cache()
4675
4676 def test_ap_wps_m7_no_random(dev, apdev):
4677     """WPS and no random for M7 on STA"""
4678     with fail_test(dev[0], 1,
4679                    "os_get_random;wps_build_encr_settings;wps_build_m7"):
4680         wps_run_pbc_fail(apdev[0], dev[0])
4681
4682 def test_ap_wps_wsc_done_oom(dev, apdev):
4683     """WPS and OOM for WSC_Done on STA"""
4684     with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
4685         wps_run_pbc_fail(apdev[0], dev[0])
4686
4687 def test_ap_wps_random_psk_fail(dev, apdev):
4688     """WPS and no random for PSK on AP"""
4689     ssid = "test-wps"
4690     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
4691     appin = "12345670"
4692     try:
4693         os.remove(pskfile)
4694     except:
4695         pass
4696
4697     try:
4698         with open(pskfile, "w") as f:
4699             f.write("# WPA PSKs\n")
4700
4701         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4702                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
4703                    "rsn_pairwise": "CCMP", "ap_pin": appin,
4704                    "wpa_psk_file": pskfile }
4705         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4706
4707         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4708         with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
4709             dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
4710             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4711             if ev is None:
4712                 raise Exception("No EAP failure reported")
4713             dev[0].request("WPS_CANCEL")
4714         dev[0].wait_disconnected()
4715
4716         with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
4717             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4718
4719         with alloc_fail(hapd, 1, "wps_build_cred"):
4720             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4721
4722         with alloc_fail(hapd, 2, "wps_build_cred"):
4723             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4724     finally:
4725         os.remove(pskfile)
4726
4727 def wps_ext_eap_identity_req(dev, hapd, bssid):
4728     logger.debug("EAP-Identity/Request")
4729     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
4730     if ev is None:
4731         raise Exception("Timeout on EAPOL-TX from hostapd")
4732     res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
4733     if "OK" not in res:
4734         raise Exception("EAPOL_RX to wpa_supplicant failed")
4735
4736 def wps_ext_eap_identity_resp(hapd, dev, addr):
4737     ev = dev.wait_event(["EAPOL-TX"], timeout=10)
4738     if ev is None:
4739         raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
4740     res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
4741     if "OK" not in res:
4742         raise Exception("EAPOL_RX to hostapd failed")
4743
4744 def wps_ext_eap_wsc(dst, src, src_addr, msg):
4745     logger.debug(msg)
4746     ev = src.wait_event(["EAPOL-TX"], timeout=10)
4747     if ev is None:
4748         raise Exception("Timeout on EAPOL-TX")
4749     res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
4750     if "OK" not in res:
4751         raise Exception("EAPOL_RX failed")
4752
4753 def wps_start_ext(apdev, dev, pbc=False):
4754     addr = dev.own_addr()
4755     bssid = apdev['bssid']
4756     ssid = "test-wps-conf"
4757     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4758                "wpa_passphrase": "12345678", "wpa": "2",
4759                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
4760     hapd = hostapd.add_ap(apdev['ifname'], params)
4761
4762     if pbc:
4763         hapd.request("WPS_PBC")
4764     else:
4765         pin = dev.wps_read_pin()
4766         hapd.request("WPS_PIN any " + pin)
4767     dev.scan_for_bss(bssid, freq="2412")
4768     hapd.request("SET ext_eapol_frame_io 1")
4769     dev.request("SET ext_eapol_frame_io 1")
4770
4771     if pbc:
4772         dev.request("WPS_PBC " + bssid)
4773     else:
4774         dev.request("WPS_PIN " + bssid + " " + pin)
4775     return addr,bssid,hapd
4776
4777 def wps_auth_corrupt(dst, src, addr):
4778     ev = src.wait_event(["EAPOL-TX"], timeout=10)
4779     if ev is None:
4780         raise Exception("Timeout on EAPOL-TX")
4781     src.request("SET ext_eapol_frame_io 0")
4782     dst.request("SET ext_eapol_frame_io 0")
4783     msg = ev.split(' ')[2]
4784     if msg[-24:-16] != '10050008':
4785         raise Exception("Could not find Authenticator attribute")
4786     # Corrupt Authenticator value
4787     msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
4788     res = dst.request("EAPOL_RX " + addr + " " + msg)
4789     if "OK" not in res:
4790         raise Exception("EAPOL_RX failed")
4791
4792 def wps_fail_finish(hapd, dev, fail_str):
4793     ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
4794     if ev is None:
4795         raise Exception("WPS-FAIL not indicated")
4796     if fail_str not in ev:
4797         raise Exception("Unexpected WPS-FAIL value: " + ev)
4798     dev.request("WPS_CANCEL")
4799     dev.wait_disconnected()
4800
4801 def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
4802     wps_auth_corrupt(dev, hapd, bssid)
4803     wps_fail_finish(hapd, dev, fail_str)
4804
4805 def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
4806     wps_auth_corrupt(hapd, dev, addr)
4807     wps_fail_finish(hapd, dev, fail_str)
4808
4809 def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
4810     """WPS and Authenticator attribute mismatch in M2"""
4811     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4812     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4813     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4814     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4815     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4816     logger.debug("M2")
4817     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
4818
4819 def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
4820     """WPS and Authenticator attribute mismatch in M3"""
4821     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4822     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4823     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4824     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4825     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4826     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4827     logger.debug("M3")
4828     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
4829
4830 def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
4831     """WPS and Authenticator attribute mismatch in M4"""
4832     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4833     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4834     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4835     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4836     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4837     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4838     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4839     logger.debug("M4")
4840     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
4841
4842 def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
4843     """WPS and Authenticator attribute mismatch in M5"""
4844     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4845     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4846     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4847     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4848     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4849     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4850     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4851     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
4852     logger.debug("M5")
4853     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
4854
4855 def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
4856     """WPS and Authenticator attribute mismatch in M6"""
4857     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4858     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4859     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4860     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4861     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4862     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4863     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4864     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
4865     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
4866     logger.debug("M6")
4867     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
4868
4869 def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
4870     """WPS and Authenticator attribute mismatch in M7"""
4871     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4872     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4873     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4874     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4875     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4876     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4877     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4878     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
4879     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
4880     wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
4881     logger.debug("M7")
4882     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
4883
4884 def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
4885     """WPS and Authenticator attribute mismatch in M8"""
4886     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4887     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4888     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4889     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4890     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4891     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4892     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4893     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
4894     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
4895     wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
4896     wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
4897     logger.debug("M8")
4898     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
4899
4900 def test_ap_wps_authenticator_missing_m2(dev, apdev):
4901     """WPS and Authenticator attribute missing from M2"""
4902     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4903     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4904     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4905     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4906     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4907     logger.debug("M2")
4908     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
4909     if ev is None:
4910         raise Exception("Timeout on EAPOL-TX")
4911     hapd.request("SET ext_eapol_frame_io 0")
4912     dev[0].request("SET ext_eapol_frame_io 0")
4913     msg = ev.split(' ')[2]
4914     if msg[-24:-16] != '10050008':
4915         raise Exception("Could not find Authenticator attribute")
4916     # Remove Authenticator value
4917     msg = msg[:-24]
4918     mlen = "%04x" % (int(msg[4:8], 16) - 12)
4919     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
4920     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
4921     if "OK" not in res:
4922         raise Exception("EAPOL_RX failed")
4923     wps_fail_finish(hapd, dev[0], "msg=5")
4924
4925 def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
4926     """WPS and M2 with different Device Password ID (P2P)"""
4927     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4928     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4929     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4930     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4931     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4932     logger.debug("M2")
4933     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
4934     if ev is None:
4935         raise Exception("Timeout on EAPOL-TX")
4936     hapd.request("SET ext_eapol_frame_io 0")
4937     dev[0].request("SET ext_eapol_frame_io 0")
4938     msg = ev.split(' ')[2]
4939     if msg[722:730] != '10120002':
4940         raise Exception("Could not find Device Password ID attribute")
4941     # Replace Device Password ID value. This will fail Authenticator check, but
4942     # allows the code path in wps_process_dev_pw_id() to be checked from debug
4943     # log.
4944     msg = msg[0:730] + "0005" + msg[734:]
4945     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
4946     if "OK" not in res:
4947         raise Exception("EAPOL_RX failed")
4948     wps_fail_finish(hapd, dev[0], "msg=5")
4949
4950 def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
4951     """WPS and M2 with different Device Password ID (PIN to PBC)"""
4952     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4953     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4954     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4955     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4956     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4957     logger.debug("M2")
4958     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
4959     if ev is None:
4960         raise Exception("Timeout on EAPOL-TX")
4961     hapd.request("SET ext_eapol_frame_io 0")
4962     dev[0].request("SET ext_eapol_frame_io 0")
4963     msg = ev.split(' ')[2]
4964     if msg[722:730] != '10120002':
4965         raise Exception("Could not find Device Password ID attribute")
4966     # Replace Device Password ID value (PIN --> PBC). This will be rejected.
4967     msg = msg[0:730] + "0004" + msg[734:]
4968     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
4969     if "OK" not in res:
4970         raise Exception("EAPOL_RX failed")
4971     wps_fail_finish(hapd, dev[0], "msg=5")
4972
4973 def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
4974     """WPS and M2 with different Device Password ID (PBC to PIN)"""
4975     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
4976     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4977     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4978     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4979     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4980     logger.debug("M2")
4981     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
4982     if ev is None:
4983         raise Exception("Timeout on EAPOL-TX")
4984     hapd.request("SET ext_eapol_frame_io 0")
4985     dev[0].request("SET ext_eapol_frame_io 0")
4986     msg = ev.split(' ')[2]
4987     if msg[722:730] != '10120002':
4988         raise Exception("Could not find Device Password ID attribute")
4989     # Replace Device Password ID value. This will fail Authenticator check, but
4990     # allows the code path in wps_process_dev_pw_id() to be checked from debug
4991     # log.
4992     msg = msg[0:730] + "0000" + msg[734:]
4993     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
4994     if "OK" not in res:
4995         raise Exception("EAPOL_RX failed")
4996     wps_fail_finish(hapd, dev[0], "msg=5")
4997     dev[0].flush_scan_cache()
4998
4999 def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5000     """WPS and M2 without Device Password ID"""
5001     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5002     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5003     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5004     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5005     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5006     logger.debug("M2")
5007     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5008     if ev is None:
5009         raise Exception("Timeout on EAPOL-TX")
5010     hapd.request("SET ext_eapol_frame_io 0")
5011     dev[0].request("SET ext_eapol_frame_io 0")
5012     msg = ev.split(' ')[2]
5013     if msg[722:730] != '10120002':
5014         raise Exception("Could not find Device Password ID attribute")
5015     # Remove Device Password ID value. This will fail Authenticator check, but
5016     # allows the code path in wps_process_dev_pw_id() to be checked from debug
5017     # log.
5018     mlen = "%04x" % (int(msg[4:8], 16) - 6)
5019     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5020     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5021     if "OK" not in res:
5022         raise Exception("EAPOL_RX failed")
5023     wps_fail_finish(hapd, dev[0], "msg=5")
5024
5025 def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5026     """WPS and M2 without Registrar Nonce"""
5027     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5028     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5029     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5030     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5031     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5032     logger.debug("M2")
5033     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5034     if ev is None:
5035         raise Exception("Timeout on EAPOL-TX")
5036     hapd.request("SET ext_eapol_frame_io 0")
5037     dev[0].request("SET ext_eapol_frame_io 0")
5038     msg = ev.split(' ')[2]
5039     if msg[96:104] != '10390010':
5040         raise Exception("Could not find Registrar Nonce attribute")
5041     # Remove Registrar Nonce. This will fail Authenticator check, but
5042     # allows the code path in wps_process_registrar_nonce() to be checked from
5043     # the debug log.
5044     mlen = "%04x" % (int(msg[4:8], 16) - 20)
5045     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5046     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5047     if "OK" not in res:
5048         raise Exception("EAPOL_RX failed")
5049     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5050     if ev is None:
5051         raise Exception("Disconnect event not seen")
5052     dev[0].request("WPS_CANCEL")
5053     dev[0].flush_scan_cache()
5054
5055 def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5056     """WPS and M2 without Enrollee Nonce"""
5057     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5058     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5059     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5060     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5061     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5062     logger.debug("M2")
5063     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5064     if ev is None:
5065         raise Exception("Timeout on EAPOL-TX")
5066     hapd.request("SET ext_eapol_frame_io 0")
5067     dev[0].request("SET ext_eapol_frame_io 0")
5068     msg = ev.split(' ')[2]
5069     if msg[56:64] != '101a0010':
5070         raise Exception("Could not find enrollee Nonce attribute")
5071     # Remove Enrollee Nonce. This will fail Authenticator check, but
5072     # allows the code path in wps_process_enrollee_nonce() to be checked from
5073     # the debug log.
5074     mlen = "%04x" % (int(msg[4:8], 16) - 20)
5075     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5076     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5077     if "OK" not in res:
5078         raise Exception("EAPOL_RX failed")
5079     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5080     if ev is None:
5081         raise Exception("Disconnect event not seen")
5082     dev[0].request("WPS_CANCEL")
5083     dev[0].flush_scan_cache()
5084
5085 def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5086     """WPS and M2 without UUID-R"""
5087     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5088     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5089     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5090     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5091     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5092     logger.debug("M2")
5093     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5094     if ev is None:
5095         raise Exception("Timeout on EAPOL-TX")
5096     hapd.request("SET ext_eapol_frame_io 0")
5097     dev[0].request("SET ext_eapol_frame_io 0")
5098     msg = ev.split(' ')[2]
5099     if msg[136:144] != '10480010':
5100         raise Exception("Could not find enrollee Nonce attribute")
5101     # Remove UUID-R. This will fail Authenticator check, but allows the code
5102     # path in wps_process_uuid_r() to be checked from the debug log.
5103     mlen = "%04x" % (int(msg[4:8], 16) - 20)
5104     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5105     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5106     if "OK" not in res:
5107         raise Exception("EAPOL_RX failed")
5108     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5109     if ev is None:
5110         raise Exception("Disconnect event not seen")
5111     dev[0].request("WPS_CANCEL")
5112     dev[0].flush_scan_cache()
5113
5114 def test_ap_wps_m2_invalid(dev, apdev):
5115     """WPS and M2 parsing failure"""
5116     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5117     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5118     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5119     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5120     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5121     logger.debug("M2")
5122     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5123     if ev is None:
5124         raise Exception("Timeout on EAPOL-TX")
5125     hapd.request("SET ext_eapol_frame_io 0")
5126     dev[0].request("SET ext_eapol_frame_io 0")
5127     msg = ev.split(' ')[2]
5128     if msg[136:144] != '10480010':
5129         raise Exception("Could not find enrollee Nonce attribute")
5130     # Remove UUID-R. This will fail Authenticator check, but allows the code
5131     # path in wps_process_uuid_r() to be checked from the debug log.
5132     mlen = "%04x" % (int(msg[4:8], 16) - 1)
5133     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5134     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5135     if "OK" not in res:
5136         raise Exception("EAPOL_RX failed")
5137     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5138     if ev is None:
5139         raise Exception("Disconnect event not seen")
5140     dev[0].request("WPS_CANCEL")
5141     dev[0].flush_scan_cache()
5142
5143 def test_ap_wps_m2_missing_msg_type(dev, apdev):
5144     """WPS and M2 without Message Type"""
5145     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5146     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5147     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5148     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5149     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5150     logger.debug("M2")
5151     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5152     if ev is None:
5153         raise Exception("Timeout on EAPOL-TX")
5154     hapd.request("SET ext_eapol_frame_io 0")
5155     dev[0].request("SET ext_eapol_frame_io 0")
5156     msg = ev.split(' ')[2]
5157     if msg[46:54] != '10220001':
5158         raise Exception("Could not find Message Type attribute")
5159     # Remove Message Type. This will fail Authenticator check, but allows the
5160     # code path in wps_process_wsc_msg() to be checked from the debug log.
5161     mlen = "%04x" % (int(msg[4:8], 16) - 5)
5162     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5163     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5164     if "OK" not in res:
5165         raise Exception("EAPOL_RX failed")
5166     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5167     if ev is None:
5168         raise Exception("Disconnect event not seen")
5169     dev[0].request("WPS_CANCEL")
5170     dev[0].flush_scan_cache()
5171
5172 def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5173     """WPS and M2 but unknown Message Type"""
5174     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5175     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5176     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5177     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5178     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5179     logger.debug("M2")
5180     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5181     if ev is None:
5182         raise Exception("Timeout on EAPOL-TX")
5183     hapd.request("SET ext_eapol_frame_io 0")
5184     dev[0].request("SET ext_eapol_frame_io 0")
5185     msg = ev.split(' ')[2]
5186     if msg[46:54] != '10220001':
5187         raise Exception("Could not find Message Type attribute")
5188     # Replace Message Type value. This will be rejected.
5189     msg = msg[0:54] + "00" + msg[56:]
5190     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5191     if "OK" not in res:
5192         raise Exception("EAPOL_RX failed")
5193     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5194     if ev is None:
5195         raise Exception("Disconnect event not seen")
5196     dev[0].request("WPS_CANCEL")
5197     dev[0].flush_scan_cache()
5198
5199 def test_ap_wps_m2_unknown_opcode(dev, apdev):
5200     """WPS and M2 but unknown opcode"""
5201     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5202     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5203     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5204     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5205     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5206     logger.debug("M2")
5207     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5208     if ev is None:
5209         raise Exception("Timeout on EAPOL-TX")
5210     hapd.request("SET ext_eapol_frame_io 0")
5211     dev[0].request("SET ext_eapol_frame_io 0")
5212     msg = ev.split(' ')[2]
5213     # Replace opcode. This will be discarded in EAP-WSC processing.
5214     msg = msg[0:32] + "00" + msg[34:]
5215     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5216     if "OK" not in res:
5217         raise Exception("EAPOL_RX failed")
5218     dev[0].request("WPS_CANCEL")
5219     dev[0].wait_disconnected()
5220     dev[0].flush_scan_cache()
5221
5222 def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5223     """WPS and M2 but unknown opcode (WSC_Start)"""
5224     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5225     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5226     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5227     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5228     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5229     logger.debug("M2")
5230     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5231     if ev is None:
5232         raise Exception("Timeout on EAPOL-TX")
5233     hapd.request("SET ext_eapol_frame_io 0")
5234     dev[0].request("SET ext_eapol_frame_io 0")
5235     msg = ev.split(' ')[2]
5236     # Replace opcode. This will be discarded in EAP-WSC processing.
5237     msg = msg[0:32] + "01" + msg[34:]
5238     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5239     if "OK" not in res:
5240         raise Exception("EAPOL_RX failed")
5241     dev[0].request("WPS_CANCEL")
5242     dev[0].wait_disconnected()
5243     dev[0].flush_scan_cache()
5244
5245 def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5246     """WPS and M2 but unknown opcode (WSC_Done)"""
5247     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5248     wps_ext_eap_identity_req(dev[0], hapd, bssid)
5249     wps_ext_eap_identity_resp(hapd, dev[0], addr)
5250     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5251     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5252     logger.debug("M2")
5253     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5254     if ev is None:
5255         raise Exception("Timeout on EAPOL-TX")
5256     hapd.request("SET ext_eapol_frame_io 0")
5257     dev[0].request("SET ext_eapol_frame_io 0")
5258     msg = ev.split(' ')[2]
5259     # Replace opcode. This will be discarded in WPS Enrollee processing.
5260     msg = msg[0:32] + "05" + msg[34:]
5261     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5262     if "OK" not in res:
5263         raise Exception("EAPOL_RX failed")
5264     dev[0].request("WPS_CANCEL")
5265     dev[0].wait_disconnected()
5266     dev[0].flush_scan_cache()
5267
5268 def wps_m2_but_other(dev, apdev, title, msgtype):
5269     addr,bssid,hapd = wps_start_ext(apdev, dev)
5270     wps_ext_eap_identity_req(dev, hapd, bssid)
5271     wps_ext_eap_identity_resp(hapd, dev, addr)
5272     wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5273     wps_ext_eap_wsc(hapd, dev, addr, "M1")
5274     logger.debug(title)
5275     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5276     if ev is None:
5277         raise Exception("Timeout on EAPOL-TX")
5278     hapd.request("SET ext_eapol_frame_io 0")
5279     dev.request("SET ext_eapol_frame_io 0")
5280     msg = ev.split(' ')[2]
5281     if msg[46:54] != '10220001':
5282         raise Exception("Could not find Message Type attribute")
5283     # Replace Message Type value. This will be rejected.
5284     msg = msg[0:54] + msgtype + msg[56:]
5285     res = dev.request("EAPOL_RX " + bssid + " " + msg)
5286     if "OK" not in res:
5287         raise Exception("EAPOL_RX failed")
5288     ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5289     if ev is None:
5290         raise Exception("WPS-FAIL event not seen")
5291     dev.request("WPS_CANCEL")
5292     dev.wait_disconnected()
5293
5294 def wps_m4_but_other(dev, apdev, title, msgtype):
5295     addr,bssid,hapd = wps_start_ext(apdev, dev)
5296     wps_ext_eap_identity_req(dev, hapd, bssid)
5297     wps_ext_eap_identity_resp(hapd, dev, addr)
5298     wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5299     wps_ext_eap_wsc(hapd, dev, addr, "M1")
5300     wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5301     wps_ext_eap_wsc(hapd, dev, addr, "M3")
5302     logger.debug(title)
5303     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5304     if ev is None:
5305         raise Exception("Timeout on EAPOL-TX")
5306     hapd.request("SET ext_eapol_frame_io 0")
5307     dev.request("SET ext_eapol_frame_io 0")
5308     msg = ev.split(' ')[2]
5309     if msg[46:54] != '10220001':
5310         raise Exception("Could not find Message Type attribute")
5311     # Replace Message Type value. This will be rejected.
5312     msg = msg[0:54] + msgtype + msg[56:]
5313     res = dev.request("EAPOL_RX " + bssid + " " + msg)
5314     if "OK" not in res:
5315         raise Exception("EAPOL_RX failed")
5316     ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5317     if ev is None:
5318         raise Exception("WPS-FAIL event not seen")
5319     dev.request("WPS_CANCEL")
5320     dev.wait_disconnected()
5321
5322 def test_ap_wps_m2_msg_type_m4(dev, apdev):
5323     """WPS and M2 but Message Type M4"""
5324     wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5325
5326 def test_ap_wps_m2_msg_type_m6(dev, apdev):
5327     """WPS and M2 but Message Type M6"""
5328     wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5329
5330 def test_ap_wps_m2_msg_type_m8(dev, apdev):
5331     """WPS and M2 but Message Type M8"""
5332     wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5333
5334 def test_ap_wps_m4_msg_type_m2(dev, apdev):
5335     """WPS and M4 but Message Type M2"""
5336     wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5337
5338 def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5339     """WPS and M4 but Message Type M2D"""
5340     wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5341
5342 def test_ap_wps_config_methods(dev, apdev):
5343     """WPS configuration method parsing"""
5344     ssid = "test-wps-conf"
5345     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5346                "wpa_passphrase": "12345678", "wpa": "2",
5347                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5348                "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
5349     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
5350     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5351                "wpa_passphrase": "12345678", "wpa": "2",
5352                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5353                "config_methods": "display push_button" }
5354     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
5355
5356 def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5357     """WPS UPnP SetSelectedRegistrar protocol testing"""
5358     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5359     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
5360
5361     location = ssdp_get_location(ap_uuid)
5362     urls = upnp_get_urls(location)
5363     eventurl = urlparse.urlparse(urls['event_sub_url'])
5364     ctrlurl = urlparse.urlparse(urls['control_url'])
5365     url = urlparse.urlparse(location)
5366     conn = httplib.HTTPConnection(url.netloc)
5367
5368     class WPSERHTTPServer(SocketServer.StreamRequestHandler):
5369         def handle(self):
5370             data = self.rfile.readline().strip()
5371             logger.debug(data)
5372             self.wfile.write(gen_wps_event())
5373
5374     server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5375     server.timeout = 1
5376
5377     headers = { "callback": '<http://127.0.0.1:12345/event>',
5378                 "NT": "upnp:event",
5379                 "timeout": "Second-1234" }
5380     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5381     resp = conn.getresponse()
5382     if resp.status != 200:
5383         raise Exception("Unexpected HTTP response: %d" % resp.status)
5384     sid = resp.getheader("sid")
5385     logger.debug("Subscription SID " + sid)
5386     server.handle_request()
5387
5388     tests = [ (500, "10"),
5389               (200, "104a000110" + "1041000101" + "101200020000" +
5390                "105300023148" +
5391                "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5392                "10480010362db47ba53a519188fb5458b986b2e4"),
5393               (200, "104a000110" + "1041000100" + "101200020000" +
5394                "105300020000"),
5395               (200, "104a000110" + "1041000100"),
5396               (200, "104a000110") ]
5397     for status,test in tests:
5398         tlvs = binascii.unhexlify(test)
5399         newmsg = base64.b64encode(tlvs)
5400         msg = '<?xml version="1.0"?>\n'
5401         msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5402         msg += '<s:Body>'
5403         msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5404         msg += '<NewMessage>'
5405         msg += newmsg
5406         msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
5407         headers = { "Content-type": 'text/xml; charset="utf-8"' }
5408         headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
5409         conn.request("POST", ctrlurl.path, msg, headers)
5410         resp = conn.getresponse()
5411         if resp.status != status:
5412             raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
5413
5414 def test_ap_wps_adv_oom(dev, apdev):
5415     """WPS AP and advertisement OOM"""
5416     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5417     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
5418
5419     with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
5420         ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5421                           no_recv=True)
5422         time.sleep(0.2)
5423
5424     with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
5425         ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5426                           no_recv=True)
5427         time.sleep(0.2)
5428
5429     with alloc_fail(hapd, 1,
5430                     "next_advertisement;advertisement_state_machine_stop"):
5431         hapd.disable()
5432
5433     with alloc_fail(hapd, 1, "ssdp_listener_start"):
5434         if "FAIL" not in hapd.request("ENABLE"):
5435             raise Exception("ENABLE succeeded during OOM")
5436
5437 def test_wps_config_methods(dev):
5438     """WPS config method update"""
5439     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
5440     wpas.interface_add("wlan5")
5441     if "OK" not in wpas.request("SET config_methods display label"):
5442         raise Exception("Failed to set config_methods")
5443     if wpas.request("GET config_methods").strip() != "display label":
5444         raise Exception("config_methods were not updated")
5445     if "OK" not in wpas.request("SET config_methods "):
5446         raise Exception("Failed to clear config_methods")
5447     if wpas.request("GET config_methods").strip() != "":
5448         raise Exception("config_methods were not cleared")