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