tests: AP configuration using wps_config and wps_cred_processing=2
[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_add_enrollee_pbc(dev, apdev):
1120     """WPS ER connected to AP and adding a new enrollee using PBC"""
1121     try:
1122         _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1123     finally:
1124         dev[0].request("WPS_ER_STOP")
1125
1126 def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1127     ssid = "wps-er-add-enrollee-pbc"
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                      "config_methods": "label push_button",
1139                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1140     logger.info("Learn AP configuration")
1141     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1142     dev[0].dump_monitor()
1143     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1144     status = dev[0].get_status()
1145     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1146         raise Exception("Not fully connected")
1147
1148     logger.info("Start ER")
1149     dev[0].request("WPS_ER_START ifname=lo")
1150     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1151     if ev is None:
1152         raise Exception("AP discovery timed out")
1153     if ap_uuid not in ev:
1154         raise Exception("Expected AP UUID not found")
1155
1156     enrollee = dev[1].p2p_interface_addr()
1157
1158     if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1159         raise Exception("Unknown UUID not reported")
1160
1161     logger.info("Add Enrollee using ER and PBC")
1162     dev[0].dump_monitor()
1163     dev[1].dump_monitor()
1164     dev[1].request("WPS_PBC")
1165
1166     for i in range(0, 2):
1167         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1168         if ev is None:
1169             raise Exception("Enrollee discovery timed out")
1170         if enrollee in ev:
1171             break
1172         if i == 1:
1173             raise Exception("Expected Enrollee not found")
1174     if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1175         raise Exception("Unknown UUID not reported")
1176     logger.info("Use learned network configuration on ER")
1177     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1178     if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1179         raise Exception("WPS_ER_PBC failed")
1180
1181     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1182     if ev is None:
1183         raise Exception("Enrollee did not report success")
1184     dev[1].wait_connected(timeout=15)
1185     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1186     if ev is None:
1187         raise Exception("WPS ER did not report success")
1188     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1189
1190 def test_ap_wps_er_pbc_overlap(dev, apdev):
1191     """WPS ER connected to AP and PBC session overlap"""
1192     try:
1193         _test_ap_wps_er_pbc_overlap(dev, apdev)
1194     finally:
1195         dev[0].request("WPS_ER_STOP")
1196
1197 def _test_ap_wps_er_pbc_overlap(dev, apdev):
1198     ssid = "wps-er-add-enrollee-pbc"
1199     ap_pin = "12345670"
1200     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1201     hostapd.add_ap(apdev[0]['ifname'],
1202                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1203                      "wpa_passphrase": "12345678", "wpa": "2",
1204                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1205                      "device_name": "Wireless AP", "manufacturer": "Company",
1206                      "model_name": "WAP", "model_number": "123",
1207                      "serial_number": "12345", "device_type": "6-0050F204-1",
1208                      "os_version": "01020300",
1209                      "config_methods": "label push_button",
1210                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1211     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1212     dev[0].dump_monitor()
1213     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1214
1215     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1216     dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1217     # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1218     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1219
1220     dev[0].dump_monitor()
1221     dev[0].request("WPS_ER_START ifname=lo")
1222
1223     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1224     if ev is None:
1225         raise Exception("AP discovery timed out")
1226     if ap_uuid not in ev:
1227         raise Exception("Expected AP UUID not found")
1228
1229     # verify BSSID selection of the AP instead of UUID
1230     if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1231         raise Exception("Could not select AP based on BSSID")
1232
1233     dev[0].dump_monitor()
1234     dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1235     dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1236     ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1237     if ev is None:
1238         raise Exception("PBC scan failed")
1239     ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1240     if ev is None:
1241         raise Exception("PBC scan failed")
1242     found1 = False
1243     found2 = False
1244     addr1 = dev[1].own_addr()
1245     addr2 = dev[2].own_addr()
1246     for i in range(3):
1247         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1248         if ev is None:
1249             raise Exception("Enrollee discovery timed out")
1250         if addr1 in ev:
1251             found1 = True
1252             if found2:
1253                 break
1254         if addr2 in ev:
1255             found2 = True
1256             if found1:
1257                 break
1258     if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1259         raise Exception("PBC overlap not reported")
1260     dev[1].request("WPS_CANCEL")
1261     dev[2].request("WPS_CANCEL")
1262     if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1263         raise Exception("Invalid WPS_ER_PBC accepted")
1264
1265 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1266     """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
1267     try:
1268         _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1269     finally:
1270         dev[0].request("WPS_ER_STOP")
1271
1272 def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1273     ssid = "wps-er-add-enrollee-pbc"
1274     ap_pin = "12345670"
1275     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1276     hostapd.add_ap(apdev[0]['ifname'],
1277                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1278                      "wpa_passphrase": "12345678", "wpa": "2",
1279                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1280                      "device_name": "Wireless AP", "manufacturer": "Company",
1281                      "model_name": "WAP", "model_number": "123",
1282                      "serial_number": "12345", "device_type": "6-0050F204-1",
1283                      "os_version": "01020300",
1284                      "config_methods": "label push_button",
1285                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1286     logger.info("Learn AP configuration")
1287     dev[0].request("SET wps_version_number 0x10")
1288     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1289     dev[0].dump_monitor()
1290     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1291     status = dev[0].get_status()
1292     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1293         raise Exception("Not fully connected")
1294
1295     logger.info("Start ER")
1296     dev[0].request("WPS_ER_START ifname=lo")
1297     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1298     if ev is None:
1299         raise Exception("AP discovery timed out")
1300     if ap_uuid not in ev:
1301         raise Exception("Expected AP UUID not found")
1302
1303     logger.info("Use learned network configuration on ER")
1304     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1305
1306     logger.info("Add Enrollee using ER and PIN")
1307     enrollee = dev[1].p2p_interface_addr()
1308     pin = dev[1].wps_read_pin()
1309     dev[0].dump_monitor()
1310     dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1311     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1312     dev[1].dump_monitor()
1313     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1314     dev[1].wait_connected(timeout=30)
1315     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1316     if ev is None:
1317         raise Exception("WPS ER did not report success")
1318
1319 def test_ap_wps_er_config_ap(dev, apdev):
1320     """WPS ER configuring AP over UPnP"""
1321     try:
1322         _test_ap_wps_er_config_ap(dev, apdev)
1323     finally:
1324         dev[0].request("WPS_ER_STOP")
1325
1326 def _test_ap_wps_er_config_ap(dev, apdev):
1327     ssid = "wps-er-ap-config"
1328     ap_pin = "12345670"
1329     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1330     hostapd.add_ap(apdev[0]['ifname'],
1331                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1332                      "wpa_passphrase": "12345678", "wpa": "2",
1333                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1334                      "device_name": "Wireless AP", "manufacturer": "Company",
1335                      "model_name": "WAP", "model_number": "123",
1336                      "serial_number": "12345", "device_type": "6-0050F204-1",
1337                      "os_version": "01020300",
1338                      "config_methods": "label push_button",
1339                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1340
1341     logger.info("Connect ER to the AP")
1342     dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1343
1344     logger.info("WPS configuration step")
1345     dev[0].request("WPS_ER_START ifname=lo")
1346     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1347     if ev is None:
1348         raise Exception("AP discovery timed out")
1349     if ap_uuid not in ev:
1350         raise Exception("Expected AP UUID not found")
1351     new_passphrase = "1234567890"
1352     dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1353                    ssid.encode("hex") + " WPA2PSK CCMP " +
1354                    new_passphrase.encode("hex"))
1355     ev = dev[0].wait_event(["WPS-SUCCESS"])
1356     if ev is None:
1357         raise Exception("WPS ER configuration operation timed out")
1358     dev[0].wait_disconnected(timeout=10)
1359     dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1360
1361     logger.info("WPS ER restart")
1362     dev[0].request("WPS_ER_START")
1363     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1364     if ev is None:
1365         raise Exception("AP discovery timed out on ER restart")
1366     if ap_uuid not in ev:
1367         raise Exception("Expected AP UUID not found on ER restart")
1368     if "OK" not in dev[0].request("WPS_ER_STOP"):
1369         raise Exception("WPS_ER_STOP failed")
1370     if "OK" not in dev[0].request("WPS_ER_STOP"):
1371         raise Exception("WPS_ER_STOP failed")
1372
1373 def test_ap_wps_er_cache_ap_settings(dev, apdev):
1374     """WPS ER caching AP settings"""
1375     try:
1376         _test_ap_wps_er_cache_ap_settings(dev, apdev)
1377     finally:
1378         dev[0].request("WPS_ER_STOP")
1379
1380 def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1381     ssid = "wps-er-add-enrollee"
1382     ap_pin = "12345670"
1383     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1384     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1385                "wpa_passphrase": "12345678", "wpa": "2",
1386                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1387                "device_name": "Wireless AP", "manufacturer": "Company",
1388                "model_name": "WAP", "model_number": "123",
1389                "serial_number": "12345", "device_type": "6-0050F204-1",
1390                "os_version": "01020300",
1391                "config_methods": "label push_button",
1392                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1393     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1394     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1395     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1396     id = int(dev[0].list_networks()[0]['id'])
1397     dev[0].set_network(id, "scan_freq", "2412")
1398
1399     dev[0].request("WPS_ER_START ifname=lo")
1400     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1401     if ev is None:
1402         raise Exception("AP discovery timed out")
1403     if ap_uuid not in ev:
1404         raise Exception("Expected AP UUID not found")
1405
1406     dev[0].dump_monitor()
1407     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1408     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1409     if ev is None:
1410         raise Exception("AP learn timed out")
1411     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1412     if ev is None:
1413         raise Exception("WPS-FAIL after AP learn timed out")
1414     time.sleep(0.1)
1415
1416     hapd.disable()
1417
1418     for i in range(2):
1419         ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1420                                  "CTRL-EVENT-DISCONNECTED" ],
1421                                timeout=15)
1422         if ev is None:
1423             raise Exception("AP removal or disconnection timed out")
1424
1425     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1426     for i in range(2):
1427         ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1428                                timeout=15)
1429         if ev is None:
1430             raise Exception("AP discovery or connection timed out")
1431
1432     pin = dev[1].wps_read_pin()
1433     dev[0].dump_monitor()
1434     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1435
1436     time.sleep(0.2)
1437
1438     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1439     dev[1].dump_monitor()
1440     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1441     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1442     if ev is None:
1443         raise Exception("Enrollee did not report success")
1444     dev[1].wait_connected(timeout=15)
1445     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1446     if ev is None:
1447         raise Exception("WPS ER did not report success")
1448
1449     dev[0].dump_monitor()
1450     dev[0].request("WPS_ER_STOP")
1451
1452 def test_ap_wps_fragmentation(dev, apdev):
1453     """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1454     ssid = "test-wps-fragmentation"
1455     appin = "12345670"
1456     hostapd.add_ap(apdev[0]['ifname'],
1457                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1458                      "wpa_passphrase": "12345678", "wpa": "3",
1459                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1460                      "wpa_pairwise": "TKIP", "ap_pin": appin,
1461                      "fragment_size": "50" })
1462     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1463     logger.info("WPS provisioning step (PBC)")
1464     hapd.request("WPS_PBC")
1465     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1466     dev[0].dump_monitor()
1467     dev[0].request("SET wps_fragment_size 50")
1468     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1469     dev[0].wait_connected(timeout=30)
1470     status = dev[0].get_status()
1471     if status['wpa_state'] != 'COMPLETED':
1472         raise Exception("Not fully connected")
1473     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1474         raise Exception("Unexpected encryption configuration")
1475     if status['key_mgmt'] != 'WPA2-PSK':
1476         raise Exception("Unexpected key_mgmt")
1477
1478     logger.info("WPS provisioning step (PIN)")
1479     pin = dev[1].wps_read_pin()
1480     hapd.request("WPS_PIN any " + pin)
1481     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1482     dev[1].request("SET wps_fragment_size 50")
1483     dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1484     dev[1].wait_connected(timeout=30)
1485     status = dev[1].get_status()
1486     if status['wpa_state'] != 'COMPLETED':
1487         raise Exception("Not fully connected")
1488     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1489         raise Exception("Unexpected encryption configuration")
1490     if status['key_mgmt'] != 'WPA2-PSK':
1491         raise Exception("Unexpected key_mgmt")
1492
1493     logger.info("WPS connection as registrar")
1494     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1495     dev[2].request("SET wps_fragment_size 50")
1496     dev[2].wps_reg(apdev[0]['bssid'], appin)
1497     status = dev[2].get_status()
1498     if status['wpa_state'] != 'COMPLETED':
1499         raise Exception("Not fully connected")
1500     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1501         raise Exception("Unexpected encryption configuration")
1502     if status['key_mgmt'] != 'WPA2-PSK':
1503         raise Exception("Unexpected key_mgmt")
1504
1505 def test_ap_wps_new_version_sta(dev, apdev):
1506     """WPS compatibility with new version number on the station"""
1507     ssid = "test-wps-ver"
1508     hostapd.add_ap(apdev[0]['ifname'],
1509                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1510                      "wpa_passphrase": "12345678", "wpa": "2",
1511                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1512     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1513     logger.info("WPS provisioning step")
1514     hapd.request("WPS_PBC")
1515     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1516     dev[0].dump_monitor()
1517     dev[0].request("SET wps_version_number 0x43")
1518     dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
1519     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1520     dev[0].wait_connected(timeout=30)
1521
1522 def test_ap_wps_new_version_ap(dev, apdev):
1523     """WPS compatibility with new version number on the AP"""
1524     ssid = "test-wps-ver"
1525     hostapd.add_ap(apdev[0]['ifname'],
1526                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1527                      "wpa_passphrase": "12345678", "wpa": "2",
1528                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1529     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1530     logger.info("WPS provisioning step")
1531     if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1532         raise Exception("Failed to enable test functionality")
1533     hapd.request("WPS_PBC")
1534     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1535     dev[0].dump_monitor()
1536     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1537     dev[0].wait_connected(timeout=30)
1538     hapd.request("SET wps_version_number 0x20")
1539
1540 def test_ap_wps_check_pin(dev, apdev):
1541     """Verify PIN checking through control interface"""
1542     hostapd.add_ap(apdev[0]['ifname'],
1543                    { "ssid": "wps", "eap_server": "1", "wps_state": "2",
1544                      "wpa_passphrase": "12345678", "wpa": "2",
1545                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1546     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1547     for t in [ ("12345670", "12345670"),
1548                ("12345678", "FAIL-CHECKSUM"),
1549                ("12345", "FAIL"),
1550                ("123456789", "FAIL"),
1551                ("1234-5670", "12345670"),
1552                ("1234 5670", "12345670"),
1553                ("1-2.3:4 5670", "12345670") ]:
1554         res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1555         res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1556         if res != res2:
1557             raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
1558         if res != t[1]:
1559             raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
1560
1561     if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
1562         raise Exception("Unexpected WPS_CHECK_PIN success")
1563     if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
1564         raise Exception("Unexpected WPS_CHECK_PIN success")
1565
1566     for i in range(0, 10):
1567         pin = dev[0].request("WPS_PIN get")
1568         rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
1569         if pin != rpin:
1570             raise Exception("Random PIN validation failed for " + pin)
1571
1572 def test_ap_wps_wep_config(dev, apdev):
1573     """WPS 2.0 AP rejecting WEP configuration"""
1574     ssid = "test-wps-config"
1575     appin = "12345670"
1576     hostapd.add_ap(apdev[0]['ifname'],
1577                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1578                      "ap_pin": appin})
1579     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1580     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1581     dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
1582                    "hello", no_wait=True)
1583     ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
1584     if ev is None:
1585         raise Exception("WPS-FAIL timed out")
1586     if "reason=2" not in ev:
1587         raise Exception("Unexpected reason code in WPS-FAIL")
1588     status = hapd.request("WPS_GET_STATUS")
1589     if "Last WPS result: Failed" not in status:
1590         raise Exception("WPS failure result not shown correctly")
1591     if "Failure Reason: WEP Prohibited" not in status:
1592         raise Exception("Failure reason not reported correctly")
1593     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
1594         raise Exception("Peer address not shown correctly")
1595
1596 def test_ap_wps_wep_enroll(dev, apdev):
1597     """WPS 2.0 STA rejecting WEP configuration"""
1598     ssid = "test-wps-wep"
1599     hostapd.add_ap(apdev[0]['ifname'],
1600                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1601                      "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
1602     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1603     hapd.request("WPS_PBC")
1604     dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1605     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1606     ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1607     if ev is None:
1608         raise Exception("WPS-FAIL event timed out")
1609     if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
1610         raise Exception("Unexpected WPS-FAIL event: " + ev)
1611
1612 def test_ap_wps_ie_fragmentation(dev, apdev):
1613     """WPS AP using fragmented WPS IE"""
1614     ssid = "test-wps-ie-fragmentation"
1615     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1616                "wpa_passphrase": "12345678", "wpa": "2",
1617                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1618                "device_name": "1234567890abcdef1234567890abcdef",
1619                "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1620                "model_name": "1234567890abcdef1234567890abcdef",
1621                "model_number": "1234567890abcdef1234567890abcdef",
1622                "serial_number": "1234567890abcdef1234567890abcdef" }
1623     hostapd.add_ap(apdev[0]['ifname'], params)
1624     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1625     hapd.request("WPS_PBC")
1626     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1627     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1628     dev[0].wait_connected(timeout=30)
1629     bss = dev[0].get_bss(apdev[0]['bssid'])
1630     if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1631         logger.info("Device Name not received correctly")
1632         logger.info(bss)
1633         # This can fail if Probe Response frame is missed and Beacon frame was
1634         # used to fill in the BSS entry. This can happen, e.g., during heavy
1635         # load every now and then and is not really an error, so try to
1636         # workaround by runnign another scan.
1637         dev[0].scan(freq="2412", only_new=True)
1638         bss = dev[0].get_bss(apdev[0]['bssid'])
1639         if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1640             logger.info(bss)
1641             raise Exception("Device Name not received correctly")
1642     if len(re.findall("dd..0050f204", bss['ie'])) != 2:
1643         raise Exception("Unexpected number of WPS IEs")
1644
1645 def get_psk(pskfile):
1646     psks = {}
1647     with open(pskfile, "r") as f:
1648         lines = f.read().splitlines()
1649         for l in lines:
1650             if l == "# WPA PSKs":
1651                 continue
1652             (addr,psk) = l.split(' ')
1653             psks[addr] = psk
1654     return psks
1655
1656 def test_ap_wps_per_station_psk(dev, apdev):
1657     """WPS PBC provisioning with per-station PSK"""
1658     addr0 = dev[0].own_addr()
1659     addr1 = dev[1].own_addr()
1660     addr2 = dev[2].own_addr()
1661     ssid = "wps"
1662     appin = "12345670"
1663     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1664     try:
1665         os.remove(pskfile)
1666     except:
1667         pass
1668
1669     try:
1670         with open(pskfile, "w") as f:
1671             f.write("# WPA PSKs\n")
1672
1673         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1674                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1675                    "rsn_pairwise": "CCMP", "ap_pin": appin,
1676                    "wpa_psk_file": pskfile }
1677         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1678
1679         logger.info("First enrollee")
1680         hapd.request("WPS_PBC")
1681         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1682         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1683         dev[0].wait_connected(timeout=30)
1684
1685         logger.info("Second enrollee")
1686         hapd.request("WPS_PBC")
1687         dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1688         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1689         dev[1].wait_connected(timeout=30)
1690
1691         logger.info("External registrar")
1692         dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1693         dev[2].wps_reg(apdev[0]['bssid'], appin)
1694
1695         logger.info("Verifying PSK results")
1696         psks = get_psk(pskfile)
1697         if addr0 not in psks:
1698             raise Exception("No PSK recorded for sta0")
1699         if addr1 not in psks:
1700             raise Exception("No PSK recorded for sta1")
1701         if addr2 not in psks:
1702             raise Exception("No PSK recorded for sta2")
1703         if psks[addr0] == psks[addr1]:
1704             raise Exception("Same PSK recorded for sta0 and sta1")
1705         if psks[addr0] == psks[addr2]:
1706             raise Exception("Same PSK recorded for sta0 and sta2")
1707         if psks[addr1] == psks[addr2]:
1708             raise Exception("Same PSK recorded for sta1 and sta2")
1709
1710         dev[0].request("REMOVE_NETWORK all")
1711         logger.info("Second external registrar")
1712         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1713         dev[0].wps_reg(apdev[0]['bssid'], appin)
1714         psks2 = get_psk(pskfile)
1715         if addr0 not in psks2:
1716             raise Exception("No PSK recorded for sta0(reg)")
1717         if psks[addr0] == psks2[addr0]:
1718             raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
1719     finally:
1720         os.remove(pskfile)
1721
1722 def test_ap_wps_per_station_psk_failure(dev, apdev):
1723     """WPS PBC provisioning with per-station PSK (file not writable)"""
1724     addr0 = dev[0].p2p_dev_addr()
1725     addr1 = dev[1].p2p_dev_addr()
1726     addr2 = dev[2].p2p_dev_addr()
1727     ssid = "wps"
1728     appin = "12345670"
1729     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1730     try:
1731         os.remove(pskfile)
1732     except:
1733         pass
1734
1735     try:
1736         with open(pskfile, "w") as f:
1737             f.write("# WPA PSKs\n")
1738
1739         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1740                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1741                    "rsn_pairwise": "CCMP", "ap_pin": appin,
1742                    "wpa_psk_file": pskfile }
1743         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1744         if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
1745             raise Exception("Failed to set wpa_psk_file")
1746
1747         logger.info("First enrollee")
1748         hapd.request("WPS_PBC")
1749         dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1750         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1751         dev[0].wait_connected(timeout=30)
1752
1753         logger.info("Second enrollee")
1754         hapd.request("WPS_PBC")
1755         dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1756         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1757         dev[1].wait_connected(timeout=30)
1758
1759         logger.info("External registrar")
1760         dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1761         dev[2].wps_reg(apdev[0]['bssid'], appin)
1762
1763         logger.info("Verifying PSK results")
1764         psks = get_psk(pskfile)
1765         if len(psks) > 0:
1766             raise Exception("PSK recorded unexpectedly")
1767     finally:
1768         os.remove(pskfile)
1769
1770 def test_ap_wps_pin_request_file(dev, apdev):
1771     """WPS PIN provisioning with configured AP"""
1772     ssid = "wps"
1773     pinfile = "/tmp/ap_wps_pin_request_file.log"
1774     if os.path.exists(pinfile):
1775         os.remove(pinfile)
1776     hostapd.add_ap(apdev[0]['ifname'],
1777                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1778                      "wps_pin_requests": pinfile,
1779                      "wpa_passphrase": "12345678", "wpa": "2",
1780                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1781     hapd = hostapd.Hostapd(apdev[0]['ifname'])
1782     uuid = dev[0].get_status_field("uuid")
1783     pin = dev[0].wps_read_pin()
1784     try:
1785         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1786         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1787         ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
1788         if ev is None:
1789             raise Exception("PIN needed event not shown")
1790         if uuid not in ev:
1791             raise Exception("UUID mismatch")
1792         dev[0].request("WPS_CANCEL")
1793         success = False
1794         with open(pinfile, "r") as f:
1795             lines = f.readlines()
1796             for l in lines:
1797                 if uuid in l:
1798                     success = True
1799                     break
1800         if not success:
1801             raise Exception("PIN request entry not in the log file")
1802     finally:
1803         try:
1804             os.remove(pinfile)
1805         except:
1806             pass
1807
1808 def test_ap_wps_auto_setup_with_config_file(dev, apdev):
1809     """WPS auto-setup with configuration file"""
1810     conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
1811     ifname = apdev[0]['ifname']
1812     try:
1813         with open(conffile, "w") as f:
1814             f.write("driver=nl80211\n")
1815             f.write("hw_mode=g\n")
1816             f.write("channel=1\n")
1817             f.write("ieee80211n=1\n")
1818             f.write("interface=%s\n" % ifname)
1819             f.write("ctrl_interface=/var/run/hostapd\n")
1820             f.write("ssid=wps\n")
1821             f.write("eap_server=1\n")
1822             f.write("wps_state=1\n")
1823         hostapd.add_bss('phy3', ifname, conffile)
1824         hapd = hostapd.Hostapd(ifname)
1825         hapd.request("WPS_PBC")
1826         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1827         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1828         dev[0].wait_connected(timeout=30)
1829         with open(conffile, "r") as f:
1830             lines = f.read().splitlines()
1831             vals = dict()
1832             for l in lines:
1833                 try:
1834                     [name,value] = l.split('=', 1)
1835                     vals[name] = value
1836                 except ValueError, e:
1837                     if "# WPS configuration" in l:
1838                         pass
1839                     else:
1840                         raise Exception("Unexpected configuration line: " + l)
1841         if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
1842             raise Exception("Incorrect configuration: " + str(vals))
1843     finally:
1844         try:
1845             os.remove(conffile)
1846         except:
1847             pass
1848
1849 def test_ap_wps_pbc_timeout(dev, apdev, params):
1850     """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
1851     if not params['long']:
1852         raise HwsimSkip("Skip test case with long duration due to --long not specified")
1853     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1854     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1855
1856     location = ssdp_get_location(ap_uuid)
1857     urls = upnp_get_urls(location)
1858     eventurl = urlparse.urlparse(urls['event_sub_url'])
1859     ctrlurl = urlparse.urlparse(urls['control_url'])
1860
1861     url = urlparse.urlparse(location)
1862     conn = httplib.HTTPConnection(url.netloc)
1863
1864     class WPSERHTTPServer(SocketServer.StreamRequestHandler):
1865         def handle(self):
1866             data = self.rfile.readline().strip()
1867             logger.debug(data)
1868             self.wfile.write(gen_wps_event())
1869
1870     server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
1871     server.timeout = 1
1872
1873     headers = { "callback": '<http://127.0.0.1:12345/event>',
1874                 "NT": "upnp:event",
1875                 "timeout": "Second-1234" }
1876     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1877     resp = conn.getresponse()
1878     if resp.status != 200:
1879         raise Exception("Unexpected HTTP response: %d" % resp.status)
1880     sid = resp.getheader("sid")
1881     logger.debug("Subscription SID " + sid)
1882
1883     msg = '''<?xml version="1.0"?>
1884 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
1885 <s:Body>
1886 <u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
1887 <NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
1888 VFi5hrLk
1889 </NewMessage>
1890 </u:SetSelectedRegistrar>
1891 </s:Body>
1892 </s:Envelope>'''
1893     headers = { "Content-type": 'text/xml; charset="utf-8"' }
1894     headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
1895     conn.request("POST", ctrlurl.path, msg, headers)
1896     resp = conn.getresponse()
1897     if resp.status != 200:
1898         raise Exception("Unexpected HTTP response: %d" % resp.status)
1899
1900     server.handle_request()
1901
1902     logger.info("Start WPS_PBC and wait for PBC walk time expiration")
1903     if "OK" not in dev[0].request("WPS_PBC"):
1904         raise Exception("WPS_PBC failed")
1905
1906     start = os.times()[4]
1907
1908     server.handle_request()
1909     dev[1].request("BSS_FLUSH 0")
1910     dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
1911                         only_new=True)
1912     bss = dev[1].get_bss(apdev[0]['bssid'])
1913     logger.debug("BSS: " + str(bss))
1914     if '[WPS-AUTH]' not in bss['flags']:
1915         raise Exception("WPS not indicated authorized")
1916
1917     server.handle_request()
1918
1919     wps_timeout_seen = False
1920
1921     while True:
1922         hapd.dump_monitor()
1923         dev[1].dump_monitor()
1924         if not wps_timeout_seen:
1925             ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
1926             if ev is not None:
1927                 logger.info("PBC timeout seen")
1928                 wps_timeout_seen = True
1929         else:
1930             dev[0].dump_monitor()
1931         now = os.times()[4]
1932         if now - start > 130:
1933             raise Exception("Selected registration information not removed")
1934         dev[1].request("BSS_FLUSH 0")
1935         dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
1936                             only_new=True)
1937         bss = dev[1].get_bss(apdev[0]['bssid'])
1938         logger.debug("BSS: " + str(bss))
1939         if '[WPS-AUTH]' not in bss['flags']:
1940             break
1941         server.handle_request()
1942
1943     server.server_close()
1944
1945     if wps_timeout_seen:
1946         return
1947
1948     now = os.times()[4]
1949     if now < start + 150:
1950         dur = start + 150 - now
1951     else:
1952         dur = 1
1953     logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
1954     ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
1955     if ev is None:
1956         raise Exception("WPS-TIMEOUT not reported")
1957
1958 def add_ssdp_ap(ifname, ap_uuid):
1959     ssid = "wps-ssdp"
1960     ap_pin = "12345670"
1961     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1962                "wpa_passphrase": "12345678", "wpa": "2",
1963                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1964                "device_name": "Wireless AP", "manufacturer": "Company",
1965                "model_name": "WAP", "model_number": "123",
1966                "serial_number": "12345", "device_type": "6-0050F204-1",
1967                "os_version": "01020300",
1968                "config_methods": "label push_button",
1969                "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
1970                "friendly_name": "WPS Access Point",
1971                "manufacturer_url": "http://www.example.com/",
1972                "model_description": "Wireless Access Point",
1973                "model_url": "http://www.example.com/model/",
1974                "upc": "123456789012" }
1975     return hostapd.add_ap(ifname, params)
1976
1977 def ssdp_send(msg, no_recv=False):
1978     socket.setdefaulttimeout(1)
1979     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1980     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1981     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1982     sock.bind(("127.0.0.1", 0))
1983     sock.sendto(msg, ("239.255.255.250", 1900))
1984     if no_recv:
1985         return None
1986     return sock.recv(1000)
1987
1988 def ssdp_send_msearch(st, no_recv=False):
1989     msg = '\r\n'.join([
1990             'M-SEARCH * HTTP/1.1',
1991             'HOST: 239.255.255.250:1900',
1992             'MX: 1',
1993             'MAN: "ssdp:discover"',
1994             'ST: ' + st,
1995             '', ''])
1996     return ssdp_send(msg, no_recv=no_recv)
1997
1998 def test_ap_wps_ssdp_msearch(dev, apdev):
1999     """WPS AP and SSDP M-SEARCH messages"""
2000     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2001     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2002
2003     msg = '\r\n'.join([
2004             'M-SEARCH * HTTP/1.1',
2005             'Host: 239.255.255.250:1900',
2006             'Mx: 1',
2007             'Man: "ssdp:discover"',
2008             'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2009             '', ''])
2010     ssdp_send(msg)
2011
2012     msg = '\r\n'.join([
2013             'M-SEARCH * HTTP/1.1',
2014             'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2015             'mx: \t1\t\t   ',
2016             'man: \t \t "ssdp:discover"   ',
2017             'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2018             '', ''])
2019     ssdp_send(msg)
2020
2021     ssdp_send_msearch("ssdp:all")
2022     ssdp_send_msearch("upnp:rootdevice")
2023     ssdp_send_msearch("uuid:" + ap_uuid)
2024     ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2025     ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
2026
2027     msg = '\r\n'.join([
2028             'M-SEARCH * HTTP/1.1',
2029             'HOST:\t239.255.255.250:1900',
2030             'MAN: "ssdp:discover"',
2031             'MX: 130',
2032             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2033             '', ''])
2034     ssdp_send(msg, no_recv=True)
2035
2036 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2037     """WPS AP and invalid SSDP M-SEARCH messages"""
2038     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2039     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2040
2041     socket.setdefaulttimeout(1)
2042     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2043     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2044     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2045     sock.bind(("127.0.0.1", 0))
2046
2047     logger.debug("Missing MX")
2048     msg = '\r\n'.join([
2049             'M-SEARCH * HTTP/1.1',
2050             'HOST: 239.255.255.250:1900',
2051             'MAN: "ssdp:discover"',
2052             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2053             '', ''])
2054     sock.sendto(msg, ("239.255.255.250", 1900))
2055
2056     logger.debug("Negative MX")
2057     msg = '\r\n'.join([
2058             'M-SEARCH * HTTP/1.1',
2059             'HOST: 239.255.255.250:1900',
2060             'MX: -1',
2061             'MAN: "ssdp:discover"',
2062             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2063             '', ''])
2064     sock.sendto(msg, ("239.255.255.250", 1900))
2065
2066     logger.debug("Invalid MX")
2067     msg = '\r\n'.join([
2068             'M-SEARCH * HTTP/1.1',
2069             'HOST: 239.255.255.250:1900',
2070             'MX; 1',
2071             'MAN: "ssdp:discover"',
2072             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2073             '', ''])
2074     sock.sendto(msg, ("239.255.255.250", 1900))
2075
2076     logger.debug("Missing MAN")
2077     msg = '\r\n'.join([
2078             'M-SEARCH * HTTP/1.1',
2079             'HOST: 239.255.255.250:1900',
2080             'MX: 1',
2081             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2082             '', ''])
2083     sock.sendto(msg, ("239.255.255.250", 1900))
2084
2085     logger.debug("Invalid MAN")
2086     msg = '\r\n'.join([
2087             'M-SEARCH * HTTP/1.1',
2088             'HOST: 239.255.255.250:1900',
2089             'MX: 1',
2090             'MAN: foo',
2091             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2092             '', ''])
2093     sock.sendto(msg, ("239.255.255.250", 1900))
2094     msg = '\r\n'.join([
2095             'M-SEARCH * HTTP/1.1',
2096             'HOST: 239.255.255.250:1900',
2097             'MX: 1',
2098             'MAN; "ssdp:discover"',
2099             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2100             '', ''])
2101     sock.sendto(msg, ("239.255.255.250", 1900))
2102
2103     logger.debug("Missing HOST")
2104     msg = '\r\n'.join([
2105             'M-SEARCH * HTTP/1.1',
2106             'MAN: "ssdp:discover"',
2107             'MX: 1',
2108             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2109             '', ''])
2110     sock.sendto(msg, ("239.255.255.250", 1900))
2111
2112     logger.debug("Missing ST")
2113     msg = '\r\n'.join([
2114             'M-SEARCH * HTTP/1.1',
2115             'HOST: 239.255.255.250:1900',
2116             'MAN: "ssdp:discover"',
2117             'MX: 1',
2118             '', ''])
2119     sock.sendto(msg, ("239.255.255.250", 1900))
2120
2121     logger.debug("Mismatching ST")
2122     msg = '\r\n'.join([
2123             'M-SEARCH * HTTP/1.1',
2124             'HOST: 239.255.255.250:1900',
2125             'MAN: "ssdp:discover"',
2126             'MX: 1',
2127             'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2128             '', ''])
2129     sock.sendto(msg, ("239.255.255.250", 1900))
2130     msg = '\r\n'.join([
2131             'M-SEARCH * HTTP/1.1',
2132             'HOST: 239.255.255.250:1900',
2133             'MAN: "ssdp:discover"',
2134             'MX: 1',
2135             'ST: foo:bar',
2136             '', ''])
2137     sock.sendto(msg, ("239.255.255.250", 1900))
2138     msg = '\r\n'.join([
2139             'M-SEARCH * HTTP/1.1',
2140             'HOST: 239.255.255.250:1900',
2141             'MAN: "ssdp:discover"',
2142             'MX: 1',
2143             'ST: foobar',
2144             '', ''])
2145     sock.sendto(msg, ("239.255.255.250", 1900))
2146
2147     logger.debug("Invalid ST")
2148     msg = '\r\n'.join([
2149             'M-SEARCH * HTTP/1.1',
2150             'HOST: 239.255.255.250:1900',
2151             'MAN: "ssdp:discover"',
2152             'MX: 1',
2153             'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2154             '', ''])
2155     sock.sendto(msg, ("239.255.255.250", 1900))
2156
2157     logger.debug("Invalid M-SEARCH")
2158     msg = '\r\n'.join([
2159             'M+SEARCH * HTTP/1.1',
2160             'HOST: 239.255.255.250:1900',
2161             'MAN: "ssdp:discover"',
2162             'MX: 1',
2163             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2164             '', ''])
2165     sock.sendto(msg, ("239.255.255.250", 1900))
2166     msg = '\r\n'.join([
2167             'M-SEARCH-* HTTP/1.1',
2168             'HOST: 239.255.255.250:1900',
2169             'MAN: "ssdp:discover"',
2170             'MX: 1',
2171             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2172             '', ''])
2173     sock.sendto(msg, ("239.255.255.250", 1900))
2174
2175     logger.debug("Invalid message format")
2176     sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2177     msg = '\r'.join([
2178             'M-SEARCH * HTTP/1.1',
2179             'HOST: 239.255.255.250:1900',
2180             'MAN: "ssdp:discover"',
2181             'MX: 1',
2182             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2183             '', ''])
2184     sock.sendto(msg, ("239.255.255.250", 1900))
2185
2186     try:
2187         r = sock.recv(1000)
2188         raise Exception("Unexpected M-SEARCH response: " + r)
2189     except socket.timeout:
2190         pass
2191
2192     logger.debug("Valid M-SEARCH")
2193     msg = '\r\n'.join([
2194             'M-SEARCH * HTTP/1.1',
2195             'HOST: 239.255.255.250:1900',
2196             'MAN: "ssdp:discover"',
2197             'MX: 1',
2198             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2199             '', ''])
2200     sock.sendto(msg, ("239.255.255.250", 1900))
2201
2202     try:
2203         r = sock.recv(1000)
2204         pass
2205     except socket.timeout:
2206         raise Exception("No SSDP response")
2207
2208 def test_ap_wps_ssdp_burst(dev, apdev):
2209     """WPS AP and SSDP burst"""
2210     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2211     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2212
2213     msg = '\r\n'.join([
2214             'M-SEARCH * HTTP/1.1',
2215             'HOST: 239.255.255.250:1900',
2216             'MAN: "ssdp:discover"',
2217             'MX: 1',
2218             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2219             '', ''])
2220     socket.setdefaulttimeout(1)
2221     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2222     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2223     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2224     sock.bind(("127.0.0.1", 0))
2225     for i in range(0, 25):
2226         sock.sendto(msg, ("239.255.255.250", 1900))
2227     resp = 0
2228     while True:
2229         try:
2230             r = sock.recv(1000)
2231             if not r.startswith("HTTP/1.1 200 OK\r\n"):
2232                 raise Exception("Unexpected message: " + r)
2233             resp += 1
2234         except socket.timeout:
2235             break
2236     if resp < 20:
2237         raise Exception("Too few SSDP responses")
2238
2239     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2240     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2241     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2242     sock.bind(("127.0.0.1", 0))
2243     for i in range(0, 25):
2244         sock.sendto(msg, ("239.255.255.250", 1900))
2245     while True:
2246         try:
2247             r = sock.recv(1000)
2248             if ap_uuid in r:
2249                 break
2250         except socket.timeout:
2251             raise Exception("No SSDP response")
2252
2253 def ssdp_get_location(uuid):
2254     res = ssdp_send_msearch("uuid:" + uuid)
2255     location = None
2256     for l in res.splitlines():
2257         if l.lower().startswith("location:"):
2258             location = l.split(':', 1)[1].strip()
2259             break
2260     if location is None:
2261         raise Exception("No UPnP location found")
2262     return location
2263
2264 def upnp_get_urls(location):
2265     conn = urllib.urlopen(location)
2266     tree = ET.parse(conn)
2267     root = tree.getroot()
2268     urn = '{urn:schemas-upnp-org:device-1-0}'
2269     service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2270     res = {}
2271     res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
2272     res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
2273     res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
2274     return res
2275
2276 def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
2277     soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2278     wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2279     ET.register_namespace('soapenv', soapns)
2280     ET.register_namespace('wfa', wpsns)
2281     attrib = {}
2282     attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2283     root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2284     body = ET.SubElement(root, "{%s}Body" % soapns)
2285     act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
2286     tree = ET.ElementTree(root)
2287     soap = StringIO.StringIO()
2288     tree.write(soap, xml_declaration=True, encoding='utf-8')
2289
2290     headers = { "Content-type": 'text/xml; charset="utf-8"' }
2291     if include_soap_action:
2292         headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2293     elif soap_action_override:
2294         headers["SOAPAction"] = soap_action_override
2295     conn.request("POST", path, soap.getvalue(), headers)
2296     return conn.getresponse()
2297
2298 def test_ap_wps_upnp(dev, apdev):
2299     """WPS AP and UPnP operations"""
2300     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2301     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2302
2303     location = ssdp_get_location(ap_uuid)
2304     urls = upnp_get_urls(location)
2305
2306     conn = urllib.urlopen(urls['scpd_url'])
2307     scpd = conn.read()
2308
2309     conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
2310     if conn.getcode() != 404:
2311         raise Exception("Unexpected HTTP response to GET unknown URL")
2312
2313     url = urlparse.urlparse(location)
2314     conn = httplib.HTTPConnection(url.netloc)
2315     #conn.set_debuglevel(1)
2316     headers = { "Content-type": 'text/xml; charset="utf-8"',
2317                 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2318     conn.request("POST", "hello", "\r\n\r\n", headers)
2319     resp = conn.getresponse()
2320     if resp.status != 404:
2321         raise Exception("Unexpected HTTP response: %d" % resp.status)
2322
2323     conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2324     resp = conn.getresponse()
2325     if resp.status != 501:
2326         raise Exception("Unexpected HTTP response: %d" % resp.status)
2327
2328     headers = { "Content-type": 'text/xml; charset="utf-8"',
2329                 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2330     ctrlurl = urlparse.urlparse(urls['control_url'])
2331     conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2332     resp = conn.getresponse()
2333     if resp.status != 401:
2334         raise Exception("Unexpected HTTP response: %d" % resp.status)
2335
2336     logger.debug("GetDeviceInfo without SOAPAction header")
2337     resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2338                             include_soap_action=False)
2339     if resp.status != 401:
2340         raise Exception("Unexpected HTTP response: %d" % resp.status)
2341
2342     logger.debug("GetDeviceInfo with invalid SOAPAction header")
2343     for act in [ "foo",
2344                  "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2345                  '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2346                  '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2347         resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2348                                 include_soap_action=False,
2349                                 soap_action_override=act)
2350         if resp.status != 401:
2351             raise Exception("Unexpected HTTP response: %d" % resp.status)
2352
2353     resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2354     if resp.status != 200:
2355         raise Exception("Unexpected HTTP response: %d" % resp.status)
2356     dev = resp.read()
2357     if "NewDeviceInfo" not in dev:
2358         raise Exception("Unexpected GetDeviceInfo response")
2359
2360     logger.debug("PutMessage without required parameters")
2361     resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2362     if resp.status != 600:
2363         raise Exception("Unexpected HTTP response: %d" % resp.status)
2364
2365     logger.debug("PutWLANResponse without required parameters")
2366     resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2367     if resp.status != 600:
2368         raise Exception("Unexpected HTTP response: %d" % resp.status)
2369
2370     logger.debug("SetSelectedRegistrar from unregistered ER")
2371     resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2372     if resp.status != 501:
2373         raise Exception("Unexpected HTTP response: %d" % resp.status)
2374
2375     logger.debug("Unknown action")
2376     resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2377     if resp.status != 401:
2378         raise Exception("Unexpected HTTP response: %d" % resp.status)
2379
2380 def test_ap_wps_upnp_subscribe(dev, apdev):
2381     """WPS AP and UPnP event subscription"""
2382     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2383     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2384
2385     location = ssdp_get_location(ap_uuid)
2386     urls = upnp_get_urls(location)
2387     eventurl = urlparse.urlparse(urls['event_sub_url'])
2388
2389     url = urlparse.urlparse(location)
2390     conn = httplib.HTTPConnection(url.netloc)
2391     #conn.set_debuglevel(1)
2392     headers = { "callback": '<http://127.0.0.1:12345/event>',
2393                 "timeout": "Second-1234" }
2394     conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2395     resp = conn.getresponse()
2396     if resp.status != 412:
2397         raise Exception("Unexpected HTTP response: %d" % resp.status)
2398
2399     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2400     resp = conn.getresponse()
2401     if resp.status != 412:
2402         raise Exception("Unexpected HTTP response: %d" % resp.status)
2403
2404     headers = { "NT": "upnp:event",
2405                 "timeout": "Second-1234" }
2406     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2407     resp = conn.getresponse()
2408     if resp.status != 412:
2409         raise Exception("Unexpected HTTP response: %d" % resp.status)
2410
2411     headers = { "callback": '<http://127.0.0.1:12345/event>',
2412                 "NT": "upnp:foobar",
2413                 "timeout": "Second-1234" }
2414     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2415     resp = conn.getresponse()
2416     if resp.status != 400:
2417         raise Exception("Unexpected HTTP response: %d" % resp.status)
2418
2419     logger.debug("Valid subscription")
2420     headers = { "callback": '<http://127.0.0.1:12345/event>',
2421                 "NT": "upnp:event",
2422                 "timeout": "Second-1234" }
2423     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2424     resp = conn.getresponse()
2425     if resp.status != 200:
2426         raise Exception("Unexpected HTTP response: %d" % resp.status)
2427     sid = resp.getheader("sid")
2428     logger.debug("Subscription SID " + sid)
2429
2430     logger.debug("Invalid re-subscription")
2431     headers = { "NT": "upnp:event",
2432                 "sid": "123456734567854",
2433                 "timeout": "Second-1234" }
2434     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2435     resp = conn.getresponse()
2436     if resp.status != 400:
2437         raise Exception("Unexpected HTTP response: %d" % resp.status)
2438
2439     logger.debug("Invalid re-subscription")
2440     headers = { "NT": "upnp:event",
2441                 "sid": "uuid:123456734567854",
2442                 "timeout": "Second-1234" }
2443     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2444     resp = conn.getresponse()
2445     if resp.status != 400:
2446         raise Exception("Unexpected HTTP response: %d" % resp.status)
2447
2448     logger.debug("Invalid re-subscription")
2449     headers = { "callback": '<http://127.0.0.1:12345/event>',
2450                 "NT": "upnp:event",
2451                 "sid": sid,
2452                 "timeout": "Second-1234" }
2453     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2454     resp = conn.getresponse()
2455     if resp.status != 400:
2456         raise Exception("Unexpected HTTP response: %d" % resp.status)
2457
2458     logger.debug("SID mismatch in re-subscription")
2459     headers = { "NT": "upnp:event",
2460                 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2461                 "timeout": "Second-1234" }
2462     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2463     resp = conn.getresponse()
2464     if resp.status != 412:
2465         raise Exception("Unexpected HTTP response: %d" % resp.status)
2466
2467     logger.debug("Valid re-subscription")
2468     headers = { "NT": "upnp:event",
2469                 "sid": sid,
2470                 "timeout": "Second-1234" }
2471     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2472     resp = conn.getresponse()
2473     if resp.status != 200:
2474         raise Exception("Unexpected HTTP response: %d" % resp.status)
2475     sid2 = resp.getheader("sid")
2476     logger.debug("Subscription SID " + sid2)
2477
2478     if sid != sid2:
2479         raise Exception("Unexpected SID change")
2480
2481     logger.debug("Valid re-subscription")
2482     headers = { "NT": "upnp:event",
2483                 "sid": "uuid: \t \t" + sid.split(':')[1],
2484                 "timeout": "Second-1234" }
2485     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2486     resp = conn.getresponse()
2487     if resp.status != 200:
2488         raise Exception("Unexpected HTTP response: %d" % resp.status)
2489
2490     logger.debug("Invalid unsubscription")
2491     headers = { "sid": sid }
2492     conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
2493     resp = conn.getresponse()
2494     if resp.status != 412:
2495         raise Exception("Unexpected HTTP response: %d" % resp.status)
2496     headers = { "foo": "bar" }
2497     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2498     resp = conn.getresponse()
2499     if resp.status != 412:
2500         raise Exception("Unexpected HTTP response: %d" % resp.status)
2501
2502     logger.debug("Valid unsubscription")
2503     headers = { "sid": sid }
2504     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2505     resp = conn.getresponse()
2506     if resp.status != 200:
2507         raise Exception("Unexpected HTTP response: %d" % resp.status)
2508
2509     logger.debug("Unsubscription for not existing SID")
2510     headers = { "sid": sid }
2511     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2512     resp = conn.getresponse()
2513     if resp.status != 412:
2514         raise Exception("Unexpected HTTP response: %d" % resp.status)
2515
2516     logger.debug("Invalid unsubscription")
2517     headers = { "sid": " \t \tfoo" }
2518     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2519     resp = conn.getresponse()
2520     if resp.status != 400:
2521         raise Exception("Unexpected HTTP response: %d" % resp.status)
2522
2523     logger.debug("Invalid unsubscription")
2524     headers = { "sid": "uuid:\t \tfoo" }
2525     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2526     resp = conn.getresponse()
2527     if resp.status != 400:
2528         raise Exception("Unexpected HTTP response: %d" % resp.status)
2529
2530     logger.debug("Invalid unsubscription")
2531     headers = { "NT": "upnp:event",
2532                 "sid": sid }
2533     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2534     resp = conn.getresponse()
2535     if resp.status != 400:
2536         raise Exception("Unexpected HTTP response: %d" % resp.status)
2537     headers = { "callback": '<http://127.0.0.1:12345/event>',
2538                 "sid": sid }
2539     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2540     resp = conn.getresponse()
2541     if resp.status != 400:
2542         raise Exception("Unexpected HTTP response: %d" % resp.status)
2543
2544     logger.debug("Valid subscription with multiple callbacks")
2545     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>',
2546                 "NT": "upnp:event",
2547                 "timeout": "Second-1234" }
2548     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2549     resp = conn.getresponse()
2550     if resp.status != 200:
2551         raise Exception("Unexpected HTTP response: %d" % resp.status)
2552     sid = resp.getheader("sid")
2553     logger.debug("Subscription SID " + sid)
2554
2555     # Force subscription to be deleted due to errors
2556     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2557     dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2558     with alloc_fail(hapd, 1, "event_build_message"):
2559         for i in range(10):
2560             dev[1].dump_monitor()
2561             dev[2].dump_monitor()
2562             dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2563             dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2564             dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2565             dev[1].request("WPS_CANCEL")
2566             dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2567             dev[2].request("WPS_CANCEL")
2568             if i % 4 == 1:
2569                 time.sleep(1)
2570             else:
2571                 time.sleep(0.1)
2572     time.sleep(0.2)
2573
2574     headers = { "sid": sid }
2575     conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
2576     resp = conn.getresponse()
2577     if resp.status != 200 and resp.status != 412:
2578         raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
2579
2580     headers = { "callback": '<http://127.0.0.1:12345/event>',
2581                 "NT": "upnp:event",
2582                 "timeout": "Second-1234" }
2583     with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
2584         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2585         resp = conn.getresponse()
2586         if resp.status != 200:
2587             raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
2588         sid = resp.getheader("sid")
2589         logger.debug("Subscription SID " + sid)
2590
2591     headers = { "sid": sid }
2592     conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2593     resp = conn.getresponse()
2594     if resp.status != 200:
2595         raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
2596
2597     headers = { "callback": '<http://127.0.0.1:12345/event>',
2598                 "NT": "upnp:event",
2599                 "timeout": "Second-1234" }
2600     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2601     resp = conn.getresponse()
2602     if resp.status != 200:
2603         raise Exception("Unexpected HTTP response: %d" % resp.status)
2604     sid = resp.getheader("sid")
2605     logger.debug("Subscription SID " + sid)
2606
2607     with alloc_fail(hapd, 1, "=event_add"):
2608         for i in range(2):
2609             dev[1].dump_monitor()
2610             dev[2].dump_monitor()
2611             dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2612             dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2613             dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2614             dev[1].request("WPS_CANCEL")
2615             dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2616             dev[2].request("WPS_CANCEL")
2617             if i == 0:
2618                 time.sleep(1)
2619             else:
2620                 time.sleep(0.1)
2621
2622     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2623     resp = conn.getresponse()
2624     if resp.status != 200:
2625         raise Exception("Unexpected HTTP response: %d" % resp.status)
2626
2627     with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
2628         dev[1].dump_monitor()
2629         dev[2].dump_monitor()
2630         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2631         dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2632         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2633         dev[1].request("WPS_CANCEL")
2634         dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2635         dev[2].request("WPS_CANCEL")
2636         time.sleep(0.1)
2637
2638     with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
2639         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2640         resp = conn.getresponse()
2641         if resp.status != 500:
2642             raise Exception("Unexpected HTTP response: %d" % resp.status)
2643
2644     with alloc_fail(hapd, 1, "=subscription_start"):
2645         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2646         resp = conn.getresponse()
2647         if resp.status != 500:
2648             raise Exception("Unexpected HTTP response: %d" % resp.status)
2649
2650     headers = { "callback": '',
2651                 "NT": "upnp:event",
2652                 "timeout": "Second-1234" }
2653     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2654     resp = conn.getresponse()
2655     if resp.status != 500:
2656         raise Exception("Unexpected HTTP response: %d" % resp.status)
2657
2658     headers = { "callback": ' <',
2659                 "NT": "upnp:event",
2660                 "timeout": "Second-1234" }
2661     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2662     resp = conn.getresponse()
2663     if resp.status != 500:
2664         raise Exception("Unexpected HTTP response: %d" % resp.status)
2665
2666     headers = { "callback": '<http://127.0.0.1:12345/event>',
2667                 "NT": "upnp:event",
2668                 "timeout": "Second-1234" }
2669     with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
2670         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2671         resp = conn.getresponse()
2672         if resp.status != 500:
2673             raise Exception("Unexpected HTTP response: %d" % resp.status)
2674
2675     with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
2676         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2677         resp = conn.getresponse()
2678         if resp.status != 500:
2679             raise Exception("Unexpected HTTP response: %d" % resp.status)
2680
2681     with alloc_fail(hapd, 1, "subscr_addr_add_url"):
2682         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2683         resp = conn.getresponse()
2684         if resp.status != 500:
2685             raise Exception("Unexpected HTTP response: %d" % resp.status)
2686
2687     with alloc_fail(hapd, 2, "subscr_addr_add_url"):
2688         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2689         resp = conn.getresponse()
2690         if resp.status != 500:
2691             raise Exception("Unexpected HTTP response: %d" % resp.status)
2692
2693     for i in range(6):
2694         headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
2695                     "NT": "upnp:event",
2696                     "timeout": "Second-1234" }
2697         conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2698         resp = conn.getresponse()
2699         if resp.status != 200:
2700             raise Exception("Unexpected HTTP response: %d" % resp.status)
2701
2702     with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
2703         dev[1].dump_monitor()
2704         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2705         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2706         dev[1].request("WPS_CANCEL")
2707         time.sleep(0.1)
2708
2709     with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
2710         dev[1].dump_monitor()
2711         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2712         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2713         dev[1].request("WPS_CANCEL")
2714         time.sleep(0.1)
2715
2716     with alloc_fail(hapd, 1, "base64_encode;upnp_wps_device_send_wlan_event"):
2717         dev[1].dump_monitor()
2718         dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2719         dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
2720         dev[1].request("WPS_CANCEL")
2721         time.sleep(0.1)
2722
2723     hapd.disable()
2724     with alloc_fail(hapd, 1, "get_netif_info"):
2725         if "FAIL" not in hapd.request("ENABLE"):
2726             raise Exception("ENABLE succeeded during OOM")
2727
2728 def test_ap_wps_upnp_http_proto(dev, apdev):
2729     """WPS AP and UPnP/HTTP protocol testing"""
2730     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2731     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2732
2733     location = ssdp_get_location(ap_uuid)
2734
2735     url = urlparse.urlparse(location)
2736     conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
2737     #conn.set_debuglevel(1)
2738
2739     conn.request("HEAD", "hello")
2740     resp = conn.getresponse()
2741     if resp.status != 501:
2742         raise Exception("Unexpected response to HEAD: " + str(resp.status))
2743     conn.close()
2744
2745     for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
2746         try:
2747             conn.request(cmd, "hello")
2748             resp = conn.getresponse()
2749         except Exception, e:
2750             pass
2751         conn.close()
2752
2753     headers = { "Content-Length": 'abc' }
2754     conn.request("HEAD", "hello", "\r\n\r\n", headers)
2755     try:
2756         resp = conn.getresponse()
2757     except Exception, e:
2758         pass
2759     conn.close()
2760
2761     headers = { "Content-Length": '-10' }
2762     conn.request("HEAD", "hello", "\r\n\r\n", headers)
2763     try:
2764         resp = conn.getresponse()
2765     except Exception, e:
2766         pass
2767     conn.close()
2768
2769     headers = { "Content-Length": '10000000000000' }
2770     conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
2771     try:
2772         resp = conn.getresponse()
2773     except Exception, e:
2774         pass
2775     conn.close()
2776
2777     headers = { "Transfer-Encoding": 'abc' }
2778     conn.request("HEAD", "hello", "\r\n\r\n", headers)
2779     resp = conn.getresponse()
2780     if resp.status != 501:
2781         raise Exception("Unexpected response to HEAD: " + str(resp.status))
2782     conn.close()
2783
2784     headers = { "Transfer-Encoding": 'chunked' }
2785     conn.request("HEAD", "hello", "\r\n\r\n", headers)
2786     resp = conn.getresponse()
2787     if resp.status != 501:
2788         raise Exception("Unexpected response to HEAD: " + str(resp.status))
2789     conn.close()
2790
2791     # Too long a header
2792     conn.request("HEAD", 5000 * 'A')
2793     try:
2794         resp = conn.getresponse()
2795     except Exception, e:
2796         pass
2797     conn.close()
2798
2799     # Long URL but within header length limits
2800     conn.request("HEAD", 3000 * 'A')
2801     resp = conn.getresponse()
2802     if resp.status != 501:
2803         raise Exception("Unexpected response to HEAD: " + str(resp.status))
2804     conn.close()
2805
2806     headers = { "Content-Length": '20' }
2807     conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
2808     try:
2809         resp = conn.getresponse()
2810     except Exception, e:
2811         pass
2812     conn.close()
2813
2814     conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
2815     resp = conn.getresponse()
2816     if resp.status != 404:
2817         raise Exception("Unexpected HTTP response: %d" % resp.status)
2818     conn.close()
2819
2820     conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
2821     try:
2822         resp = conn.getresponse()
2823     except Exception, e:
2824         pass
2825     conn.close()
2826
2827 def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
2828     """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
2829     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2830     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2831
2832     location = ssdp_get_location(ap_uuid)
2833
2834     url = urlparse.urlparse(location)
2835     conn = httplib.HTTPConnection(url.netloc)
2836     #conn.set_debuglevel(1)
2837
2838     headers = { "Transfer-Encoding": 'chunked' }
2839     conn.request("POST", "hello",
2840                  "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
2841                  headers)
2842     resp = conn.getresponse()
2843     if resp.status != 404:
2844         raise Exception("Unexpected HTTP response: %d" % resp.status)
2845     conn.close()
2846
2847     conn.putrequest("POST", "hello")
2848     conn.putheader('Transfer-Encoding', 'chunked')
2849     conn.endheaders()
2850     conn.send("a\r\nabcdefghij\r\n")
2851     time.sleep(0.1)
2852     conn.send("2\r\nkl\r\n")
2853     conn.send("0\r\n\r\n")
2854     resp = conn.getresponse()
2855     if resp.status != 404:
2856         raise Exception("Unexpected HTTP response: %d" % resp.status)
2857     conn.close()
2858
2859     conn.putrequest("POST", "hello")
2860     conn.putheader('Transfer-Encoding', 'chunked')
2861     conn.endheaders()
2862     completed = False
2863     try:
2864         for i in range(20000):
2865             conn.send("1\r\nZ\r\n")
2866         conn.send("0\r\n\r\n")
2867         resp = conn.getresponse()
2868         completed = True
2869     except Exception, e:
2870         pass
2871     conn.close()
2872     if completed:
2873         raise Exception("Too long chunked request did not result in connection reset")
2874
2875     headers = { "Transfer-Encoding": 'chunked' }
2876     conn.request("POST", "hello", "80000000\r\na", headers)
2877     try:
2878         resp = conn.getresponse()
2879     except Exception, e:
2880         pass
2881     conn.close()
2882
2883     conn.request("POST", "hello", "10000000\r\na", headers)
2884     try:
2885         resp = conn.getresponse()
2886     except Exception, e:
2887         pass
2888     conn.close()
2889
2890 def test_ap_wps_disabled(dev, apdev):
2891     """WPS operations while WPS is disabled"""
2892     ssid = "test-wps-disabled"
2893     hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
2894     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2895     if "FAIL" not in hapd.request("WPS_PBC"):
2896         raise Exception("WPS_PBC succeeded unexpectedly")
2897     if "FAIL" not in hapd.request("WPS_CANCEL"):
2898         raise Exception("WPS_CANCEL succeeded unexpectedly")
2899
2900 def test_ap_wps_mixed_cred(dev, apdev):
2901     """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
2902     ssid = "test-wps-wep"
2903     hostapd.add_ap(apdev[0]['ifname'],
2904                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2905                      "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
2906     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2907     hapd.request("WPS_PBC")
2908     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2909     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2910     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
2911     if ev is None:
2912         raise Exception("WPS-SUCCESS event timed out")
2913     nets = dev[0].list_networks()
2914     if len(nets) != 1:
2915         raise Exception("Unexpected number of network blocks")
2916     id = nets[0]['id']
2917     proto = dev[0].get_network(id, "proto")
2918     if proto != "WPA RSN":
2919         raise Exception("Unexpected merged proto field value: " + proto)
2920     pairwise = dev[0].get_network(id, "pairwise")
2921     if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
2922         raise Exception("Unexpected merged pairwise field value: " + pairwise)
2923
2924 def test_ap_wps_while_connected(dev, apdev):
2925     """WPS PBC provisioning while connected to another AP"""
2926     ssid = "test-wps-conf"
2927     hostapd.add_ap(apdev[0]['ifname'],
2928                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2929                      "wpa_passphrase": "12345678", "wpa": "2",
2930                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2931     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2932
2933     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
2934     dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
2935
2936     logger.info("WPS provisioning step")
2937     hapd.request("WPS_PBC")
2938     dev[0].dump_monitor()
2939     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2940     dev[0].wait_connected(timeout=30)
2941     status = dev[0].get_status()
2942     if status['bssid'] != apdev[0]['bssid']:
2943         raise Exception("Unexpected BSSID")
2944
2945 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
2946     """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
2947     ssid = "test-wps-conf"
2948     hostapd.add_ap(apdev[0]['ifname'],
2949                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2950                      "wpa_passphrase": "12345678", "wpa": "2",
2951                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2952     hapd = hostapd.Hostapd(apdev[0]['ifname'])
2953
2954     hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
2955
2956     try:
2957         dev[0].request("STA_AUTOCONNECT 0")
2958         dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
2959
2960         logger.info("WPS provisioning step")
2961         hapd.request("WPS_PBC")
2962         dev[0].dump_monitor()
2963         dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2964         dev[0].wait_connected(timeout=30)
2965         status = dev[0].get_status()
2966         if status['bssid'] != apdev[0]['bssid']:
2967             raise Exception("Unexpected BSSID")
2968     finally:
2969         dev[0].request("STA_AUTOCONNECT 1")
2970
2971 def test_ap_wps_from_event(dev, apdev):
2972     """WPS PBC event on AP to enable PBC"""
2973     ssid = "test-wps-conf"
2974     hapd = hostapd.add_ap(apdev[0]['ifname'],
2975                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2976                             "wpa_passphrase": "12345678", "wpa": "2",
2977                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2978     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2979     dev[0].dump_monitor()
2980     hapd.dump_monitor()
2981     dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2982
2983     ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
2984     if ev is None:
2985         raise Exception("No WPS-ENROLLEE-SEEN event on AP")
2986     vals = ev.split(' ')
2987     if vals[1] != dev[0].p2p_interface_addr():
2988         raise Exception("Unexpected enrollee address: " + vals[1])
2989     if vals[5] != '4':
2990         raise Exception("Unexpected Device Password Id: " + vals[5])
2991     hapd.request("WPS_PBC")
2992     dev[0].wait_connected(timeout=30)
2993
2994 def test_ap_wps_ap_scan_2(dev, apdev):
2995     """AP_SCAN 2 for WPS"""
2996     ssid = "test-wps-conf"
2997     hapd = hostapd.add_ap(apdev[0]['ifname'],
2998                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2999                             "wpa_passphrase": "12345678", "wpa": "2",
3000                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3001     hapd.request("WPS_PBC")
3002
3003     wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3004     wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
3005
3006     if "OK" not in wpas.request("AP_SCAN 2"):
3007         raise Exception("Failed to set AP_SCAN 2")
3008
3009     wpas.flush_scan_cache()
3010     wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
3011     wpas.request("WPS_PBC " + apdev[0]['bssid'])
3012     ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3013     if ev is None:
3014         raise Exception("WPS-SUCCESS event timed out")
3015     wpas.wait_connected(timeout=30)
3016     wpas.request("DISCONNECT")
3017     wpas.request("BSS_FLUSH 0")
3018     wpas.dump_monitor()
3019     wpas.request("REASSOCIATE")
3020     wpas.wait_connected(timeout=30)
3021
3022 def test_ap_wps_eapol_workaround(dev, apdev):
3023     """EAPOL workaround code path for 802.1X header length mismatch"""
3024     ssid = "test-wps"
3025     hostapd.add_ap(apdev[0]['ifname'],
3026                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
3027     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3028     bssid = apdev[0]['bssid']
3029     hapd.request("SET ext_eapol_frame_io 1")
3030     dev[0].request("SET ext_eapol_frame_io 1")
3031     hapd.request("WPS_PBC")
3032     dev[0].request("WPS_PBC")
3033
3034     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3035     if ev is None:
3036         raise Exception("Timeout on EAPOL-TX from hostapd")
3037
3038     res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3039     if "OK" not in res:
3040         raise Exception("EAPOL_RX to wpa_supplicant failed")
3041
3042 def test_ap_wps_iteration(dev, apdev):
3043     """WPS PIN and iterate through APs without selected registrar"""
3044     ssid = "test-wps-conf"
3045     hapd = hostapd.add_ap(apdev[0]['ifname'],
3046                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3047                             "wpa_passphrase": "12345678", "wpa": "2",
3048                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3049
3050     ssid2 = "test-wps-conf2"
3051     hapd2 = hostapd.add_ap(apdev[1]['ifname'],
3052                            { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
3053                              "wpa_passphrase": "12345678", "wpa": "2",
3054                              "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3055
3056     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3057     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3058     dev[0].dump_monitor()
3059     pin = dev[0].request("WPS_PIN any")
3060
3061     # Wait for iteration through all WPS APs to happen before enabling any
3062     # Registrar.
3063     for i in range(2):
3064         ev = dev[0].wait_event(["Associated with"], timeout=30)
3065         if ev is None:
3066             raise Exception("No association seen")
3067         ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3068         if ev is None:
3069             raise Exception("No M2D from AP")
3070         dev[0].wait_disconnected()
3071
3072     # Verify that each AP requested PIN
3073     ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3074     if ev is None:
3075         raise Exception("No WPS-PIN-NEEDED event from AP")
3076     ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3077     if ev is None:
3078         raise Exception("No WPS-PIN-NEEDED event from AP2")
3079
3080     # Provide PIN to one of the APs and verify that connection gets formed
3081     hapd.request("WPS_PIN any " + pin)
3082     dev[0].wait_connected(timeout=30)
3083
3084 def test_ap_wps_iteration_error(dev, apdev):
3085     """WPS AP iteration on no Selected Registrar and error case with an AP"""
3086     ssid = "test-wps-conf-pin"
3087     hapd = hostapd.add_ap(apdev[0]['ifname'],
3088                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3089                             "wpa_passphrase": "12345678", "wpa": "2",
3090                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3091                             "wps_independent": "1" })
3092     hapd.request("SET ext_eapol_frame_io 1")
3093     bssid = apdev[0]['bssid']
3094     pin = dev[0].wps_read_pin()
3095     dev[0].request("WPS_PIN any " + pin)
3096
3097     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3098     if ev is None:
3099         raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3100     dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3101
3102     ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3103     if ev is None:
3104         raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3105     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3106     if ev is None:
3107         raise Exception("No CTRL-EVENT-EAP-STARTED")
3108
3109     # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3110     # a case with an incorrectly behaving WPS AP.
3111
3112     # Start the real target AP and activate registrar on it.
3113     hapd2 = hostapd.add_ap(apdev[1]['ifname'],
3114                           { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3115                             "wpa_passphrase": "12345678", "wpa": "2",
3116                             "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3117                             "wps_independent": "1" })
3118     hapd2.request("WPS_PIN any " + pin)
3119
3120     dev[0].wait_disconnected(timeout=15)
3121     ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3122     if ev is None:
3123         raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3124     ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3125     if ev is None:
3126         raise Exception("No WPS-CRED-RECEIVED for the second AP")
3127     dev[0].wait_connected(timeout=15)
3128
3129 def test_ap_wps_priority(dev, apdev):
3130     """WPS PIN provisioning with configured AP and wps_priority"""
3131     ssid = "test-wps-conf-pin"
3132     hostapd.add_ap(apdev[0]['ifname'],
3133                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3134                      "wpa_passphrase": "12345678", "wpa": "2",
3135                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3136     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3137     logger.info("WPS provisioning step")
3138     pin = dev[0].wps_read_pin()
3139     hapd.request("WPS_PIN any " + pin)
3140     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3141     dev[0].dump_monitor()
3142     try:
3143         dev[0].request("SET wps_priority 6")
3144         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3145         dev[0].wait_connected(timeout=30)
3146         netw = dev[0].list_networks()
3147         prio = dev[0].get_network(netw[0]['id'], 'priority')
3148         if prio != '6':
3149             raise Exception("Unexpected network priority: " + prio)
3150     finally:
3151         dev[0].request("SET wps_priority 0")
3152
3153 def test_ap_wps_and_non_wps(dev, apdev):
3154     """WPS and non-WPS AP in single hostapd process"""
3155     params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
3156     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3157
3158     params = { "ssid": "no wps" }
3159     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
3160
3161     appin = hapd.request("WPS_AP_PIN random")
3162     if "FAIL" in appin:
3163         raise Exception("Could not generate random AP PIN")
3164     if appin not in hapd.request("WPS_AP_PIN get"):
3165         raise Exception("Could not fetch current AP PIN")
3166
3167     if "FAIL" in hapd.request("WPS_PBC"):
3168         raise Exception("WPS_PBC failed")
3169     if "FAIL" in hapd.request("WPS_CANCEL"):
3170         raise Exception("WPS_CANCEL failed")
3171
3172 def test_ap_wps_init_oom(dev, apdev):
3173     """Initial AP configuration and OOM during PSK generation"""
3174     ssid = "test-wps"
3175     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
3176     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
3177
3178     with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
3179         pin = dev[0].wps_read_pin()
3180         hapd.request("WPS_PIN any " + pin)
3181         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3182         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3183         dev[0].wait_disconnected()
3184
3185     hapd.request("WPS_PIN any " + pin)
3186     dev[0].wait_connected(timeout=30)
3187
3188 def test_ap_wps_er_oom(dev, apdev):
3189     """WPS ER OOM in XML processing"""
3190     try:
3191         _test_ap_wps_er_oom(dev, apdev)
3192     finally:
3193         dev[0].request("WPS_ER_STOP")
3194         dev[1].request("WPS_CANCEL")
3195         dev[0].request("DISCONNECT")
3196
3197 def _test_ap_wps_er_oom(dev, apdev):
3198     ssid = "wps-er-ap-config"
3199     ap_pin = "12345670"
3200     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3201     hostapd.add_ap(apdev[0]['ifname'],
3202                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3203                      "wpa_passphrase": "12345678", "wpa": "2",
3204                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3205                      "device_name": "Wireless AP", "manufacturer": "Company",
3206                      "model_name": "WAP", "model_number": "123",
3207                      "serial_number": "12345", "device_type": "6-0050F204-1",
3208                      "os_version": "01020300",
3209                      "config_methods": "label push_button",
3210                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3211
3212     dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3213
3214     with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3215         dev[0].request("WPS_ER_START ifname=lo")
3216         ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3217         if ev is not None:
3218             raise Exception("Unexpected AP discovery")
3219
3220     dev[0].request("WPS_ER_STOP")
3221     dev[0].request("WPS_ER_START ifname=lo")
3222     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3223     if ev is None:
3224         raise Exception("AP discovery timed out")
3225
3226     dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3227     with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3228         dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3229         ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3230         if ev is None:
3231             raise Exception("PBC scan failed")
3232         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3233         if ev is None:
3234             raise Exception("Enrollee discovery timed out")
3235
3236 def test_ap_wps_er_init_oom(dev, apdev):
3237     """WPS ER and OOM during init"""
3238     try:
3239         _test_ap_wps_er_init_oom(dev, apdev)
3240     finally:
3241         dev[0].request("WPS_ER_STOP")
3242
3243 def _test_ap_wps_er_init_oom(dev, apdev):
3244     with alloc_fail(dev[0], 1, "wps_er_init"):
3245         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3246             raise Exception("WPS_ER_START succeeded during OOM")
3247     with alloc_fail(dev[0], 1, "http_server_init"):
3248         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3249             raise Exception("WPS_ER_START succeeded during OOM")
3250     with alloc_fail(dev[0], 2, "http_server_init"):
3251         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3252             raise Exception("WPS_ER_START succeeded during OOM")
3253     with alloc_fail(dev[0], 1, "eloop_register_sock;wps_er_ssdp_init"):
3254         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3255             raise Exception("WPS_ER_START succeeded during OOM")
3256     with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3257         if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3258             raise Exception("WPS_ER_START succeeded during os_get_random failure")
3259
3260 def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3261     """WPS events and wpa_cli action script"""
3262     logdir = os.path.abspath(test_params['logdir'])
3263     pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3264     logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3265     actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
3266
3267     with open(actionfile, 'w') as f:
3268         f.write('#!/bin/sh\n')
3269         f.write('echo $* >> %s\n' % logfile)
3270         # Kill the process and wait some time before returning to allow all the
3271         # pending events to be processed with some of this happening after the
3272         # eloop SIGALRM signal has been scheduled.
3273         f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3274
3275     os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3276              stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
3277
3278     ssid = "test-wps-conf"
3279     hostapd.add_ap(apdev[0]['ifname'],
3280                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3281                      "wpa_passphrase": "12345678", "wpa": "2",
3282                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3283     hapd = hostapd.Hostapd(apdev[0]['ifname'])
3284
3285     prg = os.path.join(test_params['logdir'],
3286                        'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3287     if not os.path.exists(prg):
3288         prg = '../../wpa_supplicant/wpa_cli'
3289     arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
3290     subprocess.call(arg)
3291
3292     arg = [ 'ps', 'ax' ]
3293     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3294     out = cmd.communicate()[0]
3295     cmd.wait()
3296     logger.debug("Processes:\n" + out)
3297     if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3298         raise Exception("Did not see wpa_cli running")
3299
3300     hapd.request("WPS_PIN any 12345670")
3301     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3302     dev[0].dump_monitor()
3303     dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3304     dev[0].wait_connected(timeout=30)
3305
3306     for i in range(30):
3307         if not os.path.exists(pidfile):
3308             break
3309         time.sleep(0.1)
3310
3311     if not os.path.exists(logfile):
3312         raise Exception("wpa_cli action results file not found")
3313     with open(logfile, 'r') as f:
3314         res = f.read()
3315     if "WPS-SUCCESS" not in res:
3316         raise Exception("WPS-SUCCESS event not seen in action file")
3317
3318     arg = [ 'ps', 'ax' ]
3319     cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3320     out = cmd.communicate()[0]
3321     cmd.wait()
3322     logger.debug("Remaining processes:\n" + out)
3323     if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3324         raise Exception("wpa_cli still running")
3325
3326     if os.path.exists(pidfile):
3327         raise Exception("PID file not removed")
3328
3329 def test_ap_wps_er_ssdp_proto(dev, apdev):
3330     """WPS ER SSDP protocol testing"""
3331     try:
3332         _test_ap_wps_er_ssdp_proto(dev, apdev)
3333     finally:
3334         dev[0].request("WPS_ER_STOP")
3335
3336 def _test_ap_wps_er_ssdp_proto(dev, apdev):
3337     socket.setdefaulttimeout(1)
3338     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3339     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3340     sock.bind(("239.255.255.250", 1900))
3341     if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3342         raise Exception("Invalid filter accepted")
3343     if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3344         raise Exception("WPS_ER_START with filter failed")
3345     (msg,addr) = sock.recvfrom(1000)
3346     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3347     if "M-SEARCH" not in msg:
3348         raise Exception("Not an M-SEARCH")
3349     sock.sendto("FOO", addr)
3350     time.sleep(0.1)
3351     dev[0].request("WPS_ER_STOP")
3352
3353     dev[0].request("WPS_ER_START ifname=lo")
3354     (msg,addr) = sock.recvfrom(1000)
3355     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3356     if "M-SEARCH" not in msg:
3357         raise Exception("Not an M-SEARCH")
3358     sock.sendto("FOO", addr)
3359     sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3360     sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3361     sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3362     sock.sendto("HTTP/1.1 200 OK\r\ncache-control:   foo=1\r\n\r\n", addr)
3363     sock.sendto("HTTP/1.1 200 OK\r\ncache-control:   max-age=1\r\n\r\n", addr)
3364     sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3365     sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3366     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:\r\n\r\n", addr)
3367     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:     \r\n\r\n", addr)
3368     sock.sendto("HTTP/1.1 200 OK\r\nusn:   uuid:     foo\r\n\r\n", addr)
3369     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3370     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)
3371     sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
3372     with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3373         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)
3374         time.sleep(0.1)
3375     with alloc_fail(dev[0], 2, "wps_er_ap_add"):
3376         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)
3377         time.sleep(0.1)
3378
3379     # Add an AP with bogus URL
3380     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)
3381     # Update timeout on AP without updating URL
3382     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)
3383     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3384     if ev is None:
3385         raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3386
3387     # Add an AP with a valid URL (but no server listing to it)
3388     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)
3389     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3390     if ev is None:
3391         raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3392
3393     sock.close()
3394
3395 wps_event_url = None
3396
3397 def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
3398                   udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
3399     payload = '''<?xml version="1.0"?>
3400 <root xmlns="urn:schemas-upnp-org:device-1-0">
3401 <specVersion>
3402 <major>1</major>
3403 <minor>0</minor>
3404 </specVersion>
3405 <device>
3406 <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
3407 <friendlyName>WPS Access Point</friendlyName>
3408 <manufacturer>Company</manufacturer>
3409 <modelName>WAP</modelName>
3410 <modelNumber>123</modelNumber>
3411 <serialNumber>12345</serialNumber>
3412 '''
3413     if udn:
3414         payload += '<UDN>' + udn + '</UDN>'
3415     payload += '''<serviceList>
3416 <service>
3417 <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
3418 <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
3419 <SCPDURL>wps_scpd.xml</SCPDURL>
3420 '''
3421     if controlURL:
3422         payload += '<controlURL>' + controlURL + '</controlURL>\n'
3423     if eventSubURL:
3424         payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
3425     payload += '''</service>
3426 </serviceList>
3427 </device>
3428 </root>
3429 '''
3430     hdr = 'HTTP/1.1 200 OK\r\n' + \
3431           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3432           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3433           'Connection: close\r\n' + \
3434           'Content-Length: ' + str(len(payload)) + '\r\n' + \
3435           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3436     return hdr + payload
3437
3438 def gen_wps_control(payload_override=None):
3439     payload = '''<?xml version="1.0"?>
3440 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
3441 <s:Body>
3442 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
3443 <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
3444 Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
3445 +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
3446 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
3447 KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
3448 AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
3449 AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
3450 AAYANyoAASA=
3451 </NewDeviceInfo>
3452 </u:GetDeviceInfoResponse>
3453 </s:Body>
3454 </s:Envelope>
3455 '''
3456     if payload_override:
3457         payload = payload_override
3458     hdr = 'HTTP/1.1 200 OK\r\n' + \
3459           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3460           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3461           'Connection: close\r\n' + \
3462           'Content-Length: ' + str(len(payload)) + '\r\n' + \
3463           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3464     return hdr + payload
3465
3466 def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
3467     payload = ""
3468     hdr = 'HTTP/1.1 200 OK\r\n' + \
3469           'Content-Type: text/xml; charset="utf-8"\r\n' + \
3470           'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3471           'Connection: close\r\n' + \
3472           'Content-Length: ' + str(len(payload)) + '\r\n'
3473     if sid:
3474         hdr += 'SID: ' + sid + '\r\n'
3475     hdr += 'Timeout: Second-1801\r\n' + \
3476           'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3477     return hdr + payload
3478
3479 class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
3480     def handle(self):
3481         data = self.rfile.readline().strip()
3482         logger.info("HTTP server received: " + data)
3483         while True:
3484             hdr = self.rfile.readline().strip()
3485             if len(hdr) == 0:
3486                 break
3487             logger.info("HTTP header: " + hdr)
3488             if "CALLBACK:" in hdr:
3489                 global wps_event_url
3490                 wps_event_url = hdr.split(' ')[1].strip('<>')
3491
3492         if "GET /foo.xml" in data:
3493             self.handle_upnp_info()
3494         elif "POST /wps_control" in data:
3495             self.handle_wps_control()
3496         elif "SUBSCRIBE /wps_event" in data:
3497             self.handle_wps_event()
3498         else:
3499             self.handle_others(data)
3500
3501     def handle_upnp_info(self):
3502         self.wfile.write(gen_upnp_info())
3503
3504     def handle_wps_control(self):
3505         self.wfile.write(gen_wps_control())
3506
3507     def handle_wps_event(self):
3508         self.wfile.write(gen_wps_event())
3509
3510     def handle_others(self, data):
3511         logger.info("Ignore HTTP request: " + data)
3512
3513 class MyTCPServer(SocketServer.TCPServer):
3514     def __init__(self, addr, handler):
3515         self.allow_reuse_address = True
3516         SocketServer.TCPServer.__init__(self, addr, handler)
3517
3518 def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
3519                  location_url=None):
3520     socket.setdefaulttimeout(1)
3521     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3522     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3523     sock.bind(("239.255.255.250", 1900))
3524     dev.request("WPS_ER_START ifname=lo")
3525     for i in range(100):
3526         (msg,addr) = sock.recvfrom(1000)
3527         logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3528         if "M-SEARCH" in msg:
3529             break
3530         if not wait_m_search:
3531             raise Exception("Not an M-SEARCH")
3532         if i == 99:
3533             raise Exception("No M-SEARCH seen")
3534
3535     # Add an AP with a valid URL and server listing to it
3536     server = MyTCPServer(("127.0.0.1", 12345), http_server)
3537     if not location_url:
3538         location_url = 'http://127.0.0.1:12345/foo.xml'
3539     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)
3540     server.timeout = 1
3541     return server,sock
3542
3543 def wps_er_stop(dev, sock, server, on_alloc_fail=False):
3544     sock.close()
3545     server.server_close()
3546
3547     if on_alloc_fail:
3548         done = False
3549         for i in range(50):
3550             res = dev.request("GET_ALLOC_FAIL")
3551             if res.startswith("0:"):
3552                 done = True
3553                 break
3554             time.sleep(0.1)
3555         if not done:
3556             raise Exception("No allocation failure reported")
3557     else:
3558         ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3559         if ev is None:
3560             raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3561     dev.request("WPS_ER_STOP")
3562
3563 def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
3564     try:
3565         uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
3566         server,sock = wps_er_start(dev, handler, location_url=location_url)
3567         global wps_event_url
3568         wps_event_url = None
3569         server.handle_request()
3570         server.handle_request()
3571         server.handle_request()
3572         server.server_close()
3573         if no_event_url:
3574             if wps_event_url:
3575                 raise Exception("Received event URL unexpectedly")
3576             return
3577         if wps_event_url is None:
3578             raise Exception("Did not get event URL")
3579         logger.info("Event URL: " + wps_event_url)
3580     finally:
3581             dev.request("WPS_ER_STOP")
3582
3583 def send_wlanevent(url, uuid, data):
3584     conn = httplib.HTTPConnection(url.netloc)
3585     payload = '''<?xml version="1.0" encoding="utf-8"?>
3586 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
3587 <e:property><STAStatus>1</STAStatus></e:property>
3588 <e:property><APStatus>1</APStatus></e:property>
3589 <e:property><WLANEvent>'''
3590     payload += base64.b64encode(data)
3591     payload += '</WLANEvent></e:property></e:propertyset>'
3592     headers = { "Content-type": 'text/xml; charset="utf-8"',
3593                 "Server": "Unspecified, UPnP/1.0, Unspecified",
3594                 "HOST": url.netloc,
3595                 "NT": "upnp:event",
3596                 "SID": "uuid:" + uuid,
3597                 "SEQ": "0",
3598                 "Content-Length": str(len(payload)) }
3599     conn.request("NOTIFY", url.path, payload, headers)
3600     resp = conn.getresponse()
3601     if resp.status != 200:
3602         raise Exception("Unexpected HTTP response: %d" % resp.status)
3603
3604 def test_ap_wps_er_http_proto(dev, apdev):
3605     """WPS ER HTTP protocol testing"""
3606     try:
3607         _test_ap_wps_er_http_proto(dev, apdev)
3608     finally:
3609         dev[0].request("WPS_ER_STOP")
3610
3611 def _test_ap_wps_er_http_proto(dev, apdev):
3612     uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
3613     server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
3614     global wps_event_url
3615     wps_event_url = None
3616     server.handle_request()
3617     server.handle_request()
3618     server.handle_request()
3619     server.server_close()
3620     if wps_event_url is None:
3621         raise Exception("Did not get event URL")
3622     logger.info("Event URL: " + wps_event_url)
3623
3624     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3625     if ev is None:
3626         raise Exception("No WPS-ER-AP-ADD event")
3627     if uuid not in ev:
3628         raise Exception("UUID mismatch")
3629
3630     sock.close()
3631
3632     logger.info("Valid Probe Request notification")
3633     url = urlparse.urlparse(wps_event_url)
3634     conn = httplib.HTTPConnection(url.netloc)
3635     payload = '''<?xml version="1.0" encoding="utf-8"?>
3636 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
3637 <e:property><STAStatus>1</STAStatus></e:property>
3638 <e:property><APStatus>1</APStatus></e:property>
3639 <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
3640 EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
3641 RGV2aWNlIEEQSQAGADcqAAEg
3642 </WLANEvent></e:property>
3643 </e:propertyset>
3644 '''
3645     headers = { "Content-type": 'text/xml; charset="utf-8"',
3646                 "Server": "Unspecified, UPnP/1.0, Unspecified",
3647                 "HOST": url.netloc,
3648                 "NT": "upnp:event",
3649                 "SID": "uuid:" + uuid,
3650                 "SEQ": "0",
3651                 "Content-Length": str(len(payload)) }
3652     conn.request("NOTIFY", url.path, payload, headers)
3653     resp = conn.getresponse()
3654     if resp.status != 200:
3655         raise Exception("Unexpected HTTP response: %d" % resp.status)
3656
3657     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
3658     if ev is None:
3659         raise Exception("No WPS-ER-ENROLLEE-ADD event")
3660     if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
3661         raise Exception("No Enrollee UUID match")
3662
3663     logger.info("Incorrect event URL AP id")
3664     conn = httplib.HTTPConnection(url.netloc)
3665     conn.request("NOTIFY", url.path + '123', payload, headers)
3666     resp = conn.getresponse()
3667     if resp.status != 404:
3668         raise Exception("Unexpected HTTP response: %d" % resp.status)
3669
3670     logger.info("Missing AP id")
3671     conn = httplib.HTTPConnection(url.netloc)
3672     conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
3673                  payload, headers)
3674     time.sleep(0.1)
3675
3676     logger.info("Incorrect event URL event id")
3677     conn = httplib.HTTPConnection(url.netloc)
3678     conn.request("NOTIFY", '/event/123456789/123', payload, headers)
3679     time.sleep(0.1)
3680
3681     logger.info("Incorrect event URL prefix")
3682     conn = httplib.HTTPConnection(url.netloc)
3683     conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
3684     resp = conn.getresponse()
3685     if resp.status != 404:
3686         raise Exception("Unexpected HTTP response: %d" % resp.status)
3687
3688     logger.info("Unsupported request")
3689     conn = httplib.HTTPConnection(url.netloc)
3690     conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
3691     resp = conn.getresponse()
3692     if resp.status != 501:
3693         raise Exception("Unexpected HTTP response: %d" % resp.status)
3694
3695     logger.info("Unsupported request and OOM")
3696     with alloc_fail(dev[0], 1, "wps_er_http_req"):
3697         conn = httplib.HTTPConnection(url.netloc)
3698         conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
3699         time.sleep(0.5)
3700
3701     logger.info("Too short WLANEvent")
3702     data = '\x00'
3703     send_wlanevent(url, uuid, data)
3704
3705     logger.info("Invalid WLANEventMAC")
3706     data = '\x00qwertyuiopasdfghjklzxcvbnm'
3707     send_wlanevent(url, uuid, data)
3708
3709     logger.info("Unknown WLANEventType")
3710     data = '\xff02:00:00:00:00:00'
3711     send_wlanevent(url, uuid, data)
3712
3713     logger.info("Probe Request notification without any attributes")
3714     data = '\x0102:00:00:00:00:00'
3715     send_wlanevent(url, uuid, data)
3716
3717     logger.info("Probe Request notification with invalid attribute")
3718     data = '\x0102:00:00:00:00:00\xff'
3719     send_wlanevent(url, uuid, data)
3720
3721     logger.info("EAP message without any attributes")
3722     data = '\x0202:00:00:00:00:00'
3723     send_wlanevent(url, uuid, data)
3724
3725     logger.info("EAP message with invalid attribute")
3726     data = '\x0202:00:00:00:00:00\xff'
3727     send_wlanevent(url, uuid, data)
3728
3729     logger.info("EAP message from new STA and not M1")
3730     data = '\x0202:ff:ff:ff:ff:ff' + '\x10\x22\x00\x01\x05'
3731     send_wlanevent(url, uuid, data)
3732
3733     logger.info("EAP message: M1")
3734     data = '\x0202:00:00:00:00:00'
3735     data += '\x10\x22\x00\x01\x04'
3736     data += '\x10\x47\x00\x10' + 16*'\x00'
3737     data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
3738     data += '\x10\x1a\x00\x10' + 16*'\x00'
3739     data += '\x10\x32\x00\xc0' + 192*'\x00'
3740     data += '\x10\x04\x00\x02\x00\x00'
3741     data += '\x10\x10\x00\x02\x00\x00'
3742     data += '\x10\x0d\x00\x01\x00'
3743     data += '\x10\x08\x00\x02\x00\x00'
3744     data += '\x10\x44\x00\x01\x00'
3745     data += '\x10\x21\x00\x00'
3746     data += '\x10\x23\x00\x00'
3747     data += '\x10\x24\x00\x00'
3748     data += '\x10\x42\x00\x00'
3749     data += '\x10\x54\x00\x08' + 8*'\x00'
3750     data += '\x10\x11\x00\x00'
3751     data += '\x10\x3c\x00\x01\x00'
3752     data += '\x10\x02\x00\x02\x00\x00'
3753     data += '\x10\x12\x00\x02\x00\x00'
3754     data += '\x10\x09\x00\x02\x00\x00'
3755     data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
3756     m1 = data
3757     send_wlanevent(url, uuid, data)
3758
3759     logger.info("EAP message: WSC_ACK")
3760     data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0d'
3761     send_wlanevent(url, uuid, data)
3762
3763     logger.info("EAP message: M1")
3764     send_wlanevent(url, uuid, m1)
3765
3766     logger.info("EAP message: WSC_NACK")
3767     data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0e'
3768     send_wlanevent(url, uuid, data)
3769
3770     logger.info("EAP message: M1 - Too long attribute values")
3771     data = '\x0202:00:00:00:00:00'
3772     data += '\x10\x11\x00\x21' + 33*'\x00'
3773     data += '\x10\x45\x00\x21' + 33*'\x00'
3774     data += '\x10\x42\x00\x21' + 33*'\x00'
3775     data += '\x10\x24\x00\x21' + 33*'\x00'
3776     data += '\x10\x23\x00\x21' + 33*'\x00'
3777     data += '\x10\x21\x00\x41' + 65*'\x00'
3778     data += '\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
3779     send_wlanevent(url, uuid, data)
3780
3781     logger.info("EAP message: M1 missing UUID-E")
3782     data = '\x0202:00:00:00:00:00'
3783     data += '\x10\x22\x00\x01\x04'
3784     send_wlanevent(url, uuid, data)
3785
3786     logger.info("EAP message: M1 missing MAC Address")
3787     data += '\x10\x47\x00\x10' + 16*'\x00'
3788     send_wlanevent(url, uuid, data)
3789
3790     logger.info("EAP message: M1 missing Enrollee Nonce")
3791     data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
3792     send_wlanevent(url, uuid, data)
3793
3794     logger.info("EAP message: M1 missing Public Key")
3795     data += '\x10\x1a\x00\x10' + 16*'\x00'
3796     send_wlanevent(url, uuid, data)
3797
3798     logger.info("EAP message: M1 missing Authentication Type flags")
3799     data += '\x10\x32\x00\xc0' + 192*'\x00'
3800     send_wlanevent(url, uuid, data)
3801
3802     logger.info("EAP message: M1 missing Encryption Type Flags")
3803     data += '\x10\x04\x00\x02\x00\x00'
3804     send_wlanevent(url, uuid, data)
3805
3806     logger.info("EAP message: M1 missing Connection Type flags")
3807     data += '\x10\x10\x00\x02\x00\x00'
3808     send_wlanevent(url, uuid, data)
3809
3810     logger.info("EAP message: M1 missing Config Methods")
3811     data += '\x10\x0d\x00\x01\x00'
3812     send_wlanevent(url, uuid, data)
3813
3814     logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
3815     data += '\x10\x08\x00\x02\x00\x00'
3816     send_wlanevent(url, uuid, data)
3817
3818     logger.info("EAP message: M1 missing Manufacturer")
3819     data += '\x10\x44\x00\x01\x00'
3820     send_wlanevent(url, uuid, data)
3821
3822     logger.info("EAP message: M1 missing Model Name")
3823     data += '\x10\x21\x00\x00'
3824     send_wlanevent(url, uuid, data)
3825
3826     logger.info("EAP message: M1 missing Model Number")
3827     data += '\x10\x23\x00\x00'
3828     send_wlanevent(url, uuid, data)
3829
3830     logger.info("EAP message: M1 missing Serial Number")
3831     data += '\x10\x24\x00\x00'
3832     send_wlanevent(url, uuid, data)
3833
3834     logger.info("EAP message: M1 missing Primary Device Type")
3835     data += '\x10\x42\x00\x00'
3836     send_wlanevent(url, uuid, data)
3837
3838     logger.info("EAP message: M1 missing Device Name")
3839     data += '\x10\x54\x00\x08' + 8*'\x00'
3840     send_wlanevent(url, uuid, data)
3841
3842     logger.info("EAP message: M1 missing RF Bands")
3843     data += '\x10\x11\x00\x00'
3844     send_wlanevent(url, uuid, data)
3845
3846     logger.info("EAP message: M1 missing Association State")
3847     data += '\x10\x3c\x00\x01\x00'
3848     send_wlanevent(url, uuid, data)
3849
3850     logger.info("EAP message: M1 missing Device Password ID")
3851     data += '\x10\x02\x00\x02\x00\x00'
3852     send_wlanevent(url, uuid, data)
3853
3854     logger.info("EAP message: M1 missing Configuration Error")
3855     data += '\x10\x12\x00\x02\x00\x00'
3856     send_wlanevent(url, uuid, data)
3857
3858     logger.info("EAP message: M1 missing OS Version")
3859     data += '\x10\x09\x00\x02\x00\x00'
3860     send_wlanevent(url, uuid, data)
3861
3862     logger.info("Check max concurrent requests")
3863     addr = (url.hostname, url.port)
3864     socks = {}
3865     for i in range(20):
3866         socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
3867                                  socket.IPPROTO_TCP)
3868         socks[i].connect(addr)
3869     for i in range(20):
3870         socks[i].send("GET / HTTP/1.1\r\n\r\n")
3871     count = 0
3872     for i in range(20):
3873         try:
3874             res = socks[i].recv(100)
3875             if "HTTP/1" in res:
3876                 count += 1
3877         except:
3878             pass
3879         socks[i].close()
3880     logger.info("%d concurrent HTTP GET operations returned response" % count)
3881     if count < 10:
3882         raise Exception("Too few concurrent HTTP connections accepted")
3883
3884     logger.info("OOM in HTTP server")
3885     for func in [ "http_request_init", "httpread_create",
3886                   "eloop_register_timeout;httpread_create",
3887                   "eloop_register_sock;httpread_create",
3888                   "httpread_hdr_analyze" ]:
3889         with alloc_fail(dev[0], 1, func):
3890             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
3891                                  socket.IPPROTO_TCP)
3892             sock.connect(addr)
3893             sock.send("GET / HTTP/1.1\r\n\r\n")
3894             try:
3895                 sock.recv(100)
3896             except:
3897                 pass
3898             sock.close()
3899
3900     logger.info("Invalid HTTP header")
3901     for req in [ " GET / HTTP/1.1\r\n\r\n",
3902                  "HTTP/1.1 200 OK\r\n\r\n",
3903                  "HTTP/\r\n\r\n",
3904                  "GET %%a%aa% HTTP/1.1\r\n\r\n",
3905                  "GET / HTTP/1.1\r\n FOO\r\n\r\n",
3906                  "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
3907                  "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
3908                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
3909                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
3910                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
3911                  "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
3912         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
3913                              socket.IPPROTO_TCP)
3914         sock.settimeout(0.1)
3915         sock.connect(addr)
3916         sock.send(req)
3917         try:
3918             sock.recv(100)
3919         except:
3920             pass
3921         sock.close()
3922
3923     with alloc_fail(dev[0], 2, "httpread_read_handler"):
3924         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
3925                              socket.IPPROTO_TCP)
3926         sock.connect(addr)
3927         sock.send("NOTIFY / HTTP/1.1\r\n\r\n" + 4500*'a')
3928         try:
3929             sock.recv(100)
3930         except:
3931             pass
3932         sock.close()
3933
3934     conn = httplib.HTTPConnection(url.netloc)
3935     payload = '<foo'
3936     headers = { "Content-type": 'text/xml; charset="utf-8"',
3937                 "Server": "Unspecified, UPnP/1.0, Unspecified",
3938                 "HOST": url.netloc,
3939                 "NT": "upnp:event",
3940                 "SID": "uuid:" + uuid,
3941                 "SEQ": "0",
3942                 "Content-Length": str(len(payload)) }
3943     conn.request("NOTIFY", url.path, payload, headers)
3944     resp = conn.getresponse()
3945     if resp.status != 200:
3946         raise Exception("Unexpected HTTP response: %d" % resp.status)
3947
3948     conn = httplib.HTTPConnection(url.netloc)
3949     payload = '<WLANEvent foo></WLANEvent>'
3950     headers = { "Content-type": 'text/xml; charset="utf-8"',
3951                 "Server": "Unspecified, UPnP/1.0, Unspecified",
3952                 "HOST": url.netloc,
3953                 "NT": "upnp:event",
3954                 "SID": "uuid:" + uuid,
3955                 "SEQ": "0",
3956                 "Content-Length": str(len(payload)) }
3957     conn.request("NOTIFY", url.path, payload, headers)
3958     resp = conn.getresponse()
3959     if resp.status != 200:
3960         raise Exception("Unexpected HTTP response: %d" % resp.status)
3961
3962     with alloc_fail(dev[0], 1, "xml_get_first_item"):
3963         send_wlanevent(url, uuid, '')
3964
3965     with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
3966         send_wlanevent(url, uuid, 'foo')
3967
3968     for func in [ "wps_init",
3969                   "wps_process_manufacturer",
3970                   "wps_process_model_name",
3971                   "wps_process_model_number",
3972                   "wps_process_serial_number",
3973                   "wps_process_dev_name" ]:
3974         with alloc_fail(dev[0], 1, func):
3975             send_wlanevent(url, uuid, m1)
3976
3977 def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
3978     """WPS ER HTTP protocol testing - no eventSubURL"""
3979     class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
3980         def handle_upnp_info(self):
3981             self.wfile.write(gen_upnp_info(eventSubURL=None))
3982     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
3983                           no_event_url=True)
3984
3985 def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
3986     """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
3987     class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
3988         def handle_upnp_info(self):
3989             self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
3990     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
3991                           no_event_url=True)
3992
3993 def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
3994     """WPS ER HTTP protocol testing - subscribe OOM"""
3995     try:
3996         _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
3997     finally:
3998         dev[0].request("WPS_ER_STOP")
3999
4000 def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4001     tests = [ (1, "http_client_url_parse"),
4002               (1, "wpabuf_alloc;wps_er_subscribe"),
4003               (1, "http_client_addr"),
4004               (1, "eloop_register_sock;http_client_addr"),
4005               (1, "eloop_register_timeout;http_client_addr") ]
4006     for count,func in tests:
4007         with alloc_fail(dev[0], count, func):
4008             server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
4009             server.handle_request()
4010             server.handle_request()
4011             wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
4012
4013 def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4014     """WPS ER HTTP protocol testing - no SID"""
4015     class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4016         def handle_wps_event(self):
4017             self.wfile.write(gen_wps_event(sid=None))
4018     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4019
4020 def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4021     """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4022     class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4023         def handle_wps_event(self):
4024             self.wfile.write(gen_wps_event(sid='FOO'))
4025     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4026
4027 def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4028     """WPS ER HTTP protocol testing - invalid SID UUID"""
4029     class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4030         def handle_wps_event(self):
4031             self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4032     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4033
4034 def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4035     """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4036     class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4037         def handle_wps_event(self):
4038             payload = ""
4039             hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4040                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4041                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4042                   'Connection: close\r\n' + \
4043                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4044                   'Timeout: Second-1801\r\n' + \
4045                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4046             self.wfile.write(hdr + payload)
4047     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4048
4049 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4050     """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4051     class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4052         def handle_wps_event(self):
4053             payload = ""
4054             hdr = 'HTTP/1.1 FOO\r\n' + \
4055                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4056                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4057                   'Connection: close\r\n' + \
4058                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4059                   'Timeout: Second-1801\r\n' + \
4060                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4061             self.wfile.write(hdr + payload)
4062     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4063
4064 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4065     """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4066     class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4067         def handle_wps_control(self):
4068             payload = '''<?xml version="1.0"?>
4069 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4070 <s:Body>
4071 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4072 <NewDeviceInfo>Rk9P</NewDeviceInfo>
4073 </u:GetDeviceInfoResponse>
4074 </s:Body>
4075 </s:Envelope>
4076 '''
4077             self.wfile.write(gen_wps_control(payload_override=payload))
4078     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4079
4080 def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4081     """WPS ER HTTP protocol testing - No device in UPnP info"""
4082     class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4083         def handle_upnp_info(self):
4084             payload = '''<?xml version="1.0"?>
4085 <root xmlns="urn:schemas-upnp-org:device-1-0">
4086 <specVersion>
4087 <major>1</major>
4088 <minor>0</minor>
4089 </specVersion>
4090 </root>
4091 '''
4092             hdr = 'HTTP/1.1 200 OK\r\n' + \
4093                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4094                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4095                   'Connection: close\r\n' + \
4096                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4097                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4098             self.wfile.write(hdr + payload)
4099     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4100
4101 def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4102     """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4103     class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4104         def handle_upnp_info(self):
4105             payload = '''<?xml version="1.0"?>
4106 <root xmlns="urn:schemas-upnp-org:device-1-0">
4107 <specVersion>
4108 <major>1</major>
4109 <minor>0</minor>
4110 </specVersion>
4111 <device>
4112 </device>
4113 </root>
4114 '''
4115             hdr = 'HTTP/1.1 200 OK\r\n' + \
4116                   'Content-Type: text/xml; charset="utf-8"\r\n' + \
4117                   'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4118                   'Connection: close\r\n' + \
4119                   'Content-Length: ' + str(len(payload)) + '\r\n' + \
4120                   'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4121             self.wfile.write(hdr + payload)
4122     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4123
4124 def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4125     """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4126     class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4127         def handle_upnp_info(self):
4128             self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4129     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4130
4131 def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4132     """WPS ER HTTP protocol testing - no controlURL"""
4133     class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4134         def handle_upnp_info(self):
4135             self.wfile.write(gen_upnp_info(controlURL=None))
4136     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4137                           no_event_url=True)
4138
4139 def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4140     """WPS ER HTTP protocol testing - DNS name in controlURL"""
4141     class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4142         def handle_upnp_info(self):
4143             self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4144     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4145                           no_event_url=True)
4146
4147 def test_ap_wps_http_timeout(dev, apdev):
4148     """WPS AP/ER and HTTP timeout"""
4149     try:
4150         _test_ap_wps_http_timeout(dev, apdev)
4151     finally:
4152         dev[0].request("WPS_ER_STOP")
4153
4154 def _test_ap_wps_http_timeout(dev, apdev):
4155     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4156     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
4157
4158     location = ssdp_get_location(ap_uuid)
4159     url = urlparse.urlparse(location)
4160     addr = (url.hostname, url.port)
4161     logger.debug("Open HTTP connection to hostapd, but do not complete request")
4162     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4163                          socket.IPPROTO_TCP)
4164     sock.connect(addr)
4165     sock.send("G")
4166
4167     class DummyServer(SocketServer.StreamRequestHandler):
4168         def handle(self):
4169             logger.debug("DummyServer - start 31 sec wait")
4170             time.sleep(31)
4171             logger.debug("DummyServer - wait done")
4172
4173     logger.debug("Start WPS ER")
4174     server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4175                                 wait_m_search=True)
4176
4177     logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4178     # This will wait for 31 seconds..
4179     server.handle_request()
4180
4181     logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4182     try:
4183         sock.send("ET / HTTP/1.1\r\n\r\n")
4184         res = sock.recv(100)
4185         sock.close()
4186     except:
4187         pass
4188
4189 def test_ap_wps_er_url_parse(dev, apdev):
4190     """WPS ER and URL parsing special cases"""
4191     try:
4192         _test_ap_wps_er_url_parse(dev, apdev)
4193     finally:
4194         dev[0].request("WPS_ER_STOP")
4195
4196 def _test_ap_wps_er_url_parse(dev, apdev):
4197     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4198     sock.settimeout(1)
4199     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4200     sock.bind(("239.255.255.250", 1900))
4201     dev[0].request("WPS_ER_START ifname=lo")
4202     (msg,addr) = sock.recvfrom(1000)
4203     logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4204     if "M-SEARCH" not in msg:
4205         raise Exception("Not an M-SEARCH")
4206     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)
4207     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4208     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)
4209     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4210     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)
4211     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4212
4213     sock.close()
4214
4215 def test_ap_wps_er_link_update(dev, apdev):
4216     """WPS ER and link update special cases"""
4217     class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4218         def handle_upnp_info(self):
4219             self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4220     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4221
4222     class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4223         def handle_others(self, data):
4224             if "GET / " in data:
4225                 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4226     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4227                           location_url='http://127.0.0.1:12345')
4228
4229 def test_ap_wps_er_http_client(dev, apdev):
4230     """WPS ER and HTTP client special cases"""
4231     with alloc_fail(dev[0], 1, "http_link_update"):
4232         run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4233
4234     with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4235         run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4236
4237     with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4238         run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4239
4240     class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4241         def handle_upnp_info(self):
4242             self.wfile.write("GET / HTTP/1.1\r\n\r\n")
4243     run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4244                           no_event_url=True)
4245
4246 def test_ap_wps_init_oom(dev, apdev):
4247     """wps_init OOM cases"""
4248     ssid = "test-wps"
4249     appin = "12345670"
4250     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4251                "ap_pin": appin }
4252     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4253     pin = dev[0].wps_read_pin()
4254
4255     with alloc_fail(hapd, 1, "wps_init"):
4256         hapd.request("WPS_PIN any " + pin)
4257         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4258         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4259         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4260         if ev is None:
4261             raise Exception("No EAP failure reported")
4262         dev[0].request("WPS_CANCEL")
4263
4264     with alloc_fail(dev[0], 2, "wps_init"):
4265         hapd.request("WPS_PIN any " + pin)
4266         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4267         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4268         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4269         if ev is None:
4270             raise Exception("No EAP failure reported")
4271         dev[0].request("WPS_CANCEL")
4272
4273     with alloc_fail(dev[0], 2, "wps_init"):
4274         hapd.request("WPS_PBC")
4275         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4276         dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4277         ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4278         if ev is None:
4279             raise Exception("No EAP failure reported")
4280         dev[0].request("WPS_CANCEL")
4281
4282     dev[0].dump_monitor()
4283     new_ssid = "wps-new-ssid"
4284     new_passphrase = "1234567890"
4285     with alloc_fail(dev[0], 3, "wps_init"):
4286         dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4287                        new_passphrase, no_wait=True)
4288         ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4289         if ev is None:
4290             raise Exception("No EAP failure reported")
4291
4292     dev[0].flush_scan_cache()
4293
4294 def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4295     """WPS and invalid IE in Association Request frame"""
4296     ssid = "test-wps"
4297     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4298     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4299     pin = "12345670"
4300     hapd.request("WPS_PIN any " + pin)
4301     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4302     try:
4303         dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4304         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4305         for i in range(5):
4306             ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4307             if ev and "vendor=14122" in ev:
4308                 break
4309         if ev is None or "vendor=14122" not in ev:
4310             raise Exception("EAP-WSC not started")
4311         dev[0].request("WPS_CANCEL")
4312     finally:
4313         dev[0].request("VENDOR_ELEM_REMOVE 13 *")
4314
4315 def test_ap_wps_pbc_pin_mismatch(dev, apdev):
4316     """WPS PBC/PIN mismatch"""
4317     ssid = "test-wps"
4318     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4319     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4320     hapd.request("SET wps_version_number 0x10")
4321     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4322     hapd.request("WPS_PBC")
4323     pin = dev[0].wps_read_pin()
4324     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4325     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4326     if ev is None:
4327         raise Exception("Scan did not complete")
4328     dev[0].request("WPS_CANCEL")
4329
4330     hapd.request("WPS_CANCEL")
4331     dev[0].flush_scan_cache()
4332
4333 def test_ap_wps_ie_invalid(dev, apdev):
4334     """WPS PIN attempt with AP that has invalid WSC IE"""
4335     ssid = "test-wps"
4336     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4337                "vendor_elements": "dd050050f20410" }
4338     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4339     params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
4340     hostapd.add_ap(apdev[1]['ifname'], params)
4341     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4342     pin = dev[0].wps_read_pin()
4343     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4344     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4345     if ev is None:
4346         raise Exception("Scan did not complete")
4347     dev[0].request("WPS_CANCEL")
4348
4349 def test_ap_wps_scan_prio_order(dev, apdev):
4350     """WPS scan priority ordering"""
4351     ssid = "test-wps"
4352     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4353     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4354     params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
4355     hostapd.add_ap(apdev[1]['ifname'], params)
4356     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4357     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4358     pin = dev[0].wps_read_pin()
4359     dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4360     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4361     if ev is None:
4362         raise Exception("Scan did not complete")
4363     dev[0].request("WPS_CANCEL")
4364
4365 def test_ap_wps_probe_req_ie_oom(dev, apdev):
4366     """WPS ProbeReq IE OOM"""
4367     ssid = "test-wps"
4368     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4369     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4370     pin = dev[0].wps_read_pin()
4371     hapd.request("WPS_PIN any " + pin)
4372     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4373     with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
4374         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4375         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4376         if ev is None:
4377             raise Exception("Association not seen")
4378     dev[0].request("WPS_CANCEL")
4379
4380     with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
4381         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4382         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4383         if ev is None:
4384             raise Exception("Association not seen")
4385     dev[0].request("WPS_CANCEL")
4386
4387 def test_ap_wps_assoc_req_ie_oom(dev, apdev):
4388     """WPS AssocReq IE OOM"""
4389     ssid = "test-wps"
4390     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4391     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4392     pin = dev[0].wps_read_pin()
4393     hapd.request("WPS_PIN any " + pin)
4394     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4395     with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
4396         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4397         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4398         if ev is None:
4399             raise Exception("Association not seen")
4400     dev[0].request("WPS_CANCEL")
4401
4402 def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
4403     """WPS AssocResp IE OOM"""
4404     ssid = "test-wps"
4405     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4406     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4407     pin = dev[0].wps_read_pin()
4408     hapd.request("WPS_PIN any " + pin)
4409     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4410     with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
4411         dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4412         ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
4413         if ev is None:
4414             raise Exception("Association not seen")
4415     dev[0].request("WPS_CANCEL")
4416
4417 def test_ap_wps_bss_info_errors(dev, apdev):
4418     """WPS BSS info errors"""
4419     params = { "ssid": "1",
4420                "vendor_elements": "dd0e0050f20410440001ff101100010a" }
4421     hostapd.add_ap(apdev[0]['ifname'], params)
4422     params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
4423     hostapd.add_ap(apdev[1]['ifname'], params)
4424     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4425     dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4426     bss = dev[0].get_bss(apdev[0]['bssid'])
4427     logger.info("BSS: " + str(bss))
4428     if "wps_state" in bss:
4429         raise Exception("Unexpected wps_state in BSS info")
4430     if 'wps_device_name' not in bss:
4431         raise Exception("No wps_device_name in BSS info")
4432     if bss['wps_device_name'] != '_':
4433         raise Exception("Unexpected wps_device_name value")
4434     bss = dev[0].get_bss(apdev[1]['bssid'])
4435     logger.info("BSS: " + str(bss))
4436
4437     with alloc_fail(dev[0], 1, "=wps_attr_text"):
4438         bss = dev[0].get_bss(apdev[0]['bssid'])
4439         logger.info("BSS(OOM): " + str(bss))
4440
4441 def wps_run_pbc_fail_ap(apdev, dev, hapd):
4442     hapd.request("WPS_PBC")
4443     dev.scan_for_bss(apdev['bssid'], freq="2412")
4444     dev.request("WPS_PBC " + apdev['bssid'])
4445     ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4446     if ev is None:
4447         raise Exception("No EAP failure reported")
4448     dev.request("WPS_CANCEL")
4449     dev.wait_disconnected()
4450     for i in range(5):
4451         try:
4452             dev.flush_scan_cache()
4453             break
4454         except Exception, e:
4455             if str(e).startswith("Failed to trigger scan"):
4456                 # Try again
4457                 time.sleep(1)
4458             else:
4459                 raise
4460
4461 def wps_run_pbc_fail(apdev, dev):
4462     hapd = wps_start_ap(apdev)
4463     wps_run_pbc_fail_ap(apdev, dev, hapd)
4464
4465 def test_ap_wps_pk_oom(dev, apdev):
4466     """WPS and public key OOM"""
4467     with alloc_fail(dev[0], 1, "wps_build_public_key"):
4468         wps_run_pbc_fail(apdev[0], dev[0])
4469
4470 def test_ap_wps_pk_oom_ap(dev, apdev):
4471     """WPS and public key OOM on AP"""
4472     hapd = wps_start_ap(apdev[0])
4473     with alloc_fail(hapd, 1, "wps_build_public_key"):
4474         wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4475
4476 def test_ap_wps_encr_oom_ap(dev, apdev):
4477     """WPS and encrypted settings decryption OOM on AP"""
4478     hapd = wps_start_ap(apdev[0])
4479     pin = dev[0].wps_read_pin()
4480     hapd.request("WPS_PIN any " + pin)
4481     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4482     with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
4483         dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
4484         ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
4485         if ev is None:
4486             raise Exception("No WPS-FAIL reported")
4487         dev[0].request("WPS_CANCEL")
4488     dev[0].wait_disconnected()
4489
4490 def test_ap_wps_encr_no_random_ap(dev, apdev):
4491     """WPS and no random data available for encryption on AP"""
4492     hapd = wps_start_ap(apdev[0])
4493     with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
4494         wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4495
4496 def test_ap_wps_e_hash_no_random_sta(dev, apdev):
4497     """WPS and no random data available for e-hash on STA"""
4498     with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
4499         wps_run_pbc_fail(apdev[0], dev[0])
4500
4501 def test_ap_wps_m1_no_random(dev, apdev):
4502     """WPS and no random for M1 on STA"""
4503     with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
4504         wps_run_pbc_fail(apdev[0], dev[0])
4505
4506 def test_ap_wps_m1_oom(dev, apdev):
4507     """WPS and OOM for M1 on STA"""
4508     with alloc_fail(dev[0], 1, "wps_build_m1"):
4509         wps_run_pbc_fail(apdev[0], dev[0])
4510
4511 def test_ap_wps_m3_oom(dev, apdev):
4512     """WPS and OOM for M3 on STA"""
4513     with alloc_fail(dev[0], 1, "wps_build_m3"):
4514         wps_run_pbc_fail(apdev[0], dev[0])
4515
4516 def test_ap_wps_m5_oom(dev, apdev):
4517     """WPS and OOM for M5 on STA"""
4518     hapd = wps_start_ap(apdev[0])
4519     hapd.request("WPS_PBC")
4520     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4521     for i in range(1, 3):
4522         with alloc_fail(dev[0], i, "wps_build_m5"):
4523             dev[0].request("WPS_PBC " + apdev[0]['bssid'])
4524             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4525             if ev is None:
4526                 raise Exception("No EAP failure reported")
4527             dev[0].request("WPS_CANCEL")
4528             dev[0].wait_disconnected()
4529     dev[0].flush_scan_cache()
4530
4531 def test_ap_wps_m5_no_random(dev, apdev):
4532     """WPS and no random for M5 on STA"""
4533     with fail_test(dev[0], 1,
4534                    "os_get_random;wps_build_encr_settings;wps_build_m5"):
4535         wps_run_pbc_fail(apdev[0], dev[0])
4536
4537 def test_ap_wps_m7_oom(dev, apdev):
4538     """WPS and OOM for M7 on STA"""
4539     hapd = wps_start_ap(apdev[0])
4540     hapd.request("WPS_PBC")
4541     dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4542     for i in range(1, 3):
4543         with alloc_fail(dev[0], i, "wps_build_m7"):
4544             dev[0].request("WPS_PBC " + apdev[0]['bssid'])
4545             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4546             if ev is None:
4547                 raise Exception("No EAP failure reported")
4548             dev[0].request("WPS_CANCEL")
4549             dev[0].wait_disconnected()
4550     dev[0].flush_scan_cache()
4551
4552 def test_ap_wps_m7_no_random(dev, apdev):
4553     """WPS and no random for M7 on STA"""
4554     with fail_test(dev[0], 1,
4555                    "os_get_random;wps_build_encr_settings;wps_build_m7"):
4556         wps_run_pbc_fail(apdev[0], dev[0])
4557
4558 def test_ap_wps_wsc_done_oom(dev, apdev):
4559     """WPS and OOM for WSC_Done on STA"""
4560     with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
4561         wps_run_pbc_fail(apdev[0], dev[0])
4562
4563 def test_ap_wps_random_psk_fail(dev, apdev):
4564     """WPS and no random for PSK on AP"""
4565     ssid = "test-wps"
4566     pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
4567     appin = "12345670"
4568     try:
4569         os.remove(pskfile)
4570     except:
4571         pass
4572
4573     try:
4574         with open(pskfile, "w") as f:
4575             f.write("# WPA PSKs\n")
4576
4577         params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4578                    "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
4579                    "rsn_pairwise": "CCMP", "ap_pin": appin,
4580                    "wpa_psk_file": pskfile }
4581         hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4582
4583         dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4584         with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
4585             dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
4586             ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4587             if ev is None:
4588                 raise Exception("No EAP failure reported")
4589             dev[0].request("WPS_CANCEL")
4590         dev[0].wait_disconnected()
4591
4592         with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
4593             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4594
4595         with alloc_fail(hapd, 1, "wps_build_cred"):
4596             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4597
4598         with alloc_fail(hapd, 2, "wps_build_cred"):
4599             wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
4600     finally:
4601         os.remove(pskfile)
4602
4603 def wps_ext_eap_identity_req(dev, hapd, bssid):
4604     logger.debug("EAP-Identity/Request")
4605     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
4606     if ev is None:
4607         raise Exception("Timeout on EAPOL-TX from hostapd")
4608     res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
4609     if "OK" not in res:
4610         raise Exception("EAPOL_RX to wpa_supplicant failed")
4611
4612 def wps_ext_eap_identity_resp(hapd, dev, addr):
4613     ev = dev.wait_event(["EAPOL-TX"], timeout=10)
4614     if ev is None:
4615         raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
4616     res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
4617     if "OK" not in res:
4618         raise Exception("EAPOL_RX to hostapd failed")
4619
4620 def wps_ext_eap_wsc(dst, src, src_addr, msg):
4621     logger.debug(msg)
4622     ev = src.wait_event(["EAPOL-TX"], timeout=10)
4623     if ev is None:
4624         raise Exception("Timeout on EAPOL-TX")
4625     res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
4626     if "OK" not in res:
4627         raise Exception("EAPOL_RX failed")
4628
4629 def wps_start_ext(apdev, dev):
4630     addr = dev.own_addr()
4631     bssid = apdev['bssid']
4632     ssid = "test-wps-conf"
4633     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4634                "wpa_passphrase": "12345678", "wpa": "2",
4635                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
4636     hapd = hostapd.add_ap(apdev['ifname'], params)
4637
4638     pin = dev.wps_read_pin()
4639     hapd.request("WPS_PIN any " + pin)
4640     dev.scan_for_bss(bssid, freq="2412")
4641     hapd.request("SET ext_eapol_frame_io 1")
4642     dev.request("SET ext_eapol_frame_io 1")
4643
4644     dev.request("WPS_PIN " + bssid + " " + pin)
4645     return addr,bssid,hapd
4646
4647 def wps_auth_corrupt(dst, src, addr):
4648     ev = src.wait_event(["EAPOL-TX"], timeout=10)
4649     if ev is None:
4650         raise Exception("Timeout on EAPOL-TX")
4651     src.request("SET ext_eapol_frame_io 0")
4652     dst.request("SET ext_eapol_frame_io 0")
4653     msg = ev.split(' ')[2]
4654     if msg[-24:-16] != '10050008':
4655         raise Exception("Could not find Authenticator attribute")
4656     # Corrupt Authenticator value
4657     msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
4658     res = dst.request("EAPOL_RX " + addr + " " + msg)
4659     if "OK" not in res:
4660         raise Exception("EAPOL_RX failed")
4661
4662 def wps_fail_finish(hapd, dev, fail_str):
4663     ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
4664     if ev is None:
4665         raise Exception("WPS-FAIL not indicated")
4666     if fail_str not in ev:
4667         raise Exception("Unexpected WPS-FAIL value: " + ev)
4668     dev.request("WPS_CANCEL")
4669     dev.wait_disconnected()
4670
4671 def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
4672     wps_auth_corrupt(dev, hapd, bssid)
4673     wps_fail_finish(hapd, dev, fail_str)
4674
4675 def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
4676     wps_auth_corrupt(hapd, dev, addr)
4677     wps_fail_finish(hapd, dev, fail_str)
4678
4679 def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
4680     """WPS and Authenticator attribute mismatch in M2"""
4681     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4682     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4683     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4684     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4685     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4686     logger.debug("M2")
4687     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
4688
4689 def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
4690     """WPS and Authenticator attribute mismatch in M3"""
4691     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4692     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4693     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4694     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4695     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4696     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4697     logger.debug("M3")
4698     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
4699
4700 def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
4701     """WPS and Authenticator attribute mismatch in M4"""
4702     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4703     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4704     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4705     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4706     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4707     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4708     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4709     logger.debug("M4")
4710     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
4711
4712 def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
4713     """WPS and Authenticator attribute mismatch in M5"""
4714     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4715     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4716     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4717     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4718     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4719     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4720     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4721     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
4722     logger.debug("M5")
4723     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
4724
4725 def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
4726     """WPS and Authenticator attribute mismatch in M6"""
4727     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4728     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4729     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4730     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4731     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4732     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4733     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4734     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
4735     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
4736     logger.debug("M6")
4737     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
4738
4739 def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
4740     """WPS and Authenticator attribute mismatch in M7"""
4741     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4742     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4743     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4744     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4745     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4746     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4747     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4748     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
4749     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
4750     wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
4751     logger.debug("M7")
4752     wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
4753
4754 def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
4755     """WPS and Authenticator attribute mismatch in M8"""
4756     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4757     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4758     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4759     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4760     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4761     wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
4762     wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
4763     wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
4764     wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
4765     wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
4766     wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
4767     logger.debug("M8")
4768     wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
4769
4770 def test_ap_wps_authenticator_missing_m2(dev, apdev):
4771     """WPS and Authenticator attribute missing from M2"""
4772     addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
4773     wps_ext_eap_identity_req(dev[0], hapd, bssid)
4774     wps_ext_eap_identity_resp(hapd, dev[0], addr)
4775     wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
4776     wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
4777     logger.debug("M2")
4778     ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
4779     if ev is None:
4780         raise Exception("Timeout on EAPOL-TX")
4781     hapd.request("SET ext_eapol_frame_io 0")
4782     dev[0].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     # Remove Authenticator value
4787     msg = msg[:-24]
4788     mlen = "%04x" % (int(msg[4:8], 16) - 12)
4789     msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
4790     res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
4791     if "OK" not in res:
4792         raise Exception("EAPOL_RX failed")
4793     wps_fail_finish(hapd, dev[0], "msg=5")
4794
4795 def test_ap_wps_config_methods(dev, apdev):
4796     """WPS configuration method parsing"""
4797     ssid = "test-wps-conf"
4798     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4799                "wpa_passphrase": "12345678", "wpa": "2",
4800                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
4801                "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
4802     hapd = hostapd.add_ap(apdev[0]['ifname'], params)
4803     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4804                "wpa_passphrase": "12345678", "wpa": "2",
4805                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
4806                "config_methods": "display push_button" }
4807     hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
4808
4809 def test_ap_wps_set_selected_registrar_proto(dev, apdev):
4810     """WPS UPnP SetSelectedRegistrar protocol testing"""
4811     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4812     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
4813
4814     location = ssdp_get_location(ap_uuid)
4815     urls = upnp_get_urls(location)
4816     eventurl = urlparse.urlparse(urls['event_sub_url'])
4817     ctrlurl = urlparse.urlparse(urls['control_url'])
4818     url = urlparse.urlparse(location)
4819     conn = httplib.HTTPConnection(url.netloc)
4820
4821     class WPSERHTTPServer(SocketServer.StreamRequestHandler):
4822         def handle(self):
4823             data = self.rfile.readline().strip()
4824             logger.debug(data)
4825             self.wfile.write(gen_wps_event())
4826
4827     server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
4828     server.timeout = 1
4829
4830     headers = { "callback": '<http://127.0.0.1:12345/event>',
4831                 "NT": "upnp:event",
4832                 "timeout": "Second-1234" }
4833     conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
4834     resp = conn.getresponse()
4835     if resp.status != 200:
4836         raise Exception("Unexpected HTTP response: %d" % resp.status)
4837     sid = resp.getheader("sid")
4838     logger.debug("Subscription SID " + sid)
4839     server.handle_request()
4840
4841     tests = [ (500, "10"),
4842               (200, "104a000110" + "1041000101" + "101200020000" +
4843                "105300023148" +
4844                "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
4845                "10480010362db47ba53a519188fb5458b986b2e4"),
4846               (200, "104a000110" + "1041000100" + "101200020000" +
4847                "105300020000"),
4848               (200, "104a000110" + "1041000100"),
4849               (200, "104a000110") ]
4850     for status,test in tests:
4851         tlvs = binascii.unhexlify(test)
4852         newmsg = base64.b64encode(tlvs)
4853         msg = '<?xml version="1.0"?>\n'
4854         msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
4855         msg += '<s:Body>'
4856         msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
4857         msg += '<NewMessage>'
4858         msg += newmsg
4859         msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
4860         headers = { "Content-type": 'text/xml; charset="utf-8"' }
4861         headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
4862         conn.request("POST", ctrlurl.path, msg, headers)
4863         resp = conn.getresponse()
4864         if resp.status != status:
4865             raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
4866
4867 def test_ap_wps_adv_oom(dev, apdev):
4868     """WPS AP and advertisement OOM"""
4869     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4870     hapd = add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
4871
4872     with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
4873         ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
4874                           no_recv=True)
4875         time.sleep(0.2)
4876
4877     with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
4878         ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
4879                           no_recv=True)
4880         time.sleep(0.2)
4881
4882     with alloc_fail(hapd, 1,
4883                     "next_advertisement;advertisement_state_machine_stop"):
4884         hapd.disable()
4885
4886     with alloc_fail(hapd, 1, "ssdp_listener_start"):
4887         if "FAIL" not in hapd.request("ENABLE"):
4888             raise Exception("ENABLE succeeded during OOM")