]> git.ipfire.org Git - thirdparty/hostap.git/blame - tests/hwsim/test_ap_wps.py
tests: Verify network information in SCAN_RESULTS
[thirdparty/hostap.git] / tests / hwsim / test_ap_wps.py
CommitLineData
302b7a1b 1# WPS tests
8674c022 2# Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
302b7a1b
JM
3#
4# This software may be distributed under the terms of the BSD license.
5# See README for more details.
6
2035b170 7import os
302b7a1b
JM
8import time
9import subprocess
10import logging
c9aa4308 11logger = logging.getLogger()
1013a576 12import re
44ff0400 13import socket
47c549fd
JM
14import httplib
15import urlparse
16import urllib
17import xml.etree.ElementTree as ET
18import StringIO
302b7a1b
JM
19
20import hwsim_utils
21import hostapd
22
ae3ad328 23def test_ap_wps_init(dev, apdev):
302b7a1b
JM
24 """Initial AP configuration with first WPS Enrollee"""
25 ssid = "test-wps"
ae3ad328 26 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b 27 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
ae3ad328 28 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
29 logger.info("WPS provisioning step")
30 hapd.request("WPS_PBC")
d671a420
JM
31 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
32 raise Exception("PBC status not shown correctly")
b9018833
JM
33
34 id = dev[0].add_network()
35 dev[0].set_network_quoted(id, "ssid", "home")
36 dev[0].set_network_quoted(id, "psk", "12345678")
37 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
38
39 id = dev[0].add_network()
40 dev[0].set_network_quoted(id, "ssid", "home2")
41 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
42 dev[0].set_network(id, "key_mgmt", "NONE")
43 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
44
302b7a1b 45 dev[0].request("WPS_PBC")
853b49a0 46 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
302b7a1b
JM
47 if ev is None:
48 raise Exception("Association with the AP timed out")
49 status = dev[0].get_status()
ae3ad328 50 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
51 raise Exception("Not fully connected")
52 if status['ssid'] != ssid:
53 raise Exception("Unexpected SSID")
54 if status['pairwise_cipher'] != 'CCMP':
55 raise Exception("Unexpected encryption configuration")
56 if status['key_mgmt'] != 'WPA2-PSK':
57 raise Exception("Unexpected key_mgmt")
58
d671a420
JM
59 status = hapd.request("WPS_GET_STATUS")
60 if "PBC Status: Disabled" not in status:
61 raise Exception("PBC status not shown correctly")
62 if "Last WPS result: Success" not in status:
63 raise Exception("Last WPS result not shown correctly")
64 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
65 raise Exception("Peer address not shown correctly")
75b25ece
JM
66 conf = hapd.request("GET_CONFIG")
67 if "wps_state=configured" not in conf:
68 raise Exception("AP not in WPS configured state")
69 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
70 raise Exception("Unexpected rsn_pairwise_cipher")
71 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
72 raise Exception("Unexpected wpa_pairwise_cipher")
73 if "group_cipher=TKIP" not in conf:
74 raise Exception("Unexpected group_cipher")
d671a420 75
b9018833
JM
76 if len(dev[0].list_networks()) != 3:
77 raise Exception("Unexpected number of network blocks")
78
18030dc0
JM
79def test_ap_wps_init_2ap_pbc(dev, apdev):
80 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
81 ssid = "test-wps"
82 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
83 hostapd.add_ap(apdev[0]['ifname'], params)
84 hostapd.add_ap(apdev[1]['ifname'], params)
85 hapd = hostapd.Hostapd(apdev[0]['ifname'])
86 logger.info("WPS provisioning step")
87 hapd.request("WPS_PBC")
18030dc0
JM
88 dev[0].scan(freq="2412")
89 bss = dev[0].get_bss(apdev[0]['bssid'])
90 if "[WPS-PBC]" not in bss['flags']:
91 raise Exception("WPS-PBC flag missing from AP1")
92 bss = dev[0].get_bss(apdev[1]['bssid'])
93 if "[WPS-PBC]" not in bss['flags']:
94 raise Exception("WPS-PBC flag missing from AP2")
95 dev[0].dump_monitor()
f19d87f1 96 dev[0].request("SET wps_cred_processing 2")
18030dc0 97 dev[0].request("WPS_PBC")
f19d87f1
JM
98 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
99 dev[0].request("SET wps_cred_processing 0")
100 if ev is None:
101 raise Exception("WPS cred event not seen")
102 if "100e" not in ev:
103 raise Exception("WPS attributes not included in the cred event")
18030dc0
JM
104 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
105 if ev is None:
106 raise Exception("Association with the AP timed out")
107
18030dc0
JM
108 dev[1].scan(freq="2412")
109 bss = dev[1].get_bss(apdev[0]['bssid'])
110 if "[WPS-PBC]" in bss['flags']:
111 raise Exception("WPS-PBC flag not cleared from AP1")
112 bss = dev[1].get_bss(apdev[1]['bssid'])
113 if "[WPS-PBC]" in bss['flags']:
114 raise Exception("WPS-PBC flag bit ckeared from AP2")
115
116def test_ap_wps_init_2ap_pin(dev, apdev):
117 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
118 ssid = "test-wps"
119 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
120 hostapd.add_ap(apdev[0]['ifname'], params)
121 hostapd.add_ap(apdev[1]['ifname'], params)
122 hapd = hostapd.Hostapd(apdev[0]['ifname'])
123 logger.info("WPS provisioning step")
124 pin = dev[0].wps_read_pin()
125 hapd.request("WPS_PIN any " + pin)
18030dc0
JM
126 dev[0].scan(freq="2412")
127 bss = dev[0].get_bss(apdev[0]['bssid'])
128 if "[WPS-AUTH]" not in bss['flags']:
129 raise Exception("WPS-AUTH flag missing from AP1")
130 bss = dev[0].get_bss(apdev[1]['bssid'])
131 if "[WPS-AUTH]" not in bss['flags']:
132 raise Exception("WPS-AUTH flag missing from AP2")
133 dev[0].dump_monitor()
134 dev[0].request("WPS_PIN any " + pin)
135 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
136 if ev is None:
137 raise Exception("Association with the AP timed out")
138
18030dc0
JM
139 dev[1].scan(freq="2412")
140 bss = dev[1].get_bss(apdev[0]['bssid'])
141 if "[WPS-AUTH]" in bss['flags']:
142 raise Exception("WPS-AUTH flag not cleared from AP1")
143 bss = dev[1].get_bss(apdev[1]['bssid'])
144 if "[WPS-AUTH]" in bss['flags']:
145 raise Exception("WPS-AUTH flag bit ckeared from AP2")
146
35831e94
JM
147def test_ap_wps_init_through_wps_config(dev, apdev):
148 """Initial AP configuration using wps_config command"""
149 ssid = "test-wps-init-config"
150 hostapd.add_ap(apdev[0]['ifname'],
151 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
152 hapd = hostapd.Hostapd(apdev[0]['ifname'])
153 if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
154 raise Exception("WPS_CONFIG command failed")
180cd73d
JM
155 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
156 if ev is None:
157 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
158 # It takes some time for the AP to update Beacon and Probe Response frames,
159 # so wait here before requesting the scan to be started to avoid adding
160 # extra five second wait to the test due to fetching obsolete scan results.
161 hapd.ping()
162 time.sleep(0.2)
35831e94
JM
163 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
164 pairwise="CCMP", group="CCMP")
165
ae3ad328 166def test_ap_wps_conf(dev, apdev):
302b7a1b
JM
167 """WPS PBC provisioning with configured AP"""
168 ssid = "test-wps-conf"
ae3ad328 169 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
170 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
171 "wpa_passphrase": "12345678", "wpa": "2",
172 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 173 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
174 logger.info("WPS provisioning step")
175 hapd.request("WPS_PBC")
176 dev[0].dump_monitor()
177 dev[0].request("WPS_PBC")
7e3f110b 178 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
302b7a1b
JM
179 if ev is None:
180 raise Exception("Association with the AP timed out")
181 status = dev[0].get_status()
ae3ad328 182 if status['wpa_state'] != 'COMPLETED':
302b7a1b 183 raise Exception("Not fully connected")
ae3ad328
JM
184 if status['bssid'] != apdev[0]['bssid']:
185 raise Exception("Unexpected BSSID")
302b7a1b
JM
186 if status['ssid'] != ssid:
187 raise Exception("Unexpected SSID")
188 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
189 raise Exception("Unexpected encryption configuration")
190 if status['key_mgmt'] != 'WPA2-PSK':
191 raise Exception("Unexpected key_mgmt")
192
097cd9cd
JM
193 sta = hapd.get_sta(dev[0].p2p_interface_addr())
194 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
195 raise Exception("Device name not available in STA command")
196
daad14cc
JM
197def test_ap_wps_conf_5ghz(dev, apdev):
198 """WPS PBC provisioning with configured AP on 5 GHz band"""
199 try:
200 ssid = "test-wps-conf"
201 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
202 "wpa_passphrase": "12345678", "wpa": "2",
203 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
204 "country_code": "FI", "hw_mode": "a", "channel": "36" }
205 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
206 logger.info("WPS provisioning step")
207 hapd.request("WPS_PBC")
208 dev[0].request("WPS_PBC")
209 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
210 if ev is None:
211 raise Exception("Association with the AP timed out")
212
213 sta = hapd.get_sta(dev[0].p2p_interface_addr())
214 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
215 raise Exception("Device name not available in STA command")
216 finally:
217 subprocess.call(['sudo', 'iw', 'reg', 'set', '00'])
218
219def test_ap_wps_conf_chan14(dev, apdev):
220 """WPS PBC provisioning with configured AP on channel 14"""
221 try:
222 ssid = "test-wps-conf"
223 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
224 "wpa_passphrase": "12345678", "wpa": "2",
225 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
226 "country_code": "JP", "hw_mode": "b", "channel": "14" }
227 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
228 logger.info("WPS provisioning step")
229 hapd.request("WPS_PBC")
230 dev[0].request("WPS_PBC")
231 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
232 if ev is None:
233 raise Exception("Association with the AP timed out")
234
235 sta = hapd.get_sta(dev[0].p2p_interface_addr())
236 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
237 raise Exception("Device name not available in STA command")
238 finally:
239 subprocess.call(['sudo', 'iw', 'reg', 'set', '00'])
240
04e62788
JM
241def test_ap_wps_twice(dev, apdev):
242 """WPS provisioning with twice to change passphrase"""
243 ssid = "test-wps-twice"
244 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
245 "wpa_passphrase": "12345678", "wpa": "2",
246 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
247 hostapd.add_ap(apdev[0]['ifname'], params)
248 hapd = hostapd.Hostapd(apdev[0]['ifname'])
249 logger.info("WPS provisioning step")
250 hapd.request("WPS_PBC")
04e62788
JM
251 dev[0].dump_monitor()
252 dev[0].request("WPS_PBC")
253 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
254 if ev is None:
255 raise Exception("Association with the AP timed out")
256 dev[0].request("DISCONNECT")
257
258 logger.info("Restart AP with different passphrase and re-run WPS")
259 hapd_global = hostapd.HostapdGlobal()
260 hapd_global.remove(apdev[0]['ifname'])
261 params['wpa_passphrase'] = 'another passphrase'
262 hostapd.add_ap(apdev[0]['ifname'], params)
263 hapd = hostapd.Hostapd(apdev[0]['ifname'])
264 logger.info("WPS provisioning step")
265 hapd.request("WPS_PBC")
266 dev[0].dump_monitor()
2f35bc64 267 dev[0].request("WPS_PBC any")
04e62788
JM
268 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
269 if ev is None:
270 raise Exception("Association with the AP timed out")
271 networks = dev[0].list_networks()
272 if len(networks) > 1:
273 raise Exception("Unexpected duplicated network block present")
274
d658205a
JM
275def test_ap_wps_incorrect_pin(dev, apdev):
276 """WPS PIN provisioning with incorrect PIN"""
277 ssid = "test-wps-incorrect-pin"
278 hostapd.add_ap(apdev[0]['ifname'],
279 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
280 "wpa_passphrase": "12345678", "wpa": "2",
281 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
282 hapd = hostapd.Hostapd(apdev[0]['ifname'])
283
284 logger.info("WPS provisioning attempt 1")
285 hapd.request("WPS_PIN any 12345670")
d658205a
JM
286 dev[0].dump_monitor()
287 dev[0].request("WPS_PIN any 55554444")
288 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
289 if ev is None:
290 raise Exception("WPS operation timed out")
291 if "config_error=18" not in ev:
292 raise Exception("Incorrect config_error reported")
293 if "msg=8" not in ev:
294 raise Exception("PIN error detected on incorrect message")
295 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
296 if ev is None:
297 raise Exception("Timeout on disconnection event")
298 dev[0].request("WPS_CANCEL")
299 # if a scan was in progress, wait for it to complete before trying WPS again
300 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
301
d671a420
JM
302 status = hapd.request("WPS_GET_STATUS")
303 if "Last WPS result: Failed" not in status:
304 raise Exception("WPS failure result not shown correctly")
305
d658205a
JM
306 logger.info("WPS provisioning attempt 2")
307 hapd.request("WPS_PIN any 12345670")
308 dev[0].dump_monitor()
309 dev[0].request("WPS_PIN any 12344444")
310 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
311 if ev is None:
312 raise Exception("WPS operation timed out")
313 if "config_error=18" not in ev:
314 raise Exception("Incorrect config_error reported")
315 if "msg=10" not in ev:
316 raise Exception("PIN error detected on incorrect message")
317 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
318 if ev is None:
319 raise Exception("Timeout on disconnection event")
320
ae3ad328 321def test_ap_wps_conf_pin(dev, apdev):
302b7a1b
JM
322 """WPS PIN provisioning with configured AP"""
323 ssid = "test-wps-conf-pin"
ae3ad328 324 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
325 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
326 "wpa_passphrase": "12345678", "wpa": "2",
327 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 328 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
329 logger.info("WPS provisioning step")
330 pin = dev[0].wps_read_pin()
331 hapd.request("WPS_PIN any " + pin)
332 dev[0].dump_monitor()
333 dev[0].request("WPS_PIN any " + pin)
7e3f110b 334 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
302b7a1b
JM
335 if ev is None:
336 raise Exception("Association with the AP timed out")
337 status = dev[0].get_status()
ae3ad328 338 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
339 raise Exception("Not fully connected")
340 if status['ssid'] != ssid:
341 raise Exception("Unexpected SSID")
342 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
343 raise Exception("Unexpected encryption configuration")
344 if status['key_mgmt'] != 'WPA2-PSK':
345 raise Exception("Unexpected key_mgmt")
346
362ba6de
JM
347 dev[1].scan(freq="2412")
348 bss = dev[1].get_bss(apdev[0]['bssid'])
349 if "[WPS-AUTH]" in bss['flags']:
350 raise Exception("WPS-AUTH flag not cleared")
a60a6d6b 351 logger.info("Try to connect from another station using the same PIN")
6e12eaa4 352 pin = dev[1].request("WPS_PIN any")
a60a6d6b
JM
353 ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
354 if ev is None:
355 raise Exception("Operation timed out")
356 if "WPS-M2D" not in ev:
357 raise Exception("Unexpected WPS operation started")
6e12eaa4
JM
358 hapd.request("WPS_PIN any " + pin)
359 ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
360 if ev is None:
361 raise Exception("Association with the AP timed out")
362ba6de 362
e9129860
JM
363def test_ap_wps_conf_pin_2sta(dev, apdev):
364 """Two stations trying to use WPS PIN at the same time"""
365 ssid = "test-wps-conf-pin2"
366 hostapd.add_ap(apdev[0]['ifname'],
367 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
368 "wpa_passphrase": "12345678", "wpa": "2",
369 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
370 hapd = hostapd.Hostapd(apdev[0]['ifname'])
371 logger.info("WPS provisioning step")
372 pin = "12345670"
373 pin2 = "55554444"
374 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
375 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
e9129860 376 dev[0].dump_monitor()
e9129860
JM
377 dev[1].dump_monitor()
378 dev[0].request("WPS_PIN any " + pin)
379 dev[1].request("WPS_PIN any " + pin)
380 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
381 if ev is None:
382 raise Exception("Association with the AP timed out")
383 ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
384 if ev is None:
385 raise Exception("Association with the AP timed out")
0489e880
JM
386
387def test_ap_wps_conf_pin_timeout(dev, apdev):
388 """WPS PIN provisioning with configured AP timing out PIN"""
389 ssid = "test-wps-conf-pin"
390 hostapd.add_ap(apdev[0]['ifname'],
391 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
392 "wpa_passphrase": "12345678", "wpa": "2",
393 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
394 hapd = hostapd.Hostapd(apdev[0]['ifname'])
395 addr = dev[0].p2p_interface_addr()
396 pin = dev[0].wps_read_pin()
397 if "FAIL" not in hapd.request("WPS_PIN "):
398 raise Exception("Unexpected success on invalid WPS_PIN")
399 hapd.request("WPS_PIN any " + pin + " 1")
400 time.sleep(1.1)
401 dev[0].request("WPS_PIN any " + pin)
402 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
403 if ev is None:
404 raise Exception("WPS-PIN-NEEDED event timed out")
405 ev = dev[0].wait_event(["WPS-M2D"])
406 if ev is None:
407 raise Exception("M2D not reported")
408 dev[0].request("WPS_CANCEL")
409
410 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
411 dev[0].request("WPS_PIN any " + pin)
412 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
413 if ev is None:
414 raise Exception("Association with the AP timed out")
e9129860 415
ae3ad328 416def test_ap_wps_reg_connect(dev, apdev):
302b7a1b 417 """WPS registrar using AP PIN to connect"""
803edd1c 418 ssid = "test-wps-reg-ap-pin"
302b7a1b 419 appin = "12345670"
ae3ad328 420 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
421 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
422 "wpa_passphrase": "12345678", "wpa": "2",
423 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
424 "ap_pin": appin})
425 logger.info("WPS provisioning step")
302b7a1b 426 dev[0].dump_monitor()
6edaee9c 427 dev[0].wps_reg(apdev[0]['bssid'], appin)
302b7a1b 428 status = dev[0].get_status()
ae3ad328 429 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
430 raise Exception("Not fully connected")
431 if status['ssid'] != ssid:
432 raise Exception("Unexpected SSID")
433 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
434 raise Exception("Unexpected encryption configuration")
435 if status['key_mgmt'] != 'WPA2-PSK':
436 raise Exception("Unexpected key_mgmt")
437
9488858f
JM
438def check_wps_reg_failure(dev, ap, appin):
439 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
440 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
441 if ev is None:
442 raise Exception("WPS operation timed out")
443 if "WPS-SUCCESS" in ev:
444 raise Exception("WPS operation succeeded unexpectedly")
445 if "config_error=15" not in ev:
446 raise Exception("WPS setup locked state was not reported correctly")
447
e4357b19
JM
448def test_ap_wps_random_ap_pin(dev, apdev):
449 """WPS registrar using random AP PIN"""
450 ssid = "test-wps-reg-random-ap-pin"
451 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
452 hostapd.add_ap(apdev[0]['ifname'],
453 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
454 "wpa_passphrase": "12345678", "wpa": "2",
455 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
456 "device_name": "Wireless AP", "manufacturer": "Company",
457 "model_name": "WAP", "model_number": "123",
458 "serial_number": "12345", "device_type": "6-0050F204-1",
459 "os_version": "01020300",
460 "config_methods": "label push_button",
461 "uuid": ap_uuid, "upnp_iface": "lo" })
462 hapd = hostapd.Hostapd(apdev[0]['ifname'])
463 appin = hapd.request("WPS_AP_PIN random")
464 if "FAIL" in appin:
465 raise Exception("Could not generate random AP PIN")
466 if appin not in hapd.request("WPS_AP_PIN get"):
467 raise Exception("Could not fetch current AP PIN")
468 logger.info("WPS provisioning step")
e4357b19
JM
469 dev[0].wps_reg(apdev[0]['bssid'], appin)
470
471 hapd.request("WPS_AP_PIN disable")
472 logger.info("WPS provisioning step with AP PIN disabled")
9488858f
JM
473 check_wps_reg_failure(dev[1], apdev[0], appin)
474
475 logger.info("WPS provisioning step with AP PIN reset")
476 appin = "12345670"
477 hapd.request("WPS_AP_PIN set " + appin)
478 dev[1].wps_reg(apdev[0]['bssid'], appin)
479 dev[0].request("REMOVE_NETWORK all")
480 dev[1].request("REMOVE_NETWORK all")
481 dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
482 dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
483
484 logger.info("WPS provisioning step after AP PIN timeout")
485 hapd.request("WPS_AP_PIN disable")
486 appin = hapd.request("WPS_AP_PIN random 1")
487 time.sleep(1.1)
488 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
489 raise Exception("AP PIN unexpectedly still enabled")
490 check_wps_reg_failure(dev[0], apdev[0], appin)
491
492 logger.info("WPS provisioning step after AP PIN timeout(2)")
493 hapd.request("WPS_AP_PIN disable")
494 appin = "12345670"
495 hapd.request("WPS_AP_PIN set " + appin + " 1")
496 time.sleep(1.1)
497 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
498 raise Exception("AP PIN unexpectedly still enabled")
499 check_wps_reg_failure(dev[1], apdev[0], appin)
e4357b19 500
ae3ad328 501def test_ap_wps_reg_config(dev, apdev):
4b727c5c 502 """WPS registrar configuring an AP using AP PIN"""
302b7a1b
JM
503 ssid = "test-wps-init-ap-pin"
504 appin = "12345670"
ae3ad328 505 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
506 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
507 "ap_pin": appin})
508 logger.info("WPS configuration step")
302b7a1b
JM
509 dev[0].dump_monitor()
510 new_ssid = "wps-new-ssid"
511 new_passphrase = "1234567890"
6edaee9c
JM
512 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
513 new_passphrase)
302b7a1b 514 status = dev[0].get_status()
ae3ad328 515 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
516 raise Exception("Not fully connected")
517 if status['ssid'] != new_ssid:
518 raise Exception("Unexpected SSID")
519 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
520 raise Exception("Unexpected encryption configuration")
521 if status['key_mgmt'] != 'WPA2-PSK':
522 raise Exception("Unexpected key_mgmt")
523
375afd7c
JM
524 logger.info("Re-configure back to open")
525 dev[0].request("REMOVE_NETWORK all")
526 dev[0].request("BSS_FLUSH 0")
527 dev[0].request("SCAN freq=2412 only_new=1")
528 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
529 if ev is None:
530 raise Exception("Scan timed out")
531 dev[0].dump_monitor()
532 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
533 status = dev[0].get_status()
534 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
535 raise Exception("Not fully connected")
536 if status['ssid'] != "wps-open":
537 raise Exception("Unexpected SSID")
538 if status['key_mgmt'] != 'NONE':
539 raise Exception("Unexpected key_mgmt")
540
4b727c5c
JM
541def test_ap_wps_reg_config_ext_processing(dev, apdev):
542 """WPS registrar configuring an AP with external config processing"""
543 ssid = "test-wps-init-ap-pin"
544 appin = "12345670"
545 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
546 "wps_cred_processing": "1", "ap_pin": appin}
547 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
548 new_ssid = "wps-new-ssid"
549 new_passphrase = "1234567890"
550 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
551 new_passphrase, no_wait=True)
552 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
553 if ev is None:
554 raise Exception("WPS registrar operation timed out")
555 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
556 if ev is None:
557 raise Exception("WPS configuration timed out")
558 if "1026" not in ev:
559 raise Exception("AP Settings missing from event")
560 hapd.request("SET wps_cred_processing 0")
561 if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
562 raise Exception("WPS_CONFIG command failed")
563 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
564 if ev is None:
565 raise Exception("Association with the AP timed out")
566
eeefe187
JM
567def test_ap_wps_reg_config_tkip(dev, apdev):
568 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
569 ssid = "test-wps-init-ap"
570 appin = "12345670"
571 hostapd.add_ap(apdev[0]['ifname'],
572 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
573 "ap_pin": appin})
574 logger.info("WPS configuration step")
eeefe187
JM
575 dev[0].request("SET wps_version_number 0x10")
576 dev[0].dump_monitor()
577 new_ssid = "wps-new-ssid-with-tkip"
578 new_passphrase = "1234567890"
579 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
580 new_passphrase)
581 logger.info("Re-connect to verify WPA2 mixed mode")
582 dev[0].request("DISCONNECT")
583 id = 0
584 dev[0].set_network(id, "pairwise", "CCMP")
585 dev[0].set_network(id, "proto", "RSN")
586 dev[0].connect_network(id)
587 status = dev[0].get_status()
588 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
589 raise Exception("Not fully connected")
590 if status['ssid'] != new_ssid:
591 raise Exception("Unexpected SSID")
592 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
593 raise Exception("Unexpected encryption configuration")
594 if status['key_mgmt'] != 'WPA2-PSK':
595 raise Exception("Unexpected key_mgmt")
596
6645ff50
JM
597def test_ap_wps_setup_locked(dev, apdev):
598 """WPS registrar locking up AP setup on AP PIN failures"""
599 ssid = "test-wps-incorrect-ap-pin"
600 appin = "12345670"
601 hostapd.add_ap(apdev[0]['ifname'],
602 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
603 "wpa_passphrase": "12345678", "wpa": "2",
604 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
605 "ap_pin": appin})
6645ff50
JM
606 new_ssid = "wps-new-ssid-test"
607 new_passphrase = "1234567890"
608
609 ap_setup_locked=False
610 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
611 dev[0].dump_monitor()
612 logger.info("Try incorrect AP PIN - attempt " + pin)
613 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
614 "CCMP", new_passphrase, no_wait=True)
615 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
616 if ev is None:
617 raise Exception("Timeout on receiving WPS operation failure event")
618 if "CTRL-EVENT-CONNECTED" in ev:
619 raise Exception("Unexpected connection")
620 if "config_error=15" in ev:
621 logger.info("AP Setup Locked")
622 ap_setup_locked=True
623 elif "config_error=18" not in ev:
624 raise Exception("config_error=18 not reported")
625 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
626 if ev is None:
627 raise Exception("Timeout on disconnection event")
628 time.sleep(0.1)
629 if not ap_setup_locked:
630 raise Exception("AP setup was not locked")
631
d671a420
JM
632 hapd = hostapd.Hostapd(apdev[0]['ifname'])
633 status = hapd.request("WPS_GET_STATUS")
634 if "Last WPS result: Failed" not in status:
635 raise Exception("WPS failure result not shown correctly")
636 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
637 raise Exception("Peer address not shown correctly")
638
6645ff50
JM
639 time.sleep(0.5)
640 dev[0].dump_monitor()
641 logger.info("WPS provisioning step")
642 pin = dev[0].wps_read_pin()
643 hapd = hostapd.Hostapd(apdev[0]['ifname'])
644 hapd.request("WPS_PIN any " + pin)
645 dev[0].request("WPS_PIN any " + pin)
646 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
647 if ev is None:
648 raise Exception("WPS success was not reported")
649 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
650 if ev is None:
651 raise Exception("Association with the AP timed out")
652
c1cec68b
JM
653 appin = hapd.request("WPS_AP_PIN random")
654 if "FAIL" in appin:
655 raise Exception("Could not generate random AP PIN")
656 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
657 if ev is None:
658 raise Exception("Failed to unlock AP PIN")
659
33c9b8d8
JM
660def test_ap_wps_setup_locked_timeout(dev, apdev):
661 """WPS re-enabling AP PIN after timeout"""
662 ssid = "test-wps-incorrect-ap-pin"
663 appin = "12345670"
664 hostapd.add_ap(apdev[0]['ifname'],
665 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
666 "wpa_passphrase": "12345678", "wpa": "2",
667 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
668 "ap_pin": appin})
669 new_ssid = "wps-new-ssid-test"
670 new_passphrase = "1234567890"
671
672 ap_setup_locked=False
673 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
674 dev[0].dump_monitor()
675 logger.info("Try incorrect AP PIN - attempt " + pin)
676 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
677 "CCMP", new_passphrase, no_wait=True)
678 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
679 if ev is None:
680 raise Exception("Timeout on receiving WPS operation failure event")
681 if "CTRL-EVENT-CONNECTED" in ev:
682 raise Exception("Unexpected connection")
683 if "config_error=15" in ev:
684 logger.info("AP Setup Locked")
685 ap_setup_locked=True
686 break
687 elif "config_error=18" not in ev:
688 raise Exception("config_error=18 not reported")
689 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"])
690 if ev is None:
691 raise Exception("Timeout on disconnection event")
692 time.sleep(0.1)
693 if not ap_setup_locked:
694 raise Exception("AP setup was not locked")
695 hapd = hostapd.Hostapd(apdev[0]['ifname'])
696 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
697 if ev is None:
698 raise Exception("AP PIN did not get unlocked on 60 second timeout")
699
ae3ad328 700def test_ap_wps_pbc_overlap_2ap(dev, apdev):
302b7a1b 701 """WPS PBC session overlap with two active APs"""
ae3ad328 702 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
703 { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
704 "wpa_passphrase": "12345678", "wpa": "2",
705 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
706 "wps_independent": "1"})
ae3ad328 707 hostapd.add_ap(apdev[1]['ifname'],
302b7a1b
JM
708 { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
709 "wpa_passphrase": "123456789", "wpa": "2",
710 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
711 "wps_independent": "1"})
ae3ad328 712 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b 713 hapd.request("WPS_PBC")
ae3ad328 714 hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
302b7a1b
JM
715 hapd2.request("WPS_PBC")
716 logger.info("WPS provisioning step")
717 dev[0].dump_monitor()
718 dev[0].request("WPS_PBC")
719 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
720 if ev is None:
721 raise Exception("PBC session overlap not detected")
722
ae3ad328 723def test_ap_wps_pbc_overlap_2sta(dev, apdev):
302b7a1b
JM
724 """WPS PBC session overlap with two active STAs"""
725 ssid = "test-wps-pbc-overlap"
ae3ad328 726 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
727 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
728 "wpa_passphrase": "12345678", "wpa": "2",
729 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 730 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
731 logger.info("WPS provisioning step")
732 hapd.request("WPS_PBC")
302b7a1b
JM
733 dev[0].dump_monitor()
734 dev[1].dump_monitor()
735 dev[0].request("WPS_PBC")
736 dev[1].request("WPS_PBC")
737 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
738 if ev is None:
739 raise Exception("PBC session overlap not detected (dev0)")
740 if "config_error=12" not in ev:
741 raise Exception("PBC session overlap not correctly reported (dev0)")
742 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
743 if ev is None:
744 raise Exception("PBC session overlap not detected (dev1)")
745 if "config_error=12" not in ev:
746 raise Exception("PBC session overlap not correctly reported (dev1)")
11e7eeba
JM
747 hapd.request("WPS_CANCEL")
748 ret = hapd.request("WPS_PBC")
749 if "FAIL" not in ret:
750 raise Exception("PBC mode allowed to be started while PBC overlap still active")
6edaee9c 751
71afe834
JM
752def test_ap_wps_cancel(dev, apdev):
753 """WPS AP cancelling enabled config method"""
754 ssid = "test-wps-ap-cancel"
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 bssid = apdev[0]['bssid']
760 hapd = hostapd.Hostapd(apdev[0]['ifname'])
761
762 logger.info("Verify PBC enable/cancel")
763 hapd.request("WPS_PBC")
71afe834
JM
764 dev[0].scan(freq="2412")
765 bss = dev[0].get_bss(apdev[0]['bssid'])
766 if "[WPS-PBC]" not in bss['flags']:
767 raise Exception("WPS-PBC flag missing")
768 if "FAIL" in hapd.request("WPS_CANCEL"):
769 raise Exception("WPS_CANCEL failed")
770 dev[0].scan(freq="2412")
771 bss = dev[0].get_bss(apdev[0]['bssid'])
772 if "[WPS-PBC]" in bss['flags']:
773 raise Exception("WPS-PBC flag not cleared")
774
775 logger.info("Verify PIN enable/cancel")
776 hapd.request("WPS_PIN any 12345670")
777 dev[0].scan(freq="2412")
778 bss = dev[0].get_bss(apdev[0]['bssid'])
779 if "[WPS-AUTH]" not in bss['flags']:
780 raise Exception("WPS-AUTH flag missing")
781 if "FAIL" in hapd.request("WPS_CANCEL"):
782 raise Exception("WPS_CANCEL failed")
783 dev[0].scan(freq="2412")
784 bss = dev[0].get_bss(apdev[0]['bssid'])
785 if "[WPS-AUTH]" in bss['flags']:
786 raise Exception("WPS-AUTH flag not cleared")
787
6edaee9c
JM
788def test_ap_wps_er_add_enrollee(dev, apdev):
789 """WPS ER configuring AP and adding a new enrollee using PIN"""
790 ssid = "wps-er-add-enrollee"
791 ap_pin = "12345670"
792 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
793 hostapd.add_ap(apdev[0]['ifname'],
794 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
795 "device_name": "Wireless AP", "manufacturer": "Company",
796 "model_name": "WAP", "model_number": "123",
797 "serial_number": "12345", "device_type": "6-0050F204-1",
798 "os_version": "01020300",
799 "config_methods": "label push_button",
800 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
801 logger.info("WPS configuration step")
802 new_passphrase = "1234567890"
803 dev[0].dump_monitor()
6edaee9c
JM
804 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
805 new_passphrase)
806 status = dev[0].get_status()
807 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
808 raise Exception("Not fully connected")
809 if status['ssid'] != ssid:
810 raise Exception("Unexpected SSID")
811 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
812 raise Exception("Unexpected encryption configuration")
813 if status['key_mgmt'] != 'WPA2-PSK':
814 raise Exception("Unexpected key_mgmt")
815
816 logger.info("Start ER")
817 dev[0].request("WPS_ER_START ifname=lo")
818 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
819 if ev is None:
820 raise Exception("AP discovery timed out")
821 if ap_uuid not in ev:
822 raise Exception("Expected AP UUID not found")
823
824 logger.info("Learn AP configuration through UPnP")
825 dev[0].dump_monitor()
826 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
827 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
828 if ev is None:
829 raise Exception("AP learn timed out")
830 if ap_uuid not in ev:
831 raise Exception("Expected AP UUID not in settings")
832 if "ssid=" + ssid not in ev:
833 raise Exception("Expected SSID not in settings")
834 if "key=" + new_passphrase not in ev:
835 raise Exception("Expected passphrase not in settings")
836
837 logger.info("Add Enrollee using ER")
838 pin = dev[1].wps_read_pin()
839 dev[0].dump_monitor()
840 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
6edaee9c
JM
841 dev[1].dump_monitor()
842 dev[1].request("WPS_PIN any " + pin)
846be889 843 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
6edaee9c
JM
844 if ev is None:
845 raise Exception("Enrollee did not report success")
846 ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
847 if ev is None:
848 raise Exception("Association with the AP timed out")
849 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
850 if ev is None:
851 raise Exception("WPS ER did not report success")
852 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
853
11c26f1b
JM
854 logger.info("Add a specific Enrollee using ER")
855 pin = dev[2].wps_read_pin()
856 addr2 = dev[2].p2p_interface_addr()
857 dev[0].dump_monitor()
858 dev[2].dump_monitor()
859 dev[2].request("WPS_PIN any " + pin)
860 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
861 if ev is None:
862 raise Exception("Enrollee not seen")
863 if addr2 not in ev:
864 raise Exception("Unexpected Enrollee MAC address")
865 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
866 ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
867 if ev is None:
868 raise Exception("Association with the AP timed out")
869 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
870 if ev is None:
871 raise Exception("WPS ER did not report success")
872
38ae43de
JM
873 logger.info("Verify registrar selection behavior")
874 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
875 dev[1].request("DISCONNECT")
876 dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
877 dev[1].scan(freq="2412")
878 bss = dev[1].get_bss(apdev[0]['bssid'])
879 if "[WPS-AUTH]" not in bss['flags']:
880 raise Exception("WPS-AUTH flag missing")
881
882 logger.info("Stop ER")
883 dev[0].dump_monitor()
884 dev[0].request("WPS_ER_STOP")
885 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
886 if ev is None:
887 raise Exception("WPS ER unsubscription timed out")
8697cbc0 888 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
befd671c 889 # a bit before verifying that the scan results have changed.
8697cbc0 890 time.sleep(0.2)
38ae43de 891
befd671c
JM
892 for i in range(0, 10):
893 dev[1].request("BSS_FLUSH 0")
894 dev[1].scan(freq="2412", only_new=True)
895 bss = dev[1].get_bss(apdev[0]['bssid'])
896 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
897 break
898 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
899 time.sleep(0.1)
38ae43de
JM
900 if "[WPS-AUTH]" in bss['flags']:
901 raise Exception("WPS-AUTH flag not removed")
902
6edaee9c
JM
903def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
904 """WPS ER connected to AP and adding a new enrollee using PBC"""
905 ssid = "wps-er-add-enrollee-pbc"
906 ap_pin = "12345670"
907 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
908 hostapd.add_ap(apdev[0]['ifname'],
909 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
910 "wpa_passphrase": "12345678", "wpa": "2",
911 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
912 "device_name": "Wireless AP", "manufacturer": "Company",
913 "model_name": "WAP", "model_number": "123",
914 "serial_number": "12345", "device_type": "6-0050F204-1",
915 "os_version": "01020300",
916 "config_methods": "label push_button",
917 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
918 logger.info("Learn AP configuration")
919 dev[0].dump_monitor()
6edaee9c
JM
920 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
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
925 logger.info("Start ER")
926 dev[0].request("WPS_ER_START ifname=lo")
927 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
928 if ev is None:
929 raise Exception("AP discovery timed out")
930 if ap_uuid not in ev:
931 raise Exception("Expected AP UUID not found")
932
933 logger.info("Use learned network configuration on ER")
934 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
935
936 logger.info("Add Enrollee using ER and PBC")
937 dev[0].dump_monitor()
938 enrollee = dev[1].p2p_interface_addr()
6edaee9c
JM
939 dev[1].dump_monitor()
940 dev[1].request("WPS_PBC")
941
8674c022
JM
942 for i in range(0, 2):
943 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
944 if ev is None:
945 raise Exception("Enrollee discovery timed out")
946 if enrollee in ev:
947 break
948 if i == 1:
949 raise Exception("Expected Enrollee not found")
6edaee9c
JM
950 dev[0].request("WPS_ER_PBC " + enrollee)
951
952 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
953 if ev is None:
954 raise Exception("Enrollee did not report success")
955 ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
956 if ev is None:
957 raise Exception("Association with the AP timed out")
958 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
959 if ev is None:
960 raise Exception("WPS ER did not report success")
961 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
bff3ac5b 962
800bcf4e
JM
963 # verify BSSID selection of the AP instead of UUID
964 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
965 raise Exception("Could not select AP based on BSSID")
966
1f020f5e
JM
967def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
968 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
969 ssid = "wps-er-add-enrollee-pbc"
970 ap_pin = "12345670"
971 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
972 hostapd.add_ap(apdev[0]['ifname'],
973 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
974 "wpa_passphrase": "12345678", "wpa": "2",
975 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
976 "device_name": "Wireless AP", "manufacturer": "Company",
977 "model_name": "WAP", "model_number": "123",
978 "serial_number": "12345", "device_type": "6-0050F204-1",
979 "os_version": "01020300",
980 "config_methods": "label push_button",
981 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
982 logger.info("Learn AP configuration")
983 dev[0].request("SET wps_version_number 0x10")
984 dev[0].dump_monitor()
985 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
986 status = dev[0].get_status()
987 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
988 raise Exception("Not fully connected")
989
990 logger.info("Start ER")
991 dev[0].request("WPS_ER_START ifname=lo")
992 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
993 if ev is None:
994 raise Exception("AP discovery timed out")
995 if ap_uuid not in ev:
996 raise Exception("Expected AP UUID not found")
997
998 logger.info("Use learned network configuration on ER")
999 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1000
1001 logger.info("Add Enrollee using ER and PIN")
1002 enrollee = dev[1].p2p_interface_addr()
1003 pin = dev[1].wps_read_pin()
1004 dev[0].dump_monitor()
1005 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1006 dev[1].dump_monitor()
1007 dev[1].request("WPS_PIN any " + pin)
1008 ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
1009 if ev is None:
1010 raise Exception("Association with the AP timed out")
1011 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1012 if ev is None:
1013 raise Exception("WPS ER did not report success")
1014
be923570
JM
1015def test_ap_wps_er_config_ap(dev, apdev):
1016 """WPS ER configuring AP over UPnP"""
1017 ssid = "wps-er-ap-config"
1018 ap_pin = "12345670"
1019 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1020 hostapd.add_ap(apdev[0]['ifname'],
1021 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1022 "wpa_passphrase": "12345678", "wpa": "2",
1023 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1024 "device_name": "Wireless AP", "manufacturer": "Company",
1025 "model_name": "WAP", "model_number": "123",
1026 "serial_number": "12345", "device_type": "6-0050F204-1",
1027 "os_version": "01020300",
1028 "config_methods": "label push_button",
1029 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1030
1031 logger.info("Connect ER to the AP")
1032 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1033
1034 logger.info("WPS configuration step")
1035 dev[0].request("WPS_ER_START ifname=lo")
1036 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1037 if ev is None:
1038 raise Exception("AP discovery timed out")
1039 if ap_uuid not in ev:
1040 raise Exception("Expected AP UUID not found")
1041 new_passphrase = "1234567890"
1042 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1043 ssid.encode("hex") + " WPA2PSK CCMP " +
1044 new_passphrase.encode("hex"))
1045 ev = dev[0].wait_event(["WPS-SUCCESS"])
1046 if ev is None:
1047 raise Exception("WPS ER configuration operation timed out")
1048 dev[1].wait_event(["CTRL-EVENT-DISCONNECTED"])
1049 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1050
bff3ac5b
JM
1051def test_ap_wps_fragmentation(dev, apdev):
1052 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1053 ssid = "test-wps-fragmentation"
9602b355 1054 appin = "12345670"
bff3ac5b
JM
1055 hostapd.add_ap(apdev[0]['ifname'],
1056 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1057 "wpa_passphrase": "12345678", "wpa": "3",
1058 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9602b355 1059 "wpa_pairwise": "TKIP", "ap_pin": appin,
bff3ac5b
JM
1060 "fragment_size": "50" })
1061 hapd = hostapd.Hostapd(apdev[0]['ifname'])
9602b355 1062 logger.info("WPS provisioning step (PBC)")
bff3ac5b 1063 hapd.request("WPS_PBC")
bff3ac5b
JM
1064 dev[0].dump_monitor()
1065 dev[0].request("SET wps_fragment_size 50")
1066 dev[0].request("WPS_PBC")
1067 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1068 if ev is None:
1069 raise Exception("Association with the AP timed out")
1070 status = dev[0].get_status()
1071 if status['wpa_state'] != 'COMPLETED':
9602b355
JM
1072 raise Exception("Not fully connected")
1073 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1074 raise Exception("Unexpected encryption configuration")
1075 if status['key_mgmt'] != 'WPA2-PSK':
1076 raise Exception("Unexpected key_mgmt")
1077
1078 logger.info("WPS provisioning step (PIN)")
1079 pin = dev[1].wps_read_pin()
1080 hapd.request("WPS_PIN any " + pin)
1081 dev[1].request("SET wps_fragment_size 50")
1082 dev[1].request("WPS_PIN any " + pin)
1083 ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1084 if ev is None:
1085 raise Exception("Association with the AP timed out")
1086 status = dev[1].get_status()
1087 if status['wpa_state'] != 'COMPLETED':
1088 raise Exception("Not fully connected")
1089 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1090 raise Exception("Unexpected encryption configuration")
1091 if status['key_mgmt'] != 'WPA2-PSK':
1092 raise Exception("Unexpected key_mgmt")
1093
1094 logger.info("WPS connection as registrar")
1095 dev[2].request("SET wps_fragment_size 50")
1096 dev[2].wps_reg(apdev[0]['bssid'], appin)
1097 status = dev[2].get_status()
1098 if status['wpa_state'] != 'COMPLETED':
bff3ac5b
JM
1099 raise Exception("Not fully connected")
1100 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1101 raise Exception("Unexpected encryption configuration")
1102 if status['key_mgmt'] != 'WPA2-PSK':
1103 raise Exception("Unexpected key_mgmt")
10ea6848
JM
1104
1105def test_ap_wps_new_version_sta(dev, apdev):
1106 """WPS compatibility with new version number on the station"""
1107 ssid = "test-wps-ver"
1108 hostapd.add_ap(apdev[0]['ifname'],
1109 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1110 "wpa_passphrase": "12345678", "wpa": "2",
1111 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1112 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1113 logger.info("WPS provisioning step")
1114 hapd.request("WPS_PBC")
10ea6848
JM
1115 dev[0].dump_monitor()
1116 dev[0].request("SET wps_version_number 0x43")
dccafedb 1117 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
10ea6848
JM
1118 dev[0].request("WPS_PBC")
1119 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1120 if ev is None:
1121 raise Exception("Association with the AP timed out")
1122
1123def test_ap_wps_new_version_ap(dev, apdev):
1124 """WPS compatibility with new version number on the AP"""
1125 ssid = "test-wps-ver"
1126 hostapd.add_ap(apdev[0]['ifname'],
1127 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1128 "wpa_passphrase": "12345678", "wpa": "2",
1129 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1130 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1131 logger.info("WPS provisioning step")
1132 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1133 raise Exception("Failed to enable test functionality")
1134 hapd.request("WPS_PBC")
10ea6848
JM
1135 dev[0].dump_monitor()
1136 dev[0].request("WPS_PBC")
1137 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1138 hapd.request("SET wps_version_number 0x20")
1139 if ev is None:
1140 raise Exception("Association with the AP timed out")
3bdf7d7f
JM
1141
1142def test_ap_wps_check_pin(dev, apdev):
1143 """Verify PIN checking through control interface"""
1144 hostapd.add_ap(apdev[0]['ifname'],
1145 { "ssid": "wps", "eap_server": "1", "wps_state": "2",
1146 "wpa_passphrase": "12345678", "wpa": "2",
1147 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1148 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1149 for t in [ ("12345670", "12345670"),
1150 ("12345678", "FAIL-CHECKSUM"),
df58939c 1151 ("12345", "FAIL"),
6e12eaa4 1152 ("123456789", "FAIL"),
3bdf7d7f
JM
1153 ("1234-5670", "12345670"),
1154 ("1234 5670", "12345670"),
1155 ("1-2.3:4 5670", "12345670") ]:
1156 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1157 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1158 if res != res2:
1159 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
1160 if res != t[1]:
1161 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
9ba1fcb0 1162
ac786d67
JM
1163 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
1164 raise Exception("Unexpected WPS_CHECK_PIN success")
1165 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
1166 raise Exception("Unexpected WPS_CHECK_PIN success")
1167
acd9b45a
JM
1168 for i in range(0, 10):
1169 pin = dev[0].request("WPS_PIN get")
1170 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
1171 if pin != rpin:
1172 raise Exception("Random PIN validation failed for " + pin)
1173
9ba1fcb0
JM
1174def test_ap_wps_wep_config(dev, apdev):
1175 """WPS 2.0 AP rejecting WEP configuration"""
1176 ssid = "test-wps-config"
1177 appin = "12345670"
1178 hostapd.add_ap(apdev[0]['ifname'],
1179 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1180 "ap_pin": appin})
1181 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1182 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
1183 "hello", no_wait=True)
1184 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
1185 if ev is None:
1186 raise Exception("WPS-FAIL timed out")
1187 if "reason=2" not in ev:
1188 raise Exception("Unexpected reason code in WPS-FAIL")
1189 status = hapd.request("WPS_GET_STATUS")
1190 if "Last WPS result: Failed" not in status:
1191 raise Exception("WPS failure result not shown correctly")
1192 if "Failure Reason: WEP Prohibited" not in status:
1193 raise Exception("Failure reason not reported correctly")
1194 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
1195 raise Exception("Peer address not shown correctly")
1013a576 1196
11d78bb1
JM
1197def test_ap_wps_wep_enroll(dev, apdev):
1198 """WPS 2.0 STA rejecting WEP configuration"""
1199 ssid = "test-wps-wep"
1200 hostapd.add_ap(apdev[0]['ifname'],
1201 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1202 "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
1203 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1204 hapd.request("WPS_PBC")
1205 dev[0].request("WPS_PBC")
1206 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1207 if ev is None:
1208 raise Exception("WPS-FAIL event timed out")
1209 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
1210 raise Exception("Unexpected WPS-FAIL event: " + ev)
1211
1013a576
JM
1212def test_ap_wps_ie_fragmentation(dev, apdev):
1213 """WPS AP using fragmented WPS IE"""
1214 ssid = "test-wps-ie-fragmentation"
1215 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1216 "wpa_passphrase": "12345678", "wpa": "2",
1217 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1218 "device_name": "1234567890abcdef1234567890abcdef",
1219 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1220 "model_name": "1234567890abcdef1234567890abcdef",
1221 "model_number": "1234567890abcdef1234567890abcdef",
1222 "serial_number": "1234567890abcdef1234567890abcdef" }
1223 hostapd.add_ap(apdev[0]['ifname'], params)
1224 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1225 hapd.request("WPS_PBC")
1226 dev[0].request("WPS_PBC")
1227 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1228 if ev is None:
1229 raise Exception("Association with the AP timed out")
1230 bss = dev[0].get_bss(apdev[0]['bssid'])
1231 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8 1232 logger.info("Device Name not received correctly")
d7a68ad6 1233 logger.info(bss)
cf3f0ec8
JM
1234 # This can fail if Probe Response frame is missed and Beacon frame was
1235 # used to fill in the BSS entry. This can happen, e.g., during heavy
1236 # load every now and then and is not really an error, so try to
1237 # workaround by runnign another scan.
1238 dev[0].scan(freq="2412", only_new=True)
1239 bss = dev[0].get_bss(apdev[0]['bssid'])
1240 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
1241 logger.info(bss)
1242 raise Exception("Device Name not received correctly")
1013a576
JM
1243 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
1244 raise Exception("Unexpected number of WPS IEs")
44ff0400 1245
2035b170
JM
1246def get_psk(pskfile):
1247 psks = {}
1248 with open(pskfile, "r") as f:
1249 lines = f.read().splitlines()
1250 for l in lines:
1251 if l == "# WPA PSKs":
1252 continue
1253 (addr,psk) = l.split(' ')
1254 psks[addr] = psk
1255 return psks
1256
1257def test_ap_wps_per_station_psk(dev, apdev):
1258 """WPS PBC provisioning with per-station PSK"""
1259 addr0 = dev[0].p2p_dev_addr()
1260 addr1 = dev[1].p2p_dev_addr()
1261 addr2 = dev[2].p2p_dev_addr()
1262 ssid = "wps"
1263 appin = "12345670"
1264 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1265 try:
1266 os.remove(pskfile)
1267 except:
1268 pass
1269
1270 try:
1271 with open(pskfile, "w") as f:
1272 f.write("# WPA PSKs\n")
1273
1274 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1275 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1276 "rsn_pairwise": "CCMP", "ap_pin": appin,
1277 "wpa_psk_file": pskfile }
1278 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1279
1280 logger.info("First enrollee")
1281 hapd.request("WPS_PBC")
1282 dev[0].request("WPS_PBC")
1283 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
1284 if ev is None:
1285 raise Exception("Association with the AP timed out (1)")
1286
1287 logger.info("Second enrollee")
1288 hapd.request("WPS_PBC")
1289 dev[1].request("WPS_PBC")
1290 ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"])
1291 if ev is None:
1292 raise Exception("Association with the AP timed out (2)")
1293
1294 logger.info("External registrar")
1295 dev[2].wps_reg(apdev[0]['bssid'], appin)
1296
1297 logger.info("Verifying PSK results")
1298 psks = get_psk(pskfile)
1299 if addr0 not in psks:
1300 raise Exception("No PSK recorded for sta0")
1301 if addr1 not in psks:
1302 raise Exception("No PSK recorded for sta1")
1303 if addr2 not in psks:
1304 raise Exception("No PSK recorded for sta2")
1305 if psks[addr0] == psks[addr1]:
1306 raise Exception("Same PSK recorded for sta0 and sta1")
1307 if psks[addr0] == psks[addr2]:
1308 raise Exception("Same PSK recorded for sta0 and sta2")
1309 if psks[addr1] == psks[addr2]:
1310 raise Exception("Same PSK recorded for sta1 and sta2")
1311
1312 dev[0].request("REMOVE_NETWORK all")
1313 logger.info("Second external registrar")
1314 dev[0].wps_reg(apdev[0]['bssid'], appin)
1315 psks2 = get_psk(pskfile)
1316 if addr0 not in psks2:
1317 raise Exception("No PSK recorded for sta0(reg)")
1318 if psks[addr0] == psks2[addr0]:
1319 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
1320 finally:
1321 os.remove(pskfile)
1322
373cce55
JM
1323def test_ap_wps_per_station_psk_failure(dev, apdev):
1324 """WPS PBC provisioning with per-station PSK (file not writable)"""
1325 addr0 = dev[0].p2p_dev_addr()
1326 addr1 = dev[1].p2p_dev_addr()
1327 addr2 = dev[2].p2p_dev_addr()
1328 ssid = "wps"
1329 appin = "12345670"
1330 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1331 try:
1332 os.remove(pskfile)
1333 except:
1334 pass
1335
1336 try:
1337 with open(pskfile, "w") as f:
1338 f.write("# WPA PSKs\n")
1339
1340 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1341 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1342 "rsn_pairwise": "CCMP", "ap_pin": appin,
1343 "wpa_psk_file": pskfile }
1344 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1345 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
1346 raise Exception("Failed to set wpa_psk_file")
1347
1348 logger.info("First enrollee")
1349 hapd.request("WPS_PBC")
1350 dev[0].request("WPS_PBC")
1351 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"])
1352 if ev is None:
1353 raise Exception("Association with the AP timed out (1)")
1354
1355 logger.info("Second enrollee")
1356 hapd.request("WPS_PBC")
1357 dev[1].request("WPS_PBC")
1358 ev = dev[1].wait_event(["CTRL-EVENT-CONNECTED"])
1359 if ev is None:
1360 raise Exception("Association with the AP timed out (2)")
1361
1362 logger.info("External registrar")
1363 dev[2].wps_reg(apdev[0]['bssid'], appin)
1364
1365 logger.info("Verifying PSK results")
1366 psks = get_psk(pskfile)
1367 if len(psks) > 0:
1368 raise Exception("PSK recorded unexpectedly")
1369 finally:
1370 os.remove(pskfile)
1371
e8518757
JM
1372def test_ap_wps_pin_request_file(dev, apdev):
1373 """WPS PIN provisioning with configured AP"""
1374 ssid = "wps"
1375 pinfile = "/tmp/ap_wps_pin_request_file.log"
1376 if os.path.exists(pinfile):
1377 subprocess.call(['sudo', 'rm', pinfile])
1378 hostapd.add_ap(apdev[0]['ifname'],
1379 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1380 "wps_pin_requests": pinfile,
1381 "wpa_passphrase": "12345678", "wpa": "2",
1382 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1383 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1384 uuid = dev[0].get_status_field("uuid")
1385 pin = dev[0].wps_read_pin()
1386 try:
1387 dev[0].request("WPS_PIN any " + pin)
1388 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
1389 if ev is None:
1390 raise Exception("PIN needed event not shown")
1391 if uuid not in ev:
1392 raise Exception("UUID mismatch")
1393 dev[0].request("WPS_CANCEL")
1394 success = False
1395 with open(pinfile, "r") as f:
1396 lines = f.readlines()
1397 for l in lines:
1398 if uuid in l:
1399 success = True
1400 break
1401 if not success:
1402 raise Exception("PIN request entry not in the log file")
1403 finally:
1404 subprocess.call(['sudo', 'rm', pinfile])
1405
56887c35
JM
1406def test_ap_wps_auto_setup_with_config_file(dev, apdev):
1407 """WPS auto-setup with configuration file"""
1408 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
1409 ifname = apdev[0]['ifname']
1410 try:
1411 with open(conffile, "w") as f:
1412 f.write("driver=nl80211\n")
1413 f.write("hw_mode=g\n")
1414 f.write("channel=1\n")
1415 f.write("ieee80211n=1\n")
1416 f.write("interface=%s\n" % ifname)
1417 f.write("ctrl_interface=/var/run/hostapd\n")
1418 f.write("ssid=wps\n")
1419 f.write("eap_server=1\n")
1420 f.write("wps_state=1\n")
1421 hostapd.add_bss('phy3', ifname, conffile)
1422 hapd = hostapd.Hostapd(ifname)
1423 hapd.request("WPS_PBC")
1424 dev[0].request("WPS_PBC")
1425 ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=30)
1426 if ev is None:
1427 raise Exception("Association with the AP timed out")
1428 with open(conffile, "r") as f:
1429 lines = f.read().splitlines()
1430 vals = dict()
1431 for l in lines:
1432 try:
1433 [name,value] = l.split('=', 1)
1434 vals[name] = value
1435 except ValueError, e:
1436 if "# WPS configuration" in l:
1437 pass
1438 else:
1439 raise Exception("Unexpected configuration line: " + l)
1440 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
1441 raise Exception("Incorrect configuration: " + str(vals))
1442 finally:
1443 subprocess.call(['sudo', 'rm', conffile])
1444
91f3cf69
JM
1445def test_ap_wps_pbc_timeout(dev, apdev, params):
1446 """wpa_supplicant PBC walk time [long]"""
1447 if not params['long']:
1448 logger.info("Skip test case with long duration due to --long not specified")
1449 return "skip"
1450 ssid = "test-wps"
1451 hostapd.add_ap(apdev[0]['ifname'],
1452 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
1453 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1454 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
1455 if "OK" not in dev[0].request("WPS_PBC"):
1456 raise Exception("WPS_PBC failed")
1457 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=150)
1458 if ev is None:
1459 raise Exception("WPS-TIMEOUT not reported")
1460
44ff0400
JM
1461def add_ssdp_ap(ifname, ap_uuid):
1462 ssid = "wps-ssdp"
1463 ap_pin = "12345670"
1464 hostapd.add_ap(ifname,
1465 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1466 "wpa_passphrase": "12345678", "wpa": "2",
1467 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1468 "device_name": "Wireless AP", "manufacturer": "Company",
1469 "model_name": "WAP", "model_number": "123",
1470 "serial_number": "12345", "device_type": "6-0050F204-1",
1471 "os_version": "01020300",
1472 "config_methods": "label push_button",
1473 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
1474 "friendly_name": "WPS Access Point",
1475 "manufacturer_url": "http://www.example.com/",
1476 "model_description": "Wireless Access Point",
1477 "model_url": "http://www.example.com/model/",
1478 "upc": "123456789012" })
1479
1480def ssdp_send(msg, no_recv=False):
1481 socket.setdefaulttimeout(1)
1482 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1483 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1484 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1485 sock.bind(("127.0.0.1", 0))
1486 sock.sendto(msg, ("239.255.255.250", 1900))
1487 if no_recv:
1488 return None
1489 return sock.recv(1000)
1490
1491def ssdp_send_msearch(st):
1492 msg = '\r\n'.join([
1493 'M-SEARCH * HTTP/1.1',
1494 'HOST: 239.255.255.250:1900',
1495 'MX: 1',
1496 'MAN: "ssdp:discover"',
1497 'ST: ' + st,
1498 '', ''])
47c549fd 1499 return ssdp_send(msg)
44ff0400
JM
1500
1501def test_ap_wps_ssdp_msearch(dev, apdev):
1502 """WPS AP and SSDP M-SEARCH messages"""
1503 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1504 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1505
1506 msg = '\r\n'.join([
1507 'M-SEARCH * HTTP/1.1',
1508 'Host: 239.255.255.250:1900',
1509 'Mx: 1',
1510 'Man: "ssdp:discover"',
1511 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
1512 '', ''])
1513 ssdp_send(msg)
1514
1515 msg = '\r\n'.join([
1516 'M-SEARCH * HTTP/1.1',
1517 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
1518 'mx: \t1\t\t ',
1519 'man: \t \t "ssdp:discover" ',
1520 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
1521 '', ''])
1522 ssdp_send(msg)
1523
1524 ssdp_send_msearch("ssdp:all")
1525 ssdp_send_msearch("upnp:rootdevice")
1526 ssdp_send_msearch("uuid:" + ap_uuid)
1527 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
1528 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
1529
1530 msg = '\r\n'.join([
1531 'M-SEARCH * HTTP/1.1',
1532 'HOST:\t239.255.255.250:1900',
1533 'MAN: "ssdp:discover"',
1534 'MX: 130',
1535 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1536 '', ''])
1537 ssdp_send(msg, no_recv=True)
1538
1539def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
1540 """WPS AP and invalid SSDP M-SEARCH messages"""
1541 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1542 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1543
1544 socket.setdefaulttimeout(1)
1545 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1546 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1547 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1548 sock.bind(("127.0.0.1", 0))
1549
1550 logger.debug("Missing MX")
1551 msg = '\r\n'.join([
1552 'M-SEARCH * HTTP/1.1',
1553 'HOST: 239.255.255.250:1900',
1554 'MAN: "ssdp:discover"',
1555 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1556 '', ''])
1557 sock.sendto(msg, ("239.255.255.250", 1900))
1558
1559 logger.debug("Negative MX")
1560 msg = '\r\n'.join([
1561 'M-SEARCH * HTTP/1.1',
1562 'HOST: 239.255.255.250:1900',
1563 'MX: -1',
1564 'MAN: "ssdp:discover"',
1565 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1566 '', ''])
1567 sock.sendto(msg, ("239.255.255.250", 1900))
1568
1569 logger.debug("Invalid MX")
1570 msg = '\r\n'.join([
1571 'M-SEARCH * HTTP/1.1',
1572 'HOST: 239.255.255.250:1900',
1573 'MX; 1',
1574 'MAN: "ssdp:discover"',
1575 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1576 '', ''])
1577 sock.sendto(msg, ("239.255.255.250", 1900))
1578
1579 logger.debug("Missing MAN")
1580 msg = '\r\n'.join([
1581 'M-SEARCH * HTTP/1.1',
1582 'HOST: 239.255.255.250:1900',
1583 'MX: 1',
1584 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1585 '', ''])
1586 sock.sendto(msg, ("239.255.255.250", 1900))
1587
1588 logger.debug("Invalid MAN")
1589 msg = '\r\n'.join([
1590 'M-SEARCH * HTTP/1.1',
1591 'HOST: 239.255.255.250:1900',
1592 'MX: 1',
1593 'MAN: foo',
1594 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1595 '', ''])
1596 sock.sendto(msg, ("239.255.255.250", 1900))
1597 msg = '\r\n'.join([
1598 'M-SEARCH * HTTP/1.1',
1599 'HOST: 239.255.255.250:1900',
1600 'MX: 1',
1601 'MAN; "ssdp:discover"',
1602 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1603 '', ''])
1604 sock.sendto(msg, ("239.255.255.250", 1900))
1605
1606 logger.debug("Missing HOST")
1607 msg = '\r\n'.join([
1608 'M-SEARCH * HTTP/1.1',
1609 'MAN: "ssdp:discover"',
1610 'MX: 1',
1611 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1612 '', ''])
1613 sock.sendto(msg, ("239.255.255.250", 1900))
1614
1615 logger.debug("Missing ST")
1616 msg = '\r\n'.join([
1617 'M-SEARCH * HTTP/1.1',
1618 'HOST: 239.255.255.250:1900',
1619 'MAN: "ssdp:discover"',
1620 'MX: 1',
1621 '', ''])
1622 sock.sendto(msg, ("239.255.255.250", 1900))
1623
1624 logger.debug("Mismatching ST")
1625 msg = '\r\n'.join([
1626 'M-SEARCH * HTTP/1.1',
1627 'HOST: 239.255.255.250:1900',
1628 'MAN: "ssdp:discover"',
1629 'MX: 1',
1630 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
1631 '', ''])
1632 sock.sendto(msg, ("239.255.255.250", 1900))
1633 msg = '\r\n'.join([
1634 'M-SEARCH * HTTP/1.1',
1635 'HOST: 239.255.255.250:1900',
1636 'MAN: "ssdp:discover"',
1637 'MX: 1',
1638 'ST: foo:bar',
1639 '', ''])
1640 sock.sendto(msg, ("239.255.255.250", 1900))
1641 msg = '\r\n'.join([
1642 'M-SEARCH * HTTP/1.1',
1643 'HOST: 239.255.255.250:1900',
1644 'MAN: "ssdp:discover"',
1645 'MX: 1',
1646 'ST: foobar',
1647 '', ''])
1648 sock.sendto(msg, ("239.255.255.250", 1900))
1649
1650 logger.debug("Invalid ST")
1651 msg = '\r\n'.join([
1652 'M-SEARCH * HTTP/1.1',
1653 'HOST: 239.255.255.250:1900',
1654 'MAN: "ssdp:discover"',
1655 'MX: 1',
1656 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
1657 '', ''])
1658 sock.sendto(msg, ("239.255.255.250", 1900))
1659
1660 logger.debug("Invalid M-SEARCH")
1661 msg = '\r\n'.join([
1662 'M+SEARCH * HTTP/1.1',
1663 'HOST: 239.255.255.250:1900',
1664 'MAN: "ssdp:discover"',
1665 'MX: 1',
1666 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1667 '', ''])
1668 sock.sendto(msg, ("239.255.255.250", 1900))
1669 msg = '\r\n'.join([
1670 'M-SEARCH-* HTTP/1.1',
1671 'HOST: 239.255.255.250:1900',
1672 'MAN: "ssdp:discover"',
1673 'MX: 1',
1674 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1675 '', ''])
1676 sock.sendto(msg, ("239.255.255.250", 1900))
1677
1678 logger.debug("Invalid message format")
1679 sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
1680 msg = '\r'.join([
1681 'M-SEARCH * HTTP/1.1',
1682 'HOST: 239.255.255.250:1900',
1683 'MAN: "ssdp:discover"',
1684 'MX: 1',
1685 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1686 '', ''])
1687 sock.sendto(msg, ("239.255.255.250", 1900))
1688
1689 try:
1690 r = sock.recv(1000)
1691 raise Exception("Unexpected M-SEARCH response: " + r)
1692 except socket.timeout:
1693 pass
1694
1695 logger.debug("Valid M-SEARCH")
1696 msg = '\r\n'.join([
1697 'M-SEARCH * HTTP/1.1',
1698 'HOST: 239.255.255.250:1900',
1699 'MAN: "ssdp:discover"',
1700 'MX: 1',
1701 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1702 '', ''])
1703 sock.sendto(msg, ("239.255.255.250", 1900))
1704
1705 try:
1706 r = sock.recv(1000)
1707 pass
1708 except socket.timeout:
1709 raise Exception("No SSDP response")
1710
1711def test_ap_wps_ssdp_burst(dev, apdev):
1712 """WPS AP and SSDP burst"""
1713 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1714 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1715
1716 msg = '\r\n'.join([
1717 'M-SEARCH * HTTP/1.1',
1718 'HOST: 239.255.255.250:1900',
1719 'MAN: "ssdp:discover"',
1720 'MX: 1',
1721 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1722 '', ''])
1723 socket.setdefaulttimeout(1)
1724 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1725 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1726 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1727 sock.bind(("127.0.0.1", 0))
1728 for i in range(0, 25):
1729 sock.sendto(msg, ("239.255.255.250", 1900))
1730 resp = 0
1731 while True:
1732 try:
1733 r = sock.recv(1000)
1734 if not r.startswith("HTTP/1.1 200 OK\r\n"):
1735 raise Exception("Unexpected message: " + r)
1736 resp += 1
1737 except socket.timeout:
1738 break
1739 if resp < 20:
1740 raise Exception("Too few SSDP responses")
1741
1742 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1743 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1744 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1745 sock.bind(("127.0.0.1", 0))
1746 for i in range(0, 25):
1747 sock.sendto(msg, ("239.255.255.250", 1900))
1748 while True:
1749 try:
1750 r = sock.recv(1000)
1751 if ap_uuid in r:
1752 break
1753 except socket.timeout:
1754 raise Exception("No SSDP response")
47c549fd
JM
1755
1756def ssdp_get_location(uuid):
1757 res = ssdp_send_msearch("uuid:" + uuid)
1758 location = None
1759 for l in res.splitlines():
1760 if l.lower().startswith("location:"):
1761 location = l.split(':', 1)[1].strip()
1762 break
1763 if location is None:
1764 raise Exception("No UPnP location found")
1765 return location
1766
1767def upnp_get_urls(location):
1768 conn = urllib.urlopen(location)
1769 tree = ET.parse(conn)
1770 root = tree.getroot()
1771 urn = '{urn:schemas-upnp-org:device-1-0}'
1772 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
1773 res = {}
1774 res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
1775 res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
1776 res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
1777 return res
1778
1779def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
1780 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
1781 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
1782 ET.register_namespace('soapenv', soapns)
1783 ET.register_namespace('wfa', wpsns)
1784 attrib = {}
1785 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
1786 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
1787 body = ET.SubElement(root, "{%s}Body" % soapns)
1788 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
1789 tree = ET.ElementTree(root)
1790 soap = StringIO.StringIO()
1791 tree.write(soap, xml_declaration=True, encoding='utf-8')
1792
1793 headers = { "Content-type": 'text/xml; charset="utf-8"' }
1794 if include_soap_action:
1795 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
1796 elif soap_action_override:
1797 headers["SOAPAction"] = soap_action_override
1798 conn.request("POST", path, soap.getvalue(), headers)
1799 return conn.getresponse()
1800
1801def test_ap_wps_upnp(dev, apdev):
1802 """WPS AP and UPnP operations"""
1803 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1804 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1805
1806 location = ssdp_get_location(ap_uuid)
1807 urls = upnp_get_urls(location)
1808
1809 conn = urllib.urlopen(urls['scpd_url'])
1810 scpd = conn.read()
1811
1812 conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
1813 if conn.getcode() != 404:
1814 raise Exception("Unexpected HTTP response to GET unknown URL")
1815
1816 url = urlparse.urlparse(location)
1817 conn = httplib.HTTPConnection(url.netloc)
1818 #conn.set_debuglevel(1)
1819 headers = { "Content-type": 'text/xml; charset="utf-8"',
1820 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
1821 conn.request("POST", "hello", "\r\n\r\n", headers)
1822 resp = conn.getresponse()
1823 if resp.status != 404:
1824 raise Exception("Unexpected HTTP response: %s" % resp.status)
1825
1826 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
1827 resp = conn.getresponse()
1828 if resp.status != 501:
1829 raise Exception("Unexpected HTTP response: %s" % resp.status)
1830
1831 headers = { "Content-type": 'text/xml; charset="utf-8"',
1832 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
1833 ctrlurl = urlparse.urlparse(urls['control_url'])
1834 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
1835 resp = conn.getresponse()
1836 if resp.status != 401:
1837 raise Exception("Unexpected HTTP response: %s" % resp.status)
1838
1839 logger.debug("GetDeviceInfo without SOAPAction header")
1840 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
1841 include_soap_action=False)
1842 if resp.status != 401:
1843 raise Exception("Unexpected HTTP response: %s" % resp.status)
1844
1845 logger.debug("GetDeviceInfo with invalid SOAPAction header")
1846 for act in [ "foo",
1847 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
1848 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
1849 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
1850 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
1851 include_soap_action=False,
1852 soap_action_override=act)
1853 if resp.status != 401:
1854 raise Exception("Unexpected HTTP response: %s" % resp.status)
1855
1856 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
1857 if resp.status != 200:
1858 raise Exception("Unexpected HTTP response: %s" % resp.status)
1859 dev = resp.read()
1860 if "NewDeviceInfo" not in dev:
1861 raise Exception("Unexpected GetDeviceInfo response")
1862
1863 logger.debug("PutMessage without required parameters")
1864 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
1865 if resp.status != 600:
1866 raise Exception("Unexpected HTTP response: %s" % resp.status)
1867
1868 logger.debug("PutWLANResponse without required parameters")
1869 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
1870 if resp.status != 600:
1871 raise Exception("Unexpected HTTP response: %s" % resp.status)
1872
1873 logger.debug("SetSelectedRegistrar from unregistered ER")
1874 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
1875 if resp.status != 501:
1876 raise Exception("Unexpected HTTP response: %s" % resp.status)
1877
1878 logger.debug("Unknown action")
1879 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
1880 if resp.status != 401:
1881 raise Exception("Unexpected HTTP response: %s" % resp.status)
1882
1883def test_ap_wps_upnp_subscribe(dev, apdev):
1884 """WPS AP and UPnP event subscription"""
1885 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1886 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1887
1888 location = ssdp_get_location(ap_uuid)
1889 urls = upnp_get_urls(location)
1890 eventurl = urlparse.urlparse(urls['event_sub_url'])
1891
1892 url = urlparse.urlparse(location)
1893 conn = httplib.HTTPConnection(url.netloc)
1894 #conn.set_debuglevel(1)
1895 headers = { "callback": '<http://127.0.0.1:12345/event>',
1896 "timeout": "Second-1234" }
1897 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
1898 resp = conn.getresponse()
1899 if resp.status != 412:
1900 raise Exception("Unexpected HTTP response: %s" % resp.status)
1901
1902 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1903 resp = conn.getresponse()
1904 if resp.status != 412:
1905 raise Exception("Unexpected HTTP response: %s" % resp.status)
1906
1907 headers = { "NT": "upnp:event",
1908 "timeout": "Second-1234" }
1909 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1910 resp = conn.getresponse()
1911 if resp.status != 412:
1912 raise Exception("Unexpected HTTP response: %s" % resp.status)
1913
1914 headers = { "callback": '<http://127.0.0.1:12345/event>',
1915 "NT": "upnp:foobar",
1916 "timeout": "Second-1234" }
1917 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1918 resp = conn.getresponse()
1919 if resp.status != 400:
1920 raise Exception("Unexpected HTTP response: %s" % resp.status)
1921
1922 logger.debug("Valid subscription")
1923 headers = { "callback": '<http://127.0.0.1:12345/event>',
1924 "NT": "upnp:event",
1925 "timeout": "Second-1234" }
1926 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1927 resp = conn.getresponse()
1928 if resp.status != 200:
1929 raise Exception("Unexpected HTTP response: %s" % resp.status)
1930 sid = resp.getheader("sid")
1931 logger.debug("Subscription SID " + sid)
1932
1933 logger.debug("Invalid re-subscription")
1934 headers = { "NT": "upnp:event",
1935 "sid": "123456734567854",
1936 "timeout": "Second-1234" }
1937 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1938 resp = conn.getresponse()
1939 if resp.status != 400:
1940 raise Exception("Unexpected HTTP response: %s" % resp.status)
1941
1942 logger.debug("Invalid re-subscription")
1943 headers = { "NT": "upnp:event",
1944 "sid": "uuid:123456734567854",
1945 "timeout": "Second-1234" }
1946 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1947 resp = conn.getresponse()
1948 if resp.status != 400:
1949 raise Exception("Unexpected HTTP response: %s" % resp.status)
1950
1951 logger.debug("Invalid re-subscription")
1952 headers = { "callback": '<http://127.0.0.1:12345/event>',
1953 "NT": "upnp:event",
1954 "sid": sid,
1955 "timeout": "Second-1234" }
1956 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1957 resp = conn.getresponse()
1958 if resp.status != 400:
1959 raise Exception("Unexpected HTTP response: %s" % resp.status)
1960
1961 logger.debug("SID mismatch in re-subscription")
1962 headers = { "NT": "upnp:event",
1963 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
1964 "timeout": "Second-1234" }
1965 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1966 resp = conn.getresponse()
1967 if resp.status != 412:
1968 raise Exception("Unexpected HTTP response: %s" % resp.status)
1969
1970 logger.debug("Valid re-subscription")
1971 headers = { "NT": "upnp:event",
1972 "sid": sid,
1973 "timeout": "Second-1234" }
1974 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1975 resp = conn.getresponse()
1976 if resp.status != 200:
1977 raise Exception("Unexpected HTTP response: %s" % resp.status)
1978 sid2 = resp.getheader("sid")
1979 logger.debug("Subscription SID " + sid2)
1980
1981 if sid != sid2:
1982 raise Exception("Unexpected SID change")
1983
1984 logger.debug("Valid re-subscription")
1985 headers = { "NT": "upnp:event",
1986 "sid": "uuid: \t \t" + sid.split(':')[1],
1987 "timeout": "Second-1234" }
1988 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
1989 resp = conn.getresponse()
1990 if resp.status != 200:
1991 raise Exception("Unexpected HTTP response: %s" % resp.status)
1992
1993 logger.debug("Invalid unsubscription")
1994 headers = { "sid": sid }
1995 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
1996 resp = conn.getresponse()
1997 if resp.status != 412:
1998 raise Exception("Unexpected HTTP response: %s" % resp.status)
1999 headers = { "foo": "bar" }
2000 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2001 resp = conn.getresponse()
2002 if resp.status != 412:
2003 raise Exception("Unexpected HTTP response: %s" % resp.status)
2004
2005 logger.debug("Valid unsubscription")
2006 headers = { "sid": sid }
2007 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2008 resp = conn.getresponse()
2009 if resp.status != 200:
2010 raise Exception("Unexpected HTTP response: %s" % resp.status)
2011
2012 logger.debug("Unsubscription for not existing SID")
2013 headers = { "sid": sid }
2014 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2015 resp = conn.getresponse()
2016 if resp.status != 412:
2017 raise Exception("Unexpected HTTP response: %s" % resp.status)
2018
2019 logger.debug("Invalid unsubscription")
2020 headers = { "sid": " \t \tfoo" }
2021 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2022 resp = conn.getresponse()
2023 if resp.status != 400:
2024 raise Exception("Unexpected HTTP response: %s" % resp.status)
2025
2026 logger.debug("Invalid unsubscription")
2027 headers = { "sid": "uuid:\t \tfoo" }
2028 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2029 resp = conn.getresponse()
2030 if resp.status != 400:
2031 raise Exception("Unexpected HTTP response: %s" % resp.status)
2032
2033 logger.debug("Invalid unsubscription")
2034 headers = { "NT": "upnp:event",
2035 "sid": sid }
2036 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2037 resp = conn.getresponse()
2038 if resp.status != 400:
2039 raise Exception("Unexpected HTTP response: %s" % resp.status)
2040 headers = { "callback": '<http://127.0.0.1:12345/event>',
2041 "sid": sid }
2042 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2043 resp = conn.getresponse()
2044 if resp.status != 400:
2045 raise Exception("Unexpected HTTP response: %s" % resp.status)
2046
2047 logger.debug("Valid subscription with multiple callbacks")
2048 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>',
2049 "NT": "upnp:event",
2050 "timeout": "Second-1234" }
2051 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2052 resp = conn.getresponse()
2053 if resp.status != 200:
2054 raise Exception("Unexpected HTTP response: %s" % resp.status)
2055 sid = resp.getheader("sid")
2056 logger.debug("Subscription SID " + sid)