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