tests: WPS UPnP SSDP testing
[mech_eap.git] / tests / hwsim / test_ap_wps.py
1 # WPS tests
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import time
8 import subprocess
9 import logging
10 logger = logging.getLogger()
11 import re
12 import socket
13
14 import hwsim_utils
15 import hostapd
16
17 def test_ap_wps_init(dev, apdev):
18     """Initial AP configuration with first WPS Enrollee"""
19     ssid = "test-wps"
20     hostapd.add_ap(apdev[0]['ifname'],
21                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
22     hapd = hostapd.Hostapd(apdev[0]['ifname'])
23     logger.info("WPS provisioning step")
24     hapd.request("WPS_PBC")
25     if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
26         raise Exception("PBC status not shown correctly")
27     dev[0].dump_monitor()
28     dev[0].request("WPS_PBC")
29     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
30     if ev is None:
31         raise Exception("Association with the AP timed out")
32     status = dev[0].get_status()
33     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
34         raise Exception("Not fully connected")
35     if status['ssid'] != ssid:
36         raise Exception("Unexpected SSID")
37     if status['pairwise_cipher'] != 'CCMP':
38         raise Exception("Unexpected encryption configuration")
39     if status['key_mgmt'] != 'WPA2-PSK':
40         raise Exception("Unexpected key_mgmt")
41
42     status = hapd.request("WPS_GET_STATUS")
43     if "PBC Status: Disabled" not in status:
44         raise Exception("PBC status not shown correctly")
45     if "Last WPS result: Success" not in status:
46         raise Exception("Last WPS result not shown correctly")
47     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
48         raise Exception("Peer address not shown correctly")
49     conf = hapd.request("GET_CONFIG")
50     if "wps_state=configured" not in conf:
51         raise Exception("AP not in WPS configured state")
52     if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
53         raise Exception("Unexpected rsn_pairwise_cipher")
54     if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
55         raise Exception("Unexpected wpa_pairwise_cipher")
56     if "group_cipher=TKIP" not in conf:
57         raise Exception("Unexpected group_cipher")
58
59 def test_ap_wps_init_2ap_pbc(dev, apdev):
60     """Initial two-radio AP configuration with first WPS PBC Enrollee"""
61     ssid = "test-wps"
62     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
63     hostapd.add_ap(apdev[0]['ifname'], params)
64     hostapd.add_ap(apdev[1]['ifname'], params)
65     hapd = hostapd.Hostapd(apdev[0]['ifname'])
66     logger.info("WPS provisioning step")
67     hapd.request("WPS_PBC")
68     dev[0].scan(freq="2412")
69     bss = dev[0].get_bss(apdev[0]['bssid'])
70     if "[WPS-PBC]" not in bss['flags']:
71         raise Exception("WPS-PBC flag missing from AP1")
72     bss = dev[0].get_bss(apdev[1]['bssid'])
73     if "[WPS-PBC]" not in bss['flags']:
74         raise Exception("WPS-PBC flag missing from AP2")
75     dev[0].dump_monitor()
76     dev[0].request("WPS_PBC")
77     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
78     if ev is None:
79         raise Exception("Association with the AP timed out")
80
81     dev[1].scan(freq="2412")
82     bss = dev[1].get_bss(apdev[0]['bssid'])
83     if "[WPS-PBC]" in bss['flags']:
84         raise Exception("WPS-PBC flag not cleared from AP1")
85     bss = dev[1].get_bss(apdev[1]['bssid'])
86     if "[WPS-PBC]" in bss['flags']:
87         raise Exception("WPS-PBC flag bit ckeared from AP2")
88
89 def test_ap_wps_init_2ap_pin(dev, apdev):
90     """Initial two-radio AP configuration with first WPS PIN Enrollee"""
91     ssid = "test-wps"
92     params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
93     hostapd.add_ap(apdev[0]['ifname'], params)
94     hostapd.add_ap(apdev[1]['ifname'], params)
95     hapd = hostapd.Hostapd(apdev[0]['ifname'])
96     logger.info("WPS provisioning step")
97     pin = dev[0].wps_read_pin()
98     hapd.request("WPS_PIN any " + pin)
99     dev[0].scan(freq="2412")
100     bss = dev[0].get_bss(apdev[0]['bssid'])
101     if "[WPS-AUTH]" not in bss['flags']:
102         raise Exception("WPS-AUTH flag missing from AP1")
103     bss = dev[0].get_bss(apdev[1]['bssid'])
104     if "[WPS-AUTH]" not in bss['flags']:
105         raise Exception("WPS-AUTH flag missing from AP2")
106     dev[0].dump_monitor()
107     dev[0].request("WPS_PIN any " + pin)
108     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
109     if ev is None:
110         raise Exception("Association with the AP timed out")
111
112     dev[1].scan(freq="2412")
113     bss = dev[1].get_bss(apdev[0]['bssid'])
114     if "[WPS-AUTH]" in bss['flags']:
115         raise Exception("WPS-AUTH flag not cleared from AP1")
116     bss = dev[1].get_bss(apdev[1]['bssid'])
117     if "[WPS-AUTH]" in bss['flags']:
118         raise Exception("WPS-AUTH flag bit ckeared from AP2")
119
120 def test_ap_wps_init_through_wps_config(dev, apdev):
121     """Initial AP configuration using wps_config command"""
122     ssid = "test-wps-init-config"
123     hostapd.add_ap(apdev[0]['ifname'],
124                    { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
125     hapd = hostapd.Hostapd(apdev[0]['ifname'])
126     if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
127         raise Exception("WPS_CONFIG command failed")
128     dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
129                    pairwise="CCMP", group="CCMP")
130
131 def test_ap_wps_conf(dev, apdev):
132     """WPS PBC provisioning with configured AP"""
133     ssid = "test-wps-conf"
134     hostapd.add_ap(apdev[0]['ifname'],
135                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
136                      "wpa_passphrase": "12345678", "wpa": "2",
137                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
138     hapd = hostapd.Hostapd(apdev[0]['ifname'])
139     logger.info("WPS provisioning step")
140     hapd.request("WPS_PBC")
141     dev[0].dump_monitor()
142     dev[0].request("WPS_PBC")
143     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
144     if ev is None:
145         raise Exception("Association with the AP timed out")
146     status = dev[0].get_status()
147     if status['wpa_state'] != 'COMPLETED':
148         raise Exception("Not fully connected")
149     if status['bssid'] != apdev[0]['bssid']:
150         raise Exception("Unexpected BSSID")
151     if status['ssid'] != ssid:
152         raise Exception("Unexpected SSID")
153     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
154         raise Exception("Unexpected encryption configuration")
155     if status['key_mgmt'] != 'WPA2-PSK':
156         raise Exception("Unexpected key_mgmt")
157
158     sta = hapd.get_sta(dev[0].p2p_interface_addr())
159     if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
160         raise Exception("Device name not available in STA command")
161
162 def test_ap_wps_twice(dev, apdev):
163     """WPS provisioning with twice to change passphrase"""
164     ssid = "test-wps-twice"
165     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
166                "wpa_passphrase": "12345678", "wpa": "2",
167                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
168     hostapd.add_ap(apdev[0]['ifname'], params)
169     hapd = hostapd.Hostapd(apdev[0]['ifname'])
170     logger.info("WPS provisioning step")
171     hapd.request("WPS_PBC")
172     dev[0].dump_monitor()
173     dev[0].request("WPS_PBC")
174     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
175     if ev is None:
176         raise Exception("Association with the AP timed out")
177     dev[0].request("DISCONNECT")
178
179     logger.info("Restart AP with different passphrase and re-run WPS")
180     hapd_global = hostapd.HostapdGlobal()
181     hapd_global.remove(apdev[0]['ifname'])
182     params['wpa_passphrase'] = 'another passphrase'
183     hostapd.add_ap(apdev[0]['ifname'], params)
184     hapd = hostapd.Hostapd(apdev[0]['ifname'])
185     logger.info("WPS provisioning step")
186     hapd.request("WPS_PBC")
187     dev[0].dump_monitor()
188     dev[0].request("WPS_PBC")
189     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
190     if ev is None:
191         raise Exception("Association with the AP timed out")
192     networks = dev[0].list_networks()
193     if len(networks) > 1:
194         raise Exception("Unexpected duplicated network block present")
195
196 def test_ap_wps_incorrect_pin(dev, apdev):
197     """WPS PIN provisioning with incorrect PIN"""
198     ssid = "test-wps-incorrect-pin"
199     hostapd.add_ap(apdev[0]['ifname'],
200                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
201                      "wpa_passphrase": "12345678", "wpa": "2",
202                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
203     hapd = hostapd.Hostapd(apdev[0]['ifname'])
204
205     logger.info("WPS provisioning attempt 1")
206     hapd.request("WPS_PIN any 12345670")
207     dev[0].dump_monitor()
208     dev[0].request("WPS_PIN any 55554444")
209     ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
210     if ev is None:
211         raise Exception("WPS operation timed out")
212     if "config_error=18" not in ev:
213         raise Exception("Incorrect config_error reported")
214     if "msg=8" not in ev:
215         raise Exception("PIN error detected on incorrect message")
216     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
217     if ev is None:
218         raise Exception("Timeout on disconnection event")
219     dev[0].request("WPS_CANCEL")
220     # if a scan was in progress, wait for it to complete before trying WPS again
221     ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
222
223     status = hapd.request("WPS_GET_STATUS")
224     if "Last WPS result: Failed" not in status:
225         raise Exception("WPS failure result not shown correctly")
226
227     logger.info("WPS provisioning attempt 2")
228     hapd.request("WPS_PIN any 12345670")
229     dev[0].dump_monitor()
230     dev[0].request("WPS_PIN any 12344444")
231     ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
232     if ev is None:
233         raise Exception("WPS operation timed out")
234     if "config_error=18" not in ev:
235         raise Exception("Incorrect config_error reported")
236     if "msg=10" not in ev:
237         raise Exception("PIN error detected on incorrect message")
238     ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
239     if ev is None:
240         raise Exception("Timeout on disconnection event")
241
242 def test_ap_wps_conf_pin(dev, apdev):
243     """WPS PIN provisioning with configured AP"""
244     ssid = "test-wps-conf-pin"
245     hostapd.add_ap(apdev[0]['ifname'],
246                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
247                      "wpa_passphrase": "12345678", "wpa": "2",
248                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
249     hapd = hostapd.Hostapd(apdev[0]['ifname'])
250     logger.info("WPS provisioning step")
251     pin = dev[0].wps_read_pin()
252     hapd.request("WPS_PIN any " + pin)
253     dev[0].dump_monitor()
254     dev[0].request("WPS_PIN any " + pin)
255     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
256     if ev is None:
257         raise Exception("Association with the AP timed out")
258     status = dev[0].get_status()
259     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
260         raise Exception("Not fully connected")
261     if status['ssid'] != ssid:
262         raise Exception("Unexpected SSID")
263     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
264         raise Exception("Unexpected encryption configuration")
265     if status['key_mgmt'] != 'WPA2-PSK':
266         raise Exception("Unexpected key_mgmt")
267
268     dev[1].scan(freq="2412")
269     bss = dev[1].get_bss(apdev[0]['bssid'])
270     if "[WPS-AUTH]" in bss['flags']:
271         raise Exception("WPS-AUTH flag not cleared")
272     logger.info("Try to connect from another station using the same PIN")
273     dev[1].request("WPS_PIN any " + pin)
274     ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
275     if ev is None:
276         raise Exception("Operation timed out")
277     if "WPS-M2D" not in ev:
278         raise Exception("Unexpected WPS operation started")
279
280 def test_ap_wps_conf_pin_2sta(dev, apdev):
281     """Two stations trying to use WPS PIN at the same time"""
282     ssid = "test-wps-conf-pin2"
283     hostapd.add_ap(apdev[0]['ifname'],
284                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
285                      "wpa_passphrase": "12345678", "wpa": "2",
286                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
287     hapd = hostapd.Hostapd(apdev[0]['ifname'])
288     logger.info("WPS provisioning step")
289     pin = "12345670"
290     pin2 = "55554444"
291     hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
292     hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
293     dev[0].dump_monitor()
294     dev[1].dump_monitor()
295     dev[0].request("WPS_PIN any " + pin)
296     dev[1].request("WPS_PIN any " + pin)
297     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
298     if ev is None:
299         raise Exception("Association with the AP timed out")
300     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
301     if ev is None:
302         raise Exception("Association with the AP timed out")
303
304 def test_ap_wps_reg_connect(dev, apdev):
305     """WPS registrar using AP PIN to connect"""
306     ssid = "test-wps-reg-ap-pin"
307     appin = "12345670"
308     hostapd.add_ap(apdev[0]['ifname'],
309                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
310                      "wpa_passphrase": "12345678", "wpa": "2",
311                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
312                      "ap_pin": appin})
313     logger.info("WPS provisioning step")
314     dev[0].dump_monitor()
315     dev[0].wps_reg(apdev[0]['bssid'], appin)
316     status = dev[0].get_status()
317     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
318         raise Exception("Not fully connected")
319     if status['ssid'] != ssid:
320         raise Exception("Unexpected SSID")
321     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
322         raise Exception("Unexpected encryption configuration")
323     if status['key_mgmt'] != 'WPA2-PSK':
324         raise Exception("Unexpected key_mgmt")
325
326 def check_wps_reg_failure(dev, ap, appin):
327     dev.request("WPS_REG " + ap['bssid'] + " " + appin)
328     ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
329     if ev is None:
330         raise Exception("WPS operation timed out")
331     if "WPS-SUCCESS" in ev:
332         raise Exception("WPS operation succeeded unexpectedly")
333     if "config_error=15" not in ev:
334         raise Exception("WPS setup locked state was not reported correctly")
335
336 def test_ap_wps_random_ap_pin(dev, apdev):
337     """WPS registrar using random AP PIN"""
338     ssid = "test-wps-reg-random-ap-pin"
339     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
340     hostapd.add_ap(apdev[0]['ifname'],
341                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
342                      "wpa_passphrase": "12345678", "wpa": "2",
343                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
344                      "device_name": "Wireless AP", "manufacturer": "Company",
345                      "model_name": "WAP", "model_number": "123",
346                      "serial_number": "12345", "device_type": "6-0050F204-1",
347                      "os_version": "01020300",
348                      "config_methods": "label push_button",
349                      "uuid": ap_uuid, "upnp_iface": "lo" })
350     hapd = hostapd.Hostapd(apdev[0]['ifname'])
351     appin = hapd.request("WPS_AP_PIN random")
352     if "FAIL" in appin:
353         raise Exception("Could not generate random AP PIN")
354     if appin not in hapd.request("WPS_AP_PIN get"):
355         raise Exception("Could not fetch current AP PIN")
356     logger.info("WPS provisioning step")
357     dev[0].wps_reg(apdev[0]['bssid'], appin)
358
359     hapd.request("WPS_AP_PIN disable")
360     logger.info("WPS provisioning step with AP PIN disabled")
361     check_wps_reg_failure(dev[1], apdev[0], appin)
362
363     logger.info("WPS provisioning step with AP PIN reset")
364     appin = "12345670"
365     hapd.request("WPS_AP_PIN set " + appin)
366     dev[1].wps_reg(apdev[0]['bssid'], appin)
367     dev[0].request("REMOVE_NETWORK all")
368     dev[1].request("REMOVE_NETWORK all")
369     dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
370     dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
371
372     logger.info("WPS provisioning step after AP PIN timeout")
373     hapd.request("WPS_AP_PIN disable")
374     appin = hapd.request("WPS_AP_PIN random 1")
375     time.sleep(1.1)
376     if "FAIL" not in hapd.request("WPS_AP_PIN get"):
377         raise Exception("AP PIN unexpectedly still enabled")
378     check_wps_reg_failure(dev[0], apdev[0], appin)
379
380     logger.info("WPS provisioning step after AP PIN timeout(2)")
381     hapd.request("WPS_AP_PIN disable")
382     appin = "12345670"
383     hapd.request("WPS_AP_PIN set " + appin + " 1")
384     time.sleep(1.1)
385     if "FAIL" not in hapd.request("WPS_AP_PIN get"):
386         raise Exception("AP PIN unexpectedly still enabled")
387     check_wps_reg_failure(dev[1], apdev[0], appin)
388
389 def test_ap_wps_reg_config(dev, apdev):
390     """WPS registrar configuring and AP using AP PIN"""
391     ssid = "test-wps-init-ap-pin"
392     appin = "12345670"
393     hostapd.add_ap(apdev[0]['ifname'],
394                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
395                      "ap_pin": appin})
396     logger.info("WPS configuration step")
397     dev[0].dump_monitor()
398     new_ssid = "wps-new-ssid"
399     new_passphrase = "1234567890"
400     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
401                    new_passphrase)
402     status = dev[0].get_status()
403     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
404         raise Exception("Not fully connected")
405     if status['ssid'] != new_ssid:
406         raise Exception("Unexpected SSID")
407     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
408         raise Exception("Unexpected encryption configuration")
409     if status['key_mgmt'] != 'WPA2-PSK':
410         raise Exception("Unexpected key_mgmt")
411
412 def test_ap_wps_reg_config_tkip(dev, apdev):
413     """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
414     ssid = "test-wps-init-ap"
415     appin = "12345670"
416     hostapd.add_ap(apdev[0]['ifname'],
417                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
418                      "ap_pin": appin})
419     logger.info("WPS configuration step")
420     dev[0].request("SET wps_version_number 0x10")
421     dev[0].dump_monitor()
422     new_ssid = "wps-new-ssid-with-tkip"
423     new_passphrase = "1234567890"
424     dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
425                    new_passphrase)
426     logger.info("Re-connect to verify WPA2 mixed mode")
427     dev[0].request("DISCONNECT")
428     id = 0
429     dev[0].set_network(id, "pairwise", "CCMP")
430     dev[0].set_network(id, "proto", "RSN")
431     dev[0].connect_network(id)
432     status = dev[0].get_status()
433     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
434         raise Exception("Not fully connected")
435     if status['ssid'] != new_ssid:
436         raise Exception("Unexpected SSID")
437     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
438         raise Exception("Unexpected encryption configuration")
439     if status['key_mgmt'] != 'WPA2-PSK':
440         raise Exception("Unexpected key_mgmt")
441
442 def test_ap_wps_setup_locked(dev, apdev):
443     """WPS registrar locking up AP setup on AP PIN failures"""
444     ssid = "test-wps-incorrect-ap-pin"
445     appin = "12345670"
446     hostapd.add_ap(apdev[0]['ifname'],
447                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
448                      "wpa_passphrase": "12345678", "wpa": "2",
449                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
450                      "ap_pin": appin})
451     new_ssid = "wps-new-ssid-test"
452     new_passphrase = "1234567890"
453
454     ap_setup_locked=False
455     for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
456         dev[0].dump_monitor()
457         logger.info("Try incorrect AP PIN - attempt " + pin)
458         dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
459                        "CCMP", new_passphrase, no_wait=True)
460         ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
461         if ev is None:
462             raise Exception("Timeout on receiving WPS operation failure event")
463         if "CTRL-EVENT-CONNECTED" in ev:
464             raise Exception("Unexpected connection")
465         if "config_error=15" in ev:
466             logger.info("AP Setup Locked")
467             ap_setup_locked=True
468         elif "config_error=18" not in ev:
469             raise Exception("config_error=18 not reported")
470         ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
471         if ev is None:
472             raise Exception("Timeout on disconnection event")
473         time.sleep(0.1)
474     if not ap_setup_locked:
475         raise Exception("AP setup was not locked")
476
477     hapd = hostapd.Hostapd(apdev[0]['ifname'])
478     status = hapd.request("WPS_GET_STATUS")
479     if "Last WPS result: Failed" not in status:
480         raise Exception("WPS failure result not shown correctly")
481     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
482         raise Exception("Peer address not shown correctly")
483
484     time.sleep(0.5)
485     dev[0].dump_monitor()
486     logger.info("WPS provisioning step")
487     pin = dev[0].wps_read_pin()
488     hapd = hostapd.Hostapd(apdev[0]['ifname'])
489     hapd.request("WPS_PIN any " + pin)
490     dev[0].request("WPS_PIN any " + pin)
491     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
492     if ev is None:
493         raise Exception("WPS success was not reported")
494     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
495     if ev is None:
496         raise Exception("Association with the AP timed out")
497
498 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
499     """WPS PBC session overlap with two active APs"""
500     hostapd.add_ap(apdev[0]['ifname'],
501                    { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
502                      "wpa_passphrase": "12345678", "wpa": "2",
503                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
504                      "wps_independent": "1"})
505     hostapd.add_ap(apdev[1]['ifname'],
506                    { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
507                      "wpa_passphrase": "123456789", "wpa": "2",
508                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
509                      "wps_independent": "1"})
510     hapd = hostapd.Hostapd(apdev[0]['ifname'])
511     hapd.request("WPS_PBC")
512     hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
513     hapd2.request("WPS_PBC")
514     logger.info("WPS provisioning step")
515     dev[0].dump_monitor()
516     dev[0].request("WPS_PBC")
517     ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
518     if ev is None:
519         raise Exception("PBC session overlap not detected")
520
521 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
522     """WPS PBC session overlap with two active STAs"""
523     ssid = "test-wps-pbc-overlap"
524     hostapd.add_ap(apdev[0]['ifname'],
525                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
526                      "wpa_passphrase": "12345678", "wpa": "2",
527                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
528     hapd = hostapd.Hostapd(apdev[0]['ifname'])
529     logger.info("WPS provisioning step")
530     hapd.request("WPS_PBC")
531     dev[0].dump_monitor()
532     dev[1].dump_monitor()
533     dev[0].request("WPS_PBC")
534     dev[1].request("WPS_PBC")
535     ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
536     if ev is None:
537         raise Exception("PBC session overlap not detected (dev0)")
538     if "config_error=12" not in ev:
539         raise Exception("PBC session overlap not correctly reported (dev0)")
540     ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
541     if ev is None:
542         raise Exception("PBC session overlap not detected (dev1)")
543     if "config_error=12" not in ev:
544         raise Exception("PBC session overlap not correctly reported (dev1)")
545     hapd.request("WPS_CANCEL")
546     ret = hapd.request("WPS_PBC")
547     if "FAIL" not in ret:
548         raise Exception("PBC mode allowed to be started while PBC overlap still active")
549
550 def test_ap_wps_cancel(dev, apdev):
551     """WPS AP cancelling enabled config method"""
552     ssid = "test-wps-ap-cancel"
553     hostapd.add_ap(apdev[0]['ifname'],
554                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
555                      "wpa_passphrase": "12345678", "wpa": "2",
556                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
557     bssid = apdev[0]['bssid']
558     hapd = hostapd.Hostapd(apdev[0]['ifname'])
559
560     logger.info("Verify PBC enable/cancel")
561     hapd.request("WPS_PBC")
562     dev[0].scan(freq="2412")
563     bss = dev[0].get_bss(apdev[0]['bssid'])
564     if "[WPS-PBC]" not in bss['flags']:
565         raise Exception("WPS-PBC flag missing")
566     if "FAIL" in hapd.request("WPS_CANCEL"):
567         raise Exception("WPS_CANCEL failed")
568     dev[0].scan(freq="2412")
569     bss = dev[0].get_bss(apdev[0]['bssid'])
570     if "[WPS-PBC]" in bss['flags']:
571         raise Exception("WPS-PBC flag not cleared")
572
573     logger.info("Verify PIN enable/cancel")
574     hapd.request("WPS_PIN any 12345670")
575     dev[0].scan(freq="2412")
576     bss = dev[0].get_bss(apdev[0]['bssid'])
577     if "[WPS-AUTH]" not in bss['flags']:
578         raise Exception("WPS-AUTH flag missing")
579     if "FAIL" in hapd.request("WPS_CANCEL"):
580         raise Exception("WPS_CANCEL failed")
581     dev[0].scan(freq="2412")
582     bss = dev[0].get_bss(apdev[0]['bssid'])
583     if "[WPS-AUTH]" in bss['flags']:
584         raise Exception("WPS-AUTH flag not cleared")
585
586 def test_ap_wps_er_add_enrollee(dev, apdev):
587     """WPS ER configuring AP and adding a new enrollee using PIN"""
588     ssid = "wps-er-add-enrollee"
589     ap_pin = "12345670"
590     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
591     hostapd.add_ap(apdev[0]['ifname'],
592                    { "ssid": ssid, "eap_server": "1", "wps_state": "1",
593                      "device_name": "Wireless AP", "manufacturer": "Company",
594                      "model_name": "WAP", "model_number": "123",
595                      "serial_number": "12345", "device_type": "6-0050F204-1",
596                      "os_version": "01020300",
597                      "config_methods": "label push_button",
598                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
599     logger.info("WPS configuration step")
600     new_passphrase = "1234567890"
601     dev[0].dump_monitor()
602     dev[0].wps_reg(apdev[0]['bssid'], ap_pin, 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'] != 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("Start ER")
615     dev[0].request("WPS_ER_START ifname=lo")
616     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
617     if ev is None:
618         raise Exception("AP discovery timed out")
619     if ap_uuid not in ev:
620         raise Exception("Expected AP UUID not found")
621
622     logger.info("Learn AP configuration through UPnP")
623     dev[0].dump_monitor()
624     dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
625     ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
626     if ev is None:
627         raise Exception("AP learn timed out")
628     if ap_uuid not in ev:
629         raise Exception("Expected AP UUID not in settings")
630     if "ssid=" + ssid not in ev:
631         raise Exception("Expected SSID not in settings")
632     if "key=" + new_passphrase not in ev:
633         raise Exception("Expected passphrase not in settings")
634
635     logger.info("Add Enrollee using ER")
636     pin = dev[1].wps_read_pin()
637     dev[0].dump_monitor()
638     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
639     dev[1].dump_monitor()
640     dev[1].request("WPS_PIN any " + pin)
641     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
642     if ev is None:
643         raise Exception("Enrollee did not report success")
644     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
645     if ev is None:
646         raise Exception("Association with the AP timed out")
647     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
648     if ev is None:
649         raise Exception("WPS ER did not report success")
650     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
651
652     logger.info("Add a specific Enrollee using ER")
653     pin = dev[2].wps_read_pin()
654     addr2 = dev[2].p2p_interface_addr()
655     dev[0].dump_monitor()
656     dev[2].dump_monitor()
657     dev[2].request("WPS_PIN any " + pin)
658     ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
659     if ev is None:
660         raise Exception("Enrollee not seen")
661     if addr2 not in ev:
662         raise Exception("Unexpected Enrollee MAC address")
663     dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
664     ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
665     if ev is None:
666         raise Exception("Association with the AP timed out")
667     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
668     if ev is None:
669         raise Exception("WPS ER did not report success")
670
671     logger.info("Verify registrar selection behavior")
672     dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
673     dev[1].request("DISCONNECT")
674     dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
675     dev[1].scan(freq="2412")
676     bss = dev[1].get_bss(apdev[0]['bssid'])
677     if "[WPS-AUTH]" not in bss['flags']:
678         raise Exception("WPS-AUTH flag missing")
679
680     logger.info("Stop ER")
681     dev[0].dump_monitor()
682     dev[0].request("WPS_ER_STOP")
683     ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
684     if ev is None:
685         raise Exception("WPS ER unsubscription timed out")
686     # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
687     # a bit before verifying that the scan results have change.
688     time.sleep(0.2)
689
690     dev[1].scan(freq="2412")
691     bss = dev[1].get_bss(apdev[0]['bssid'])
692     if "[WPS-AUTH]" in bss['flags']:
693         raise Exception("WPS-AUTH flag not removed")
694
695 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
696     """WPS ER connected to AP and adding a new enrollee using PBC"""
697     ssid = "wps-er-add-enrollee-pbc"
698     ap_pin = "12345670"
699     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
700     hostapd.add_ap(apdev[0]['ifname'],
701                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
702                      "wpa_passphrase": "12345678", "wpa": "2",
703                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
704                      "device_name": "Wireless AP", "manufacturer": "Company",
705                      "model_name": "WAP", "model_number": "123",
706                      "serial_number": "12345", "device_type": "6-0050F204-1",
707                      "os_version": "01020300",
708                      "config_methods": "label push_button",
709                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
710     logger.info("Learn AP configuration")
711     dev[0].dump_monitor()
712     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
713     status = dev[0].get_status()
714     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
715         raise Exception("Not fully connected")
716
717     logger.info("Start ER")
718     dev[0].request("WPS_ER_START ifname=lo")
719     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
720     if ev is None:
721         raise Exception("AP discovery timed out")
722     if ap_uuid not in ev:
723         raise Exception("Expected AP UUID not found")
724
725     logger.info("Use learned network configuration on ER")
726     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
727
728     logger.info("Add Enrollee using ER and PBC")
729     dev[0].dump_monitor()
730     enrollee = dev[1].p2p_interface_addr()
731     dev[1].dump_monitor()
732     dev[1].request("WPS_PBC")
733
734     for i in range(0, 2):
735         ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
736         if ev is None:
737             raise Exception("Enrollee discovery timed out")
738         if enrollee in ev:
739             break
740         if i == 1:
741             raise Exception("Expected Enrollee not found")
742     dev[0].request("WPS_ER_PBC " + enrollee)
743
744     ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
745     if ev is None:
746         raise Exception("Enrollee did not report success")
747     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
748     if ev is None:
749         raise Exception("Association with the AP timed out")
750     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
751     if ev is None:
752         raise Exception("WPS ER did not report success")
753     hwsim_utils.test_connectivity_sta(dev[0], dev[1])
754
755     # verify BSSID selection of the AP instead of UUID
756     if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
757         raise Exception("Could not select AP based on BSSID")
758
759 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
760     """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
761     ssid = "wps-er-add-enrollee-pbc"
762     ap_pin = "12345670"
763     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
764     hostapd.add_ap(apdev[0]['ifname'],
765                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
766                      "wpa_passphrase": "12345678", "wpa": "2",
767                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
768                      "device_name": "Wireless AP", "manufacturer": "Company",
769                      "model_name": "WAP", "model_number": "123",
770                      "serial_number": "12345", "device_type": "6-0050F204-1",
771                      "os_version": "01020300",
772                      "config_methods": "label push_button",
773                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
774     logger.info("Learn AP configuration")
775     dev[0].request("SET wps_version_number 0x10")
776     dev[0].dump_monitor()
777     dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
778     status = dev[0].get_status()
779     if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
780         raise Exception("Not fully connected")
781
782     logger.info("Start ER")
783     dev[0].request("WPS_ER_START ifname=lo")
784     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
785     if ev is None:
786         raise Exception("AP discovery timed out")
787     if ap_uuid not in ev:
788         raise Exception("Expected AP UUID not found")
789
790     logger.info("Use learned network configuration on ER")
791     dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
792
793     logger.info("Add Enrollee using ER and PIN")
794     enrollee = dev[1].p2p_interface_addr()
795     pin = dev[1].wps_read_pin()
796     dev[0].dump_monitor()
797     dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
798     dev[1].dump_monitor()
799     dev[1].request("WPS_PIN any " + pin)
800     ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
801     if ev is None:
802         raise Exception("Association with the AP timed out")
803     ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
804     if ev is None:
805         raise Exception("WPS ER did not report success")
806
807 def test_ap_wps_er_config_ap(dev, apdev):
808     """WPS ER configuring AP over UPnP"""
809     ssid = "wps-er-ap-config"
810     ap_pin = "12345670"
811     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
812     hostapd.add_ap(apdev[0]['ifname'],
813                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
814                      "wpa_passphrase": "12345678", "wpa": "2",
815                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
816                      "device_name": "Wireless AP", "manufacturer": "Company",
817                      "model_name": "WAP", "model_number": "123",
818                      "serial_number": "12345", "device_type": "6-0050F204-1",
819                      "os_version": "01020300",
820                      "config_methods": "label push_button",
821                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
822
823     logger.info("Connect ER to the AP")
824     dev[0].connect(ssid, psk="12345678", scan_freq="2412")
825
826     logger.info("WPS configuration step")
827     dev[0].request("WPS_ER_START ifname=lo")
828     ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
829     if ev is None:
830         raise Exception("AP discovery timed out")
831     if ap_uuid not in ev:
832         raise Exception("Expected AP UUID not found")
833     new_passphrase = "1234567890"
834     dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
835                    ssid.encode("hex") + " WPA2PSK CCMP " +
836                    new_passphrase.encode("hex"))
837     ev = dev[0].wait_event(["WPS-SUCCESS"])
838     if ev is None:
839         raise Exception("WPS ER configuration operation timed out")
840     dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
841     dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
842
843 def test_ap_wps_fragmentation(dev, apdev):
844     """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
845     ssid = "test-wps-fragmentation"
846     hostapd.add_ap(apdev[0]['ifname'],
847                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
848                      "wpa_passphrase": "12345678", "wpa": "3",
849                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
850                      "wpa_pairwise": "TKIP",
851                      "fragment_size": "50" })
852     hapd = hostapd.Hostapd(apdev[0]['ifname'])
853     logger.info("WPS provisioning step")
854     hapd.request("WPS_PBC")
855     dev[0].dump_monitor()
856     dev[0].request("SET wps_fragment_size 50")
857     dev[0].request("WPS_PBC")
858     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
859     if ev is None:
860         raise Exception("Association with the AP timed out")
861     status = dev[0].get_status()
862     if status['wpa_state'] != 'COMPLETED':
863         raise Exception("Not fully connected")
864     if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
865         raise Exception("Unexpected encryption configuration")
866     if status['key_mgmt'] != 'WPA2-PSK':
867         raise Exception("Unexpected key_mgmt")
868
869 def test_ap_wps_new_version_sta(dev, apdev):
870     """WPS compatibility with new version number on the station"""
871     ssid = "test-wps-ver"
872     hostapd.add_ap(apdev[0]['ifname'],
873                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
874                      "wpa_passphrase": "12345678", "wpa": "2",
875                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
876     hapd = hostapd.Hostapd(apdev[0]['ifname'])
877     logger.info("WPS provisioning step")
878     hapd.request("WPS_PBC")
879     dev[0].dump_monitor()
880     dev[0].request("SET wps_version_number 0x43")
881     dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
882     dev[0].request("WPS_PBC")
883     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
884     if ev is None:
885         raise Exception("Association with the AP timed out")
886
887 def test_ap_wps_new_version_ap(dev, apdev):
888     """WPS compatibility with new version number on the AP"""
889     ssid = "test-wps-ver"
890     hostapd.add_ap(apdev[0]['ifname'],
891                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
892                      "wpa_passphrase": "12345678", "wpa": "2",
893                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
894     hapd = hostapd.Hostapd(apdev[0]['ifname'])
895     logger.info("WPS provisioning step")
896     if "FAIL" in hapd.request("SET wps_version_number 0x43"):
897         raise Exception("Failed to enable test functionality")
898     hapd.request("WPS_PBC")
899     dev[0].dump_monitor()
900     dev[0].request("WPS_PBC")
901     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
902     hapd.request("SET wps_version_number 0x20")
903     if ev is None:
904         raise Exception("Association with the AP timed out")
905
906 def test_ap_wps_check_pin(dev, apdev):
907     """Verify PIN checking through control interface"""
908     hostapd.add_ap(apdev[0]['ifname'],
909                    { "ssid": "wps", "eap_server": "1", "wps_state": "2",
910                      "wpa_passphrase": "12345678", "wpa": "2",
911                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
912     hapd = hostapd.Hostapd(apdev[0]['ifname'])
913     for t in [ ("12345670", "12345670"),
914                ("12345678", "FAIL-CHECKSUM"),
915                ("1234-5670", "12345670"),
916                ("1234 5670", "12345670"),
917                ("1-2.3:4 5670", "12345670") ]:
918         res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
919         res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
920         if res != res2:
921             raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
922         if res != t[1]:
923             raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
924
925 def test_ap_wps_wep_config(dev, apdev):
926     """WPS 2.0 AP rejecting WEP configuration"""
927     ssid = "test-wps-config"
928     appin = "12345670"
929     hostapd.add_ap(apdev[0]['ifname'],
930                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
931                      "ap_pin": appin})
932     hapd = hostapd.Hostapd(apdev[0]['ifname'])
933     dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
934                    "hello", no_wait=True)
935     ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
936     if ev is None:
937         raise Exception("WPS-FAIL timed out")
938     if "reason=2" not in ev:
939         raise Exception("Unexpected reason code in WPS-FAIL")
940     status = hapd.request("WPS_GET_STATUS")
941     if "Last WPS result: Failed" not in status:
942         raise Exception("WPS failure result not shown correctly")
943     if "Failure Reason: WEP Prohibited" not in status:
944         raise Exception("Failure reason not reported correctly")
945     if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
946         raise Exception("Peer address not shown correctly")
947
948 def test_ap_wps_ie_fragmentation(dev, apdev):
949     """WPS AP using fragmented WPS IE"""
950     ssid = "test-wps-ie-fragmentation"
951     params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
952                "wpa_passphrase": "12345678", "wpa": "2",
953                "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
954                "device_name": "1234567890abcdef1234567890abcdef",
955                "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
956                "model_name": "1234567890abcdef1234567890abcdef",
957                "model_number": "1234567890abcdef1234567890abcdef",
958                "serial_number": "1234567890abcdef1234567890abcdef" }
959     hostapd.add_ap(apdev[0]['ifname'], params)
960     hapd = hostapd.Hostapd(apdev[0]['ifname'])
961     hapd.request("WPS_PBC")
962     dev[0].request("WPS_PBC")
963     ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
964     if ev is None:
965         raise Exception("Association with the AP timed out")
966     bss = dev[0].get_bss(apdev[0]['bssid'])
967     if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
968         raise Exception("Device Name not received correctly")
969     if len(re.findall("dd..0050f204", bss['ie'])) != 2:
970         raise Exception("Unexpected number of WPS IEs")
971
972 def add_ssdp_ap(ifname, ap_uuid):
973     ssid = "wps-ssdp"
974     ap_pin = "12345670"
975     hostapd.add_ap(ifname,
976                    { "ssid": ssid, "eap_server": "1", "wps_state": "2",
977                      "wpa_passphrase": "12345678", "wpa": "2",
978                      "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
979                      "device_name": "Wireless AP", "manufacturer": "Company",
980                      "model_name": "WAP", "model_number": "123",
981                      "serial_number": "12345", "device_type": "6-0050F204-1",
982                      "os_version": "01020300",
983                      "config_methods": "label push_button",
984                      "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
985                      "friendly_name": "WPS Access Point",
986                      "manufacturer_url": "http://www.example.com/",
987                      "model_description": "Wireless Access Point",
988                      "model_url": "http://www.example.com/model/",
989                      "upc": "123456789012" })
990
991 def ssdp_send(msg, no_recv=False):
992     socket.setdefaulttimeout(1)
993     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
994     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
995     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
996     sock.bind(("127.0.0.1", 0))
997     sock.sendto(msg, ("239.255.255.250", 1900))
998     if no_recv:
999         return None
1000     return sock.recv(1000)
1001
1002 def ssdp_send_msearch(st):
1003     msg = '\r\n'.join([
1004             'M-SEARCH * HTTP/1.1',
1005             'HOST: 239.255.255.250:1900',
1006             'MX: 1',
1007             'MAN: "ssdp:discover"',
1008             'ST: ' + st,
1009             '', ''])
1010     ssdp_send(msg)
1011
1012 def test_ap_wps_ssdp_msearch(dev, apdev):
1013     """WPS AP and SSDP M-SEARCH messages"""
1014     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1015     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1016
1017     msg = '\r\n'.join([
1018             'M-SEARCH * HTTP/1.1',
1019             'Host: 239.255.255.250:1900',
1020             'Mx: 1',
1021             'Man: "ssdp:discover"',
1022             'St: urn:schemas-wifialliance-org:device:WFADevice:1',
1023             '', ''])
1024     ssdp_send(msg)
1025
1026     msg = '\r\n'.join([
1027             'M-SEARCH * HTTP/1.1',
1028             'host:\t239.255.255.250:1900\t\t\t\t \t\t',
1029             'mx: \t1\t\t   ',
1030             'man: \t \t "ssdp:discover"   ',
1031             'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
1032             '', ''])
1033     ssdp_send(msg)
1034
1035     ssdp_send_msearch("ssdp:all")
1036     ssdp_send_msearch("upnp:rootdevice")
1037     ssdp_send_msearch("uuid:" + ap_uuid)
1038     ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
1039     ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
1040
1041     msg = '\r\n'.join([
1042             'M-SEARCH * HTTP/1.1',
1043             'HOST:\t239.255.255.250:1900',
1044             'MAN: "ssdp:discover"',
1045             'MX: 130',
1046             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1047             '', ''])
1048     ssdp_send(msg, no_recv=True)
1049
1050 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
1051     """WPS AP and invalid SSDP M-SEARCH messages"""
1052     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1053     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1054
1055     socket.setdefaulttimeout(1)
1056     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1057     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1058     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1059     sock.bind(("127.0.0.1", 0))
1060
1061     logger.debug("Missing MX")
1062     msg = '\r\n'.join([
1063             'M-SEARCH * HTTP/1.1',
1064             'HOST: 239.255.255.250:1900',
1065             'MAN: "ssdp:discover"',
1066             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1067             '', ''])
1068     sock.sendto(msg, ("239.255.255.250", 1900))
1069
1070     logger.debug("Negative MX")
1071     msg = '\r\n'.join([
1072             'M-SEARCH * HTTP/1.1',
1073             'HOST: 239.255.255.250:1900',
1074             'MX: -1',
1075             'MAN: "ssdp:discover"',
1076             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1077             '', ''])
1078     sock.sendto(msg, ("239.255.255.250", 1900))
1079
1080     logger.debug("Invalid MX")
1081     msg = '\r\n'.join([
1082             'M-SEARCH * HTTP/1.1',
1083             'HOST: 239.255.255.250:1900',
1084             'MX; 1',
1085             'MAN: "ssdp:discover"',
1086             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1087             '', ''])
1088     sock.sendto(msg, ("239.255.255.250", 1900))
1089
1090     logger.debug("Missing MAN")
1091     msg = '\r\n'.join([
1092             'M-SEARCH * HTTP/1.1',
1093             'HOST: 239.255.255.250:1900',
1094             'MX: 1',
1095             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1096             '', ''])
1097     sock.sendto(msg, ("239.255.255.250", 1900))
1098
1099     logger.debug("Invalid MAN")
1100     msg = '\r\n'.join([
1101             'M-SEARCH * HTTP/1.1',
1102             'HOST: 239.255.255.250:1900',
1103             'MX: 1',
1104             'MAN: foo',
1105             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1106             '', ''])
1107     sock.sendto(msg, ("239.255.255.250", 1900))
1108     msg = '\r\n'.join([
1109             'M-SEARCH * HTTP/1.1',
1110             'HOST: 239.255.255.250:1900',
1111             'MX: 1',
1112             'MAN; "ssdp:discover"',
1113             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1114             '', ''])
1115     sock.sendto(msg, ("239.255.255.250", 1900))
1116
1117     logger.debug("Missing HOST")
1118     msg = '\r\n'.join([
1119             'M-SEARCH * HTTP/1.1',
1120             'MAN: "ssdp:discover"',
1121             'MX: 1',
1122             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1123             '', ''])
1124     sock.sendto(msg, ("239.255.255.250", 1900))
1125
1126     logger.debug("Missing ST")
1127     msg = '\r\n'.join([
1128             'M-SEARCH * HTTP/1.1',
1129             'HOST: 239.255.255.250:1900',
1130             'MAN: "ssdp:discover"',
1131             'MX: 1',
1132             '', ''])
1133     sock.sendto(msg, ("239.255.255.250", 1900))
1134
1135     logger.debug("Mismatching ST")
1136     msg = '\r\n'.join([
1137             'M-SEARCH * HTTP/1.1',
1138             'HOST: 239.255.255.250:1900',
1139             'MAN: "ssdp:discover"',
1140             'MX: 1',
1141             'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
1142             '', ''])
1143     sock.sendto(msg, ("239.255.255.250", 1900))
1144     msg = '\r\n'.join([
1145             'M-SEARCH * HTTP/1.1',
1146             'HOST: 239.255.255.250:1900',
1147             'MAN: "ssdp:discover"',
1148             'MX: 1',
1149             'ST: foo:bar',
1150             '', ''])
1151     sock.sendto(msg, ("239.255.255.250", 1900))
1152     msg = '\r\n'.join([
1153             'M-SEARCH * HTTP/1.1',
1154             'HOST: 239.255.255.250:1900',
1155             'MAN: "ssdp:discover"',
1156             'MX: 1',
1157             'ST: foobar',
1158             '', ''])
1159     sock.sendto(msg, ("239.255.255.250", 1900))
1160
1161     logger.debug("Invalid ST")
1162     msg = '\r\n'.join([
1163             'M-SEARCH * HTTP/1.1',
1164             'HOST: 239.255.255.250:1900',
1165             'MAN: "ssdp:discover"',
1166             'MX: 1',
1167             'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
1168             '', ''])
1169     sock.sendto(msg, ("239.255.255.250", 1900))
1170
1171     logger.debug("Invalid M-SEARCH")
1172     msg = '\r\n'.join([
1173             'M+SEARCH * HTTP/1.1',
1174             'HOST: 239.255.255.250:1900',
1175             'MAN: "ssdp:discover"',
1176             'MX: 1',
1177             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1178             '', ''])
1179     sock.sendto(msg, ("239.255.255.250", 1900))
1180     msg = '\r\n'.join([
1181             'M-SEARCH-* HTTP/1.1',
1182             'HOST: 239.255.255.250:1900',
1183             'MAN: "ssdp:discover"',
1184             'MX: 1',
1185             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1186             '', ''])
1187     sock.sendto(msg, ("239.255.255.250", 1900))
1188
1189     logger.debug("Invalid message format")
1190     sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
1191     msg = '\r'.join([
1192             'M-SEARCH * HTTP/1.1',
1193             'HOST: 239.255.255.250:1900',
1194             'MAN: "ssdp:discover"',
1195             'MX: 1',
1196             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1197             '', ''])
1198     sock.sendto(msg, ("239.255.255.250", 1900))
1199
1200     try:
1201         r = sock.recv(1000)
1202         raise Exception("Unexpected M-SEARCH response: " + r)
1203     except socket.timeout:
1204         pass
1205
1206     logger.debug("Valid M-SEARCH")
1207     msg = '\r\n'.join([
1208             'M-SEARCH * HTTP/1.1',
1209             'HOST: 239.255.255.250:1900',
1210             'MAN: "ssdp:discover"',
1211             'MX: 1',
1212             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1213             '', ''])
1214     sock.sendto(msg, ("239.255.255.250", 1900))
1215
1216     try:
1217         r = sock.recv(1000)
1218         pass
1219     except socket.timeout:
1220         raise Exception("No SSDP response")
1221
1222 def test_ap_wps_ssdp_burst(dev, apdev):
1223     """WPS AP and SSDP burst"""
1224     ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1225     add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1226
1227     msg = '\r\n'.join([
1228             'M-SEARCH * HTTP/1.1',
1229             'HOST: 239.255.255.250:1900',
1230             'MAN: "ssdp:discover"',
1231             'MX: 1',
1232             'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1233             '', ''])
1234     socket.setdefaulttimeout(1)
1235     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1236     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1237     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1238     sock.bind(("127.0.0.1", 0))
1239     for i in range(0, 25):
1240         sock.sendto(msg, ("239.255.255.250", 1900))
1241     resp = 0
1242     while True:
1243         try:
1244             r = sock.recv(1000)
1245             if not r.startswith("HTTP/1.1 200 OK\r\n"):
1246                 raise Exception("Unexpected message: " + r)
1247             resp += 1
1248         except socket.timeout:
1249             break
1250     if resp < 20:
1251         raise Exception("Too few SSDP responses")
1252
1253     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1254     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1255     sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1256     sock.bind(("127.0.0.1", 0))
1257     for i in range(0, 25):
1258         sock.sendto(msg, ("239.255.255.250", 1900))
1259     while True:
1260         try:
1261             r = sock.recv(1000)
1262             if ap_uuid in r:
1263                 break
1264         except socket.timeout:
1265             raise Exception("No SSDP response")