]> git.ipfire.org Git - thirdparty/hostap.git/blame - tests/hwsim/test_ap_wps.py
tests: BSS entry expiration when AP changes SSID
[thirdparty/hostap.git] / tests / hwsim / test_ap_wps.py
CommitLineData
302b7a1b 1# WPS tests
a1eabc74 2# Copyright (c) 2013-2015, 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 8import time
2602a2ff 9import stat
302b7a1b
JM
10import subprocess
11import logging
c9aa4308 12logger = logging.getLogger()
1013a576 13import re
44ff0400 14import socket
47c549fd
JM
15import httplib
16import urlparse
17import urllib
18import xml.etree.ElementTree as ET
19import StringIO
c965ae03 20import SocketServer
302b7a1b
JM
21
22import hwsim_utils
23import hostapd
1531402e 24from wpasupplicant import WpaSupplicant
c965ae03 25from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
302b7a1b 26
ae3ad328 27def test_ap_wps_init(dev, apdev):
302b7a1b
JM
28 """Initial AP configuration with first WPS Enrollee"""
29 ssid = "test-wps"
ae3ad328 30 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b 31 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
ae3ad328 32 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
33 logger.info("WPS provisioning step")
34 hapd.request("WPS_PBC")
d671a420
JM
35 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
36 raise Exception("PBC status not shown correctly")
b9018833
JM
37
38 id = dev[0].add_network()
39 dev[0].set_network_quoted(id, "ssid", "home")
40 dev[0].set_network_quoted(id, "psk", "12345678")
41 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
42
43 id = dev[0].add_network()
44 dev[0].set_network_quoted(id, "ssid", "home2")
45 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
46 dev[0].set_network(id, "key_mgmt", "NONE")
47 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
48
302b7a1b 49 dev[0].request("WPS_PBC")
5f35a5e2 50 dev[0].wait_connected(timeout=30)
302b7a1b 51 status = dev[0].get_status()
ae3ad328 52 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
53 raise Exception("Not fully connected")
54 if status['ssid'] != ssid:
55 raise Exception("Unexpected SSID")
56 if status['pairwise_cipher'] != 'CCMP':
57 raise Exception("Unexpected encryption configuration")
58 if status['key_mgmt'] != 'WPA2-PSK':
59 raise Exception("Unexpected key_mgmt")
60
d671a420
JM
61 status = hapd.request("WPS_GET_STATUS")
62 if "PBC Status: Disabled" not in status:
63 raise Exception("PBC status not shown correctly")
64 if "Last WPS result: Success" not in status:
65 raise Exception("Last WPS result not shown correctly")
66 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
67 raise Exception("Peer address not shown correctly")
75b25ece
JM
68 conf = hapd.request("GET_CONFIG")
69 if "wps_state=configured" not in conf:
70 raise Exception("AP not in WPS configured state")
742408af
JM
71 if "wpa=3" not in conf:
72 raise Exception("AP not in WPA+WPA2 configuration")
75b25ece
JM
73 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
74 raise Exception("Unexpected rsn_pairwise_cipher")
75 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
76 raise Exception("Unexpected wpa_pairwise_cipher")
77 if "group_cipher=TKIP" not in conf:
78 raise Exception("Unexpected group_cipher")
d671a420 79
b9018833
JM
80 if len(dev[0].list_networks()) != 3:
81 raise Exception("Unexpected number of network blocks")
82
18030dc0
JM
83def test_ap_wps_init_2ap_pbc(dev, apdev):
84 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
85 ssid = "test-wps"
86 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
87 hostapd.add_ap(apdev[0]['ifname'], params)
88 hostapd.add_ap(apdev[1]['ifname'], params)
89 hapd = hostapd.Hostapd(apdev[0]['ifname'])
90 logger.info("WPS provisioning step")
91 hapd.request("WPS_PBC")
84a40841
JM
92 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
93 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
94 bss = dev[0].get_bss(apdev[0]['bssid'])
95 if "[WPS-PBC]" not in bss['flags']:
96 raise Exception("WPS-PBC flag missing from AP1")
97 bss = dev[0].get_bss(apdev[1]['bssid'])
98 if "[WPS-PBC]" not in bss['flags']:
99 raise Exception("WPS-PBC flag missing from AP2")
100 dev[0].dump_monitor()
f19d87f1 101 dev[0].request("SET wps_cred_processing 2")
18030dc0 102 dev[0].request("WPS_PBC")
f19d87f1
JM
103 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
104 dev[0].request("SET wps_cred_processing 0")
105 if ev is None:
106 raise Exception("WPS cred event not seen")
107 if "100e" not in ev:
108 raise Exception("WPS attributes not included in the cred event")
5f35a5e2 109 dev[0].wait_connected(timeout=30)
18030dc0 110
84a40841
JM
111 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
112 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
113 bss = dev[1].get_bss(apdev[0]['bssid'])
114 if "[WPS-PBC]" in bss['flags']:
115 raise Exception("WPS-PBC flag not cleared from AP1")
116 bss = dev[1].get_bss(apdev[1]['bssid'])
117 if "[WPS-PBC]" in bss['flags']:
0bde923c 118 raise Exception("WPS-PBC flag not cleared from AP2")
18030dc0
JM
119
120def test_ap_wps_init_2ap_pin(dev, apdev):
121 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
122 ssid = "test-wps"
123 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
124 hostapd.add_ap(apdev[0]['ifname'], params)
125 hostapd.add_ap(apdev[1]['ifname'], params)
126 hapd = hostapd.Hostapd(apdev[0]['ifname'])
127 logger.info("WPS provisioning step")
128 pin = dev[0].wps_read_pin()
129 hapd.request("WPS_PIN any " + pin)
84a40841
JM
130 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
131 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
132 bss = dev[0].get_bss(apdev[0]['bssid'])
133 if "[WPS-AUTH]" not in bss['flags']:
134 raise Exception("WPS-AUTH flag missing from AP1")
135 bss = dev[0].get_bss(apdev[1]['bssid'])
136 if "[WPS-AUTH]" not in bss['flags']:
137 raise Exception("WPS-AUTH flag missing from AP2")
138 dev[0].dump_monitor()
139 dev[0].request("WPS_PIN any " + pin)
5f35a5e2 140 dev[0].wait_connected(timeout=30)
18030dc0 141
84a40841
JM
142 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
143 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
144 bss = dev[1].get_bss(apdev[0]['bssid'])
145 if "[WPS-AUTH]" in bss['flags']:
146 raise Exception("WPS-AUTH flag not cleared from AP1")
147 bss = dev[1].get_bss(apdev[1]['bssid'])
148 if "[WPS-AUTH]" in bss['flags']:
0bde923c 149 raise Exception("WPS-AUTH flag not cleared from AP2")
18030dc0 150
35831e94
JM
151def test_ap_wps_init_through_wps_config(dev, apdev):
152 """Initial AP configuration using wps_config command"""
153 ssid = "test-wps-init-config"
154 hostapd.add_ap(apdev[0]['ifname'],
155 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
156 hapd = hostapd.Hostapd(apdev[0]['ifname'])
157 if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
158 raise Exception("WPS_CONFIG command failed")
180cd73d
JM
159 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
160 if ev is None:
161 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
162 # It takes some time for the AP to update Beacon and Probe Response frames,
163 # so wait here before requesting the scan to be started to avoid adding
164 # extra five second wait to the test due to fetching obsolete scan results.
165 hapd.ping()
166 time.sleep(0.2)
35831e94
JM
167 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
168 pairwise="CCMP", group="CCMP")
169
e1eb0e9e
JM
170def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
171 """AP configuration using wps_config command with invalid passphrase"""
172 ssid = "test-wps-init-config"
173 hostapd.add_ap(apdev[0]['ifname'],
174 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
175 hapd = hostapd.Hostapd(apdev[0]['ifname'])
176 if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
177 raise Exception("Invalid WPS_CONFIG command accepted")
178
ae3ad328 179def test_ap_wps_conf(dev, apdev):
302b7a1b
JM
180 """WPS PBC provisioning with configured AP"""
181 ssid = "test-wps-conf"
ae3ad328 182 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
183 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
184 "wpa_passphrase": "12345678", "wpa": "2",
185 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 186 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
187 logger.info("WPS provisioning step")
188 hapd.request("WPS_PBC")
33d0b157 189 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 190 dev[0].dump_monitor()
33d0b157 191 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 192 dev[0].wait_connected(timeout=30)
302b7a1b 193 status = dev[0].get_status()
ae3ad328 194 if status['wpa_state'] != 'COMPLETED':
302b7a1b 195 raise Exception("Not fully connected")
ae3ad328
JM
196 if status['bssid'] != apdev[0]['bssid']:
197 raise Exception("Unexpected BSSID")
302b7a1b
JM
198 if status['ssid'] != ssid:
199 raise Exception("Unexpected SSID")
200 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
201 raise Exception("Unexpected encryption configuration")
202 if status['key_mgmt'] != 'WPA2-PSK':
203 raise Exception("Unexpected key_mgmt")
204
097cd9cd
JM
205 sta = hapd.get_sta(dev[0].p2p_interface_addr())
206 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
207 raise Exception("Device name not available in STA command")
208
daad14cc
JM
209def test_ap_wps_conf_5ghz(dev, apdev):
210 """WPS PBC provisioning with configured AP on 5 GHz band"""
211 try:
9d7fdac5 212 hapd = None
daad14cc
JM
213 ssid = "test-wps-conf"
214 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
215 "wpa_passphrase": "12345678", "wpa": "2",
216 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
217 "country_code": "FI", "hw_mode": "a", "channel": "36" }
218 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
219 logger.info("WPS provisioning step")
220 hapd.request("WPS_PBC")
33d0b157
JM
221 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
222 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 223 dev[0].wait_connected(timeout=30)
daad14cc
JM
224
225 sta = hapd.get_sta(dev[0].p2p_interface_addr())
226 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
227 raise Exception("Device name not available in STA command")
228 finally:
9d7fdac5
JM
229 dev[0].request("DISCONNECT")
230 if hapd:
231 hapd.request("DISABLE")
c4668009 232 subprocess.call(['iw', 'reg', 'set', '00'])
9d7fdac5 233 dev[0].flush_scan_cache()
daad14cc
JM
234
235def test_ap_wps_conf_chan14(dev, apdev):
236 """WPS PBC provisioning with configured AP on channel 14"""
237 try:
9d7fdac5 238 hapd = None
daad14cc
JM
239 ssid = "test-wps-conf"
240 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
241 "wpa_passphrase": "12345678", "wpa": "2",
242 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
243 "country_code": "JP", "hw_mode": "b", "channel": "14" }
244 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
245 logger.info("WPS provisioning step")
246 hapd.request("WPS_PBC")
247 dev[0].request("WPS_PBC")
5f35a5e2 248 dev[0].wait_connected(timeout=30)
daad14cc
JM
249
250 sta = hapd.get_sta(dev[0].p2p_interface_addr())
251 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
252 raise Exception("Device name not available in STA command")
253 finally:
9d7fdac5
JM
254 dev[0].request("DISCONNECT")
255 if hapd:
256 hapd.request("DISABLE")
c4668009 257 subprocess.call(['iw', 'reg', 'set', '00'])
9d7fdac5 258 dev[0].flush_scan_cache()
daad14cc 259
04e62788
JM
260def test_ap_wps_twice(dev, apdev):
261 """WPS provisioning with twice to change passphrase"""
262 ssid = "test-wps-twice"
263 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
264 "wpa_passphrase": "12345678", "wpa": "2",
265 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
266 hostapd.add_ap(apdev[0]['ifname'], params)
267 hapd = hostapd.Hostapd(apdev[0]['ifname'])
268 logger.info("WPS provisioning step")
269 hapd.request("WPS_PBC")
33d0b157 270 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
04e62788 271 dev[0].dump_monitor()
33d0b157 272 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 273 dev[0].wait_connected(timeout=30)
04e62788
JM
274 dev[0].request("DISCONNECT")
275
276 logger.info("Restart AP with different passphrase and re-run WPS")
277 hapd_global = hostapd.HostapdGlobal()
278 hapd_global.remove(apdev[0]['ifname'])
279 params['wpa_passphrase'] = 'another passphrase'
280 hostapd.add_ap(apdev[0]['ifname'], params)
281 hapd = hostapd.Hostapd(apdev[0]['ifname'])
282 logger.info("WPS provisioning step")
283 hapd.request("WPS_PBC")
284 dev[0].dump_monitor()
33d0b157 285 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 286 dev[0].wait_connected(timeout=30)
04e62788
JM
287 networks = dev[0].list_networks()
288 if len(networks) > 1:
289 raise Exception("Unexpected duplicated network block present")
290
d658205a
JM
291def test_ap_wps_incorrect_pin(dev, apdev):
292 """WPS PIN provisioning with incorrect PIN"""
293 ssid = "test-wps-incorrect-pin"
294 hostapd.add_ap(apdev[0]['ifname'],
295 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
296 "wpa_passphrase": "12345678", "wpa": "2",
297 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
298 hapd = hostapd.Hostapd(apdev[0]['ifname'])
299
300 logger.info("WPS provisioning attempt 1")
301 hapd.request("WPS_PIN any 12345670")
33d0b157 302 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
d658205a 303 dev[0].dump_monitor()
33d0b157 304 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
d658205a
JM
305 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
306 if ev is None:
307 raise Exception("WPS operation timed out")
308 if "config_error=18" not in ev:
309 raise Exception("Incorrect config_error reported")
310 if "msg=8" not in ev:
311 raise Exception("PIN error detected on incorrect message")
5f35a5e2 312 dev[0].wait_disconnected(timeout=10)
d658205a
JM
313 dev[0].request("WPS_CANCEL")
314 # if a scan was in progress, wait for it to complete before trying WPS again
315 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
316
d671a420
JM
317 status = hapd.request("WPS_GET_STATUS")
318 if "Last WPS result: Failed" not in status:
319 raise Exception("WPS failure result not shown correctly")
320
d658205a
JM
321 logger.info("WPS provisioning attempt 2")
322 hapd.request("WPS_PIN any 12345670")
323 dev[0].dump_monitor()
33d0b157 324 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
d658205a
JM
325 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
326 if ev is None:
327 raise Exception("WPS operation timed out")
328 if "config_error=18" not in ev:
329 raise Exception("Incorrect config_error reported")
330 if "msg=10" not in ev:
331 raise Exception("PIN error detected on incorrect message")
5f35a5e2 332 dev[0].wait_disconnected(timeout=10)
d658205a 333
ae3ad328 334def test_ap_wps_conf_pin(dev, apdev):
302b7a1b
JM
335 """WPS PIN provisioning with configured AP"""
336 ssid = "test-wps-conf-pin"
ae3ad328 337 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
338 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
339 "wpa_passphrase": "12345678", "wpa": "2",
340 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 341 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
342 logger.info("WPS provisioning step")
343 pin = dev[0].wps_read_pin()
344 hapd.request("WPS_PIN any " + pin)
33d0b157 345 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 346 dev[0].dump_monitor()
33d0b157 347 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 348 dev[0].wait_connected(timeout=30)
302b7a1b 349 status = dev[0].get_status()
ae3ad328 350 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
351 raise Exception("Not fully connected")
352 if status['ssid'] != ssid:
353 raise Exception("Unexpected SSID")
354 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
355 raise Exception("Unexpected encryption configuration")
356 if status['key_mgmt'] != 'WPA2-PSK':
357 raise Exception("Unexpected key_mgmt")
358
84a40841 359 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
362ba6de
JM
360 bss = dev[1].get_bss(apdev[0]['bssid'])
361 if "[WPS-AUTH]" in bss['flags']:
362 raise Exception("WPS-AUTH flag not cleared")
a60a6d6b 363 logger.info("Try to connect from another station using the same PIN")
33d0b157 364 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
a60a6d6b
JM
365 ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
366 if ev is None:
367 raise Exception("Operation timed out")
368 if "WPS-M2D" not in ev:
369 raise Exception("Unexpected WPS operation started")
6e12eaa4 370 hapd.request("WPS_PIN any " + pin)
5f35a5e2 371 dev[1].wait_connected(timeout=30)
362ba6de 372
6257f9c0
JM
373def test_ap_wps_conf_pin_v1(dev, apdev):
374 """WPS PIN provisioning with configured WPS v1.0 AP"""
375 ssid = "test-wps-conf-pin-v1"
376 hostapd.add_ap(apdev[0]['ifname'],
377 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
378 "wpa_passphrase": "12345678", "wpa": "2",
379 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
380 hapd = hostapd.Hostapd(apdev[0]['ifname'])
381 logger.info("WPS provisioning step")
382 pin = dev[0].wps_read_pin()
383 hapd.request("SET wps_version_number 0x10")
384 hapd.request("WPS_PIN any " + pin)
385 found = False
386 for i in range(0, 10):
387 dev[0].scan(freq="2412")
388 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
389 found = True
390 break
391 if not found:
392 hapd.request("SET wps_version_number 0x20")
393 raise Exception("WPS-PIN flag not seen in scan results")
394 dev[0].dump_monitor()
33d0b157 395 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 396 dev[0].wait_connected(timeout=30)
6257f9c0 397 hapd.request("SET wps_version_number 0x20")
6257f9c0 398
e9129860
JM
399def test_ap_wps_conf_pin_2sta(dev, apdev):
400 """Two stations trying to use WPS PIN at the same time"""
401 ssid = "test-wps-conf-pin2"
402 hostapd.add_ap(apdev[0]['ifname'],
403 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
404 "wpa_passphrase": "12345678", "wpa": "2",
405 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
406 hapd = hostapd.Hostapd(apdev[0]['ifname'])
407 logger.info("WPS provisioning step")
408 pin = "12345670"
409 pin2 = "55554444"
410 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
411 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
e9129860 412 dev[0].dump_monitor()
e9129860 413 dev[1].dump_monitor()
33d0b157
JM
414 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
415 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
416 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
417 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2
JM
418 dev[0].wait_connected(timeout=30)
419 dev[1].wait_connected(timeout=30)
0489e880
JM
420
421def test_ap_wps_conf_pin_timeout(dev, apdev):
422 """WPS PIN provisioning with configured AP timing out PIN"""
423 ssid = "test-wps-conf-pin"
424 hostapd.add_ap(apdev[0]['ifname'],
425 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
426 "wpa_passphrase": "12345678", "wpa": "2",
427 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
428 hapd = hostapd.Hostapd(apdev[0]['ifname'])
429 addr = dev[0].p2p_interface_addr()
430 pin = dev[0].wps_read_pin()
431 if "FAIL" not in hapd.request("WPS_PIN "):
432 raise Exception("Unexpected success on invalid WPS_PIN")
433 hapd.request("WPS_PIN any " + pin + " 1")
33d0b157 434 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
0489e880 435 time.sleep(1.1)
33d0b157 436 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
0489e880
JM
437 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
438 if ev is None:
439 raise Exception("WPS-PIN-NEEDED event timed out")
440 ev = dev[0].wait_event(["WPS-M2D"])
441 if ev is None:
442 raise Exception("M2D not reported")
443 dev[0].request("WPS_CANCEL")
444
445 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
33d0b157 446 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 447 dev[0].wait_connected(timeout=30)
e9129860 448
ae3ad328 449def test_ap_wps_reg_connect(dev, apdev):
302b7a1b 450 """WPS registrar using AP PIN to connect"""
803edd1c 451 ssid = "test-wps-reg-ap-pin"
302b7a1b 452 appin = "12345670"
ae3ad328 453 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
454 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
455 "wpa_passphrase": "12345678", "wpa": "2",
456 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
457 "ap_pin": appin})
458 logger.info("WPS provisioning step")
302b7a1b 459 dev[0].dump_monitor()
33d0b157 460 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 461 dev[0].wps_reg(apdev[0]['bssid'], appin)
302b7a1b 462 status = dev[0].get_status()
ae3ad328 463 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
464 raise Exception("Not fully connected")
465 if status['ssid'] != ssid:
466 raise Exception("Unexpected SSID")
467 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
468 raise Exception("Unexpected encryption configuration")
469 if status['key_mgmt'] != 'WPA2-PSK':
470 raise Exception("Unexpected key_mgmt")
471
e60be3b3
JM
472def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
473 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
474 ssid = "test-wps-reg-ap-pin"
475 appin = "12345670"
476 hostapd.add_ap(apdev[0]['ifname'],
477 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
478 "wpa_passphrase": "12345678", "wpa": "3",
479 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
480 "wpa_pairwise": "TKIP", "ap_pin": appin})
481 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
482 dev[0].wps_reg(apdev[0]['bssid'], appin)
483 status = dev[0].get_status()
484 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
485 raise Exception("Not fully connected")
486 if status['ssid'] != ssid:
487 raise Exception("Unexpected SSID")
488 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
489 raise Exception("Unexpected encryption configuration")
490 if status['key_mgmt'] != 'WPA2-PSK':
491 raise Exception("Unexpected key_mgmt")
492
9488858f
JM
493def check_wps_reg_failure(dev, ap, appin):
494 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
495 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
496 if ev is None:
497 raise Exception("WPS operation timed out")
498 if "WPS-SUCCESS" in ev:
499 raise Exception("WPS operation succeeded unexpectedly")
500 if "config_error=15" not in ev:
501 raise Exception("WPS setup locked state was not reported correctly")
502
e4357b19
JM
503def test_ap_wps_random_ap_pin(dev, apdev):
504 """WPS registrar using random AP PIN"""
505 ssid = "test-wps-reg-random-ap-pin"
506 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
507 hostapd.add_ap(apdev[0]['ifname'],
508 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
509 "wpa_passphrase": "12345678", "wpa": "2",
510 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
511 "device_name": "Wireless AP", "manufacturer": "Company",
512 "model_name": "WAP", "model_number": "123",
513 "serial_number": "12345", "device_type": "6-0050F204-1",
514 "os_version": "01020300",
515 "config_methods": "label push_button",
516 "uuid": ap_uuid, "upnp_iface": "lo" })
517 hapd = hostapd.Hostapd(apdev[0]['ifname'])
518 appin = hapd.request("WPS_AP_PIN random")
519 if "FAIL" in appin:
520 raise Exception("Could not generate random AP PIN")
521 if appin not in hapd.request("WPS_AP_PIN get"):
522 raise Exception("Could not fetch current AP PIN")
523 logger.info("WPS provisioning step")
33d0b157 524 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
e4357b19
JM
525 dev[0].wps_reg(apdev[0]['bssid'], appin)
526
527 hapd.request("WPS_AP_PIN disable")
528 logger.info("WPS provisioning step with AP PIN disabled")
33d0b157 529 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9488858f
JM
530 check_wps_reg_failure(dev[1], apdev[0], appin)
531
532 logger.info("WPS provisioning step with AP PIN reset")
533 appin = "12345670"
534 hapd.request("WPS_AP_PIN set " + appin)
535 dev[1].wps_reg(apdev[0]['bssid'], appin)
536 dev[0].request("REMOVE_NETWORK all")
537 dev[1].request("REMOVE_NETWORK all")
5f35a5e2
JM
538 dev[0].wait_disconnected(timeout=10)
539 dev[1].wait_disconnected(timeout=10)
9488858f
JM
540
541 logger.info("WPS provisioning step after AP PIN timeout")
542 hapd.request("WPS_AP_PIN disable")
543 appin = hapd.request("WPS_AP_PIN random 1")
544 time.sleep(1.1)
545 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
546 raise Exception("AP PIN unexpectedly still enabled")
547 check_wps_reg_failure(dev[0], apdev[0], appin)
548
549 logger.info("WPS provisioning step after AP PIN timeout(2)")
550 hapd.request("WPS_AP_PIN disable")
551 appin = "12345670"
552 hapd.request("WPS_AP_PIN set " + appin + " 1")
553 time.sleep(1.1)
554 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
555 raise Exception("AP PIN unexpectedly still enabled")
556 check_wps_reg_failure(dev[1], apdev[0], appin)
e4357b19 557
ae3ad328 558def test_ap_wps_reg_config(dev, apdev):
4b727c5c 559 """WPS registrar configuring an AP using AP PIN"""
302b7a1b
JM
560 ssid = "test-wps-init-ap-pin"
561 appin = "12345670"
ae3ad328 562 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
563 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
564 "ap_pin": appin})
565 logger.info("WPS configuration step")
33d0b157 566 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
302b7a1b
JM
567 dev[0].dump_monitor()
568 new_ssid = "wps-new-ssid"
569 new_passphrase = "1234567890"
6edaee9c
JM
570 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
571 new_passphrase)
302b7a1b 572 status = dev[0].get_status()
ae3ad328 573 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
574 raise Exception("Not fully connected")
575 if status['ssid'] != new_ssid:
576 raise Exception("Unexpected SSID")
577 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
578 raise Exception("Unexpected encryption configuration")
579 if status['key_mgmt'] != 'WPA2-PSK':
580 raise Exception("Unexpected key_mgmt")
581
375afd7c
JM
582 logger.info("Re-configure back to open")
583 dev[0].request("REMOVE_NETWORK all")
243dcc4a 584 dev[0].flush_scan_cache()
375afd7c
JM
585 dev[0].dump_monitor()
586 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
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'] != "wps-open":
591 raise Exception("Unexpected SSID")
592 if status['key_mgmt'] != 'NONE':
593 raise Exception("Unexpected key_mgmt")
594
4b727c5c
JM
595def test_ap_wps_reg_config_ext_processing(dev, apdev):
596 """WPS registrar configuring an AP with external config processing"""
597 ssid = "test-wps-init-ap-pin"
598 appin = "12345670"
599 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
600 "wps_cred_processing": "1", "ap_pin": appin}
601 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
33d0b157 602 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4b727c5c
JM
603 new_ssid = "wps-new-ssid"
604 new_passphrase = "1234567890"
605 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
606 new_passphrase, no_wait=True)
607 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
608 if ev is None:
609 raise Exception("WPS registrar operation timed out")
610 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
611 if ev is None:
612 raise Exception("WPS configuration timed out")
613 if "1026" not in ev:
614 raise Exception("AP Settings missing from event")
615 hapd.request("SET wps_cred_processing 0")
616 if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
617 raise Exception("WPS_CONFIG command failed")
5f35a5e2 618 dev[0].wait_connected(timeout=15)
4b727c5c 619
eeefe187
JM
620def test_ap_wps_reg_config_tkip(dev, apdev):
621 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
a1eabc74 622 skip_with_fips(dev[0])
eeefe187
JM
623 ssid = "test-wps-init-ap"
624 appin = "12345670"
625 hostapd.add_ap(apdev[0]['ifname'],
626 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
627 "ap_pin": appin})
628 logger.info("WPS configuration step")
eeefe187 629 dev[0].request("SET wps_version_number 0x10")
33d0b157 630 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
eeefe187
JM
631 dev[0].dump_monitor()
632 new_ssid = "wps-new-ssid-with-tkip"
633 new_passphrase = "1234567890"
634 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
635 new_passphrase)
636 logger.info("Re-connect to verify WPA2 mixed mode")
637 dev[0].request("DISCONNECT")
638 id = 0
639 dev[0].set_network(id, "pairwise", "CCMP")
640 dev[0].set_network(id, "proto", "RSN")
641 dev[0].connect_network(id)
642 status = dev[0].get_status()
643 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
3c086180 644 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
eeefe187
JM
645 if status['ssid'] != new_ssid:
646 raise Exception("Unexpected SSID")
647 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
648 raise Exception("Unexpected encryption configuration")
649 if status['key_mgmt'] != 'WPA2-PSK':
650 raise Exception("Unexpected key_mgmt")
651
6645ff50
JM
652def test_ap_wps_setup_locked(dev, apdev):
653 """WPS registrar locking up AP setup on AP PIN failures"""
654 ssid = "test-wps-incorrect-ap-pin"
655 appin = "12345670"
656 hostapd.add_ap(apdev[0]['ifname'],
657 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
658 "wpa_passphrase": "12345678", "wpa": "2",
659 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
660 "ap_pin": appin})
6645ff50
JM
661 new_ssid = "wps-new-ssid-test"
662 new_passphrase = "1234567890"
663
33d0b157 664 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6645ff50
JM
665 ap_setup_locked=False
666 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
667 dev[0].dump_monitor()
668 logger.info("Try incorrect AP PIN - attempt " + pin)
669 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
670 "CCMP", new_passphrase, no_wait=True)
671 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
672 if ev is None:
673 raise Exception("Timeout on receiving WPS operation failure event")
674 if "CTRL-EVENT-CONNECTED" in ev:
675 raise Exception("Unexpected connection")
676 if "config_error=15" in ev:
677 logger.info("AP Setup Locked")
678 ap_setup_locked=True
679 elif "config_error=18" not in ev:
680 raise Exception("config_error=18 not reported")
5f35a5e2 681 dev[0].wait_disconnected(timeout=10)
6645ff50
JM
682 time.sleep(0.1)
683 if not ap_setup_locked:
684 raise Exception("AP setup was not locked")
685
d671a420
JM
686 hapd = hostapd.Hostapd(apdev[0]['ifname'])
687 status = hapd.request("WPS_GET_STATUS")
688 if "Last WPS result: Failed" not in status:
689 raise Exception("WPS failure result not shown correctly")
690 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
691 raise Exception("Peer address not shown correctly")
692
6645ff50
JM
693 time.sleep(0.5)
694 dev[0].dump_monitor()
695 logger.info("WPS provisioning step")
696 pin = dev[0].wps_read_pin()
697 hapd = hostapd.Hostapd(apdev[0]['ifname'])
698 hapd.request("WPS_PIN any " + pin)
33d0b157 699 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
6645ff50
JM
700 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
701 if ev is None:
702 raise Exception("WPS success was not reported")
5f35a5e2 703 dev[0].wait_connected(timeout=30)
6645ff50 704
c1cec68b
JM
705 appin = hapd.request("WPS_AP_PIN random")
706 if "FAIL" in appin:
707 raise Exception("Could not generate random AP PIN")
708 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
709 if ev is None:
710 raise Exception("Failed to unlock AP PIN")
711
33c9b8d8
JM
712def test_ap_wps_setup_locked_timeout(dev, apdev):
713 """WPS re-enabling AP PIN after timeout"""
714 ssid = "test-wps-incorrect-ap-pin"
715 appin = "12345670"
716 hostapd.add_ap(apdev[0]['ifname'],
717 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
718 "wpa_passphrase": "12345678", "wpa": "2",
719 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
720 "ap_pin": appin})
721 new_ssid = "wps-new-ssid-test"
722 new_passphrase = "1234567890"
723
33d0b157 724 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
33c9b8d8
JM
725 ap_setup_locked=False
726 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
727 dev[0].dump_monitor()
728 logger.info("Try incorrect AP PIN - attempt " + pin)
729 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
730 "CCMP", new_passphrase, no_wait=True)
9ed53f5e 731 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
33c9b8d8
JM
732 if ev is None:
733 raise Exception("Timeout on receiving WPS operation failure event")
734 if "CTRL-EVENT-CONNECTED" in ev:
735 raise Exception("Unexpected connection")
736 if "config_error=15" in ev:
737 logger.info("AP Setup Locked")
738 ap_setup_locked=True
739 break
740 elif "config_error=18" not in ev:
741 raise Exception("config_error=18 not reported")
5f35a5e2 742 dev[0].wait_disconnected(timeout=10)
33c9b8d8
JM
743 time.sleep(0.1)
744 if not ap_setup_locked:
745 raise Exception("AP setup was not locked")
746 hapd = hostapd.Hostapd(apdev[0]['ifname'])
747 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
748 if ev is None:
749 raise Exception("AP PIN did not get unlocked on 60 second timeout")
750
ae3ad328 751def test_ap_wps_pbc_overlap_2ap(dev, apdev):
302b7a1b 752 """WPS PBC session overlap with two active APs"""
ae3ad328 753 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
754 { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
755 "wpa_passphrase": "12345678", "wpa": "2",
756 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
757 "wps_independent": "1"})
ae3ad328 758 hostapd.add_ap(apdev[1]['ifname'],
302b7a1b
JM
759 { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
760 "wpa_passphrase": "123456789", "wpa": "2",
761 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
762 "wps_independent": "1"})
ae3ad328 763 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b 764 hapd.request("WPS_PBC")
ae3ad328 765 hapd2 = hostapd.Hostapd(apdev[1]['ifname'])
302b7a1b
JM
766 hapd2.request("WPS_PBC")
767 logger.info("WPS provisioning step")
84a40841
JM
768 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
769 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
302b7a1b
JM
770 dev[0].request("WPS_PBC")
771 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
772 if ev is None:
773 raise Exception("PBC session overlap not detected")
492c3a91
JM
774 hapd.request("DISABLE")
775 hapd2.request("DISABLE")
776 dev[0].flush_scan_cache()
302b7a1b 777
ae3ad328 778def test_ap_wps_pbc_overlap_2sta(dev, apdev):
302b7a1b
JM
779 """WPS PBC session overlap with two active STAs"""
780 ssid = "test-wps-pbc-overlap"
ae3ad328 781 hostapd.add_ap(apdev[0]['ifname'],
302b7a1b
JM
782 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
783 "wpa_passphrase": "12345678", "wpa": "2",
784 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
ae3ad328 785 hapd = hostapd.Hostapd(apdev[0]['ifname'])
302b7a1b
JM
786 logger.info("WPS provisioning step")
787 hapd.request("WPS_PBC")
33d0b157 788 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 789 dev[0].dump_monitor()
33d0b157 790 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 791 dev[1].dump_monitor()
33d0b157
JM
792 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
793 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
302b7a1b
JM
794 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
795 if ev is None:
796 raise Exception("PBC session overlap not detected (dev0)")
797 if "config_error=12" not in ev:
798 raise Exception("PBC session overlap not correctly reported (dev0)")
492c3a91
JM
799 dev[0].request("WPS_CANCEL")
800 dev[0].request("DISCONNECT")
302b7a1b
JM
801 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
802 if ev is None:
803 raise Exception("PBC session overlap not detected (dev1)")
804 if "config_error=12" not in ev:
805 raise Exception("PBC session overlap not correctly reported (dev1)")
492c3a91
JM
806 dev[1].request("WPS_CANCEL")
807 dev[1].request("DISCONNECT")
11e7eeba
JM
808 hapd.request("WPS_CANCEL")
809 ret = hapd.request("WPS_PBC")
810 if "FAIL" not in ret:
811 raise Exception("PBC mode allowed to be started while PBC overlap still active")
492c3a91
JM
812 hapd.request("DISABLE")
813 dev[0].flush_scan_cache()
814 dev[1].flush_scan_cache()
6edaee9c 815
71afe834
JM
816def test_ap_wps_cancel(dev, apdev):
817 """WPS AP cancelling enabled config method"""
818 ssid = "test-wps-ap-cancel"
819 hostapd.add_ap(apdev[0]['ifname'],
820 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
821 "wpa_passphrase": "12345678", "wpa": "2",
822 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
823 bssid = apdev[0]['bssid']
824 hapd = hostapd.Hostapd(apdev[0]['ifname'])
825
826 logger.info("Verify PBC enable/cancel")
827 hapd.request("WPS_PBC")
71afe834 828 dev[0].scan(freq="2412")
84a40841 829 dev[0].scan(freq="2412")
71afe834
JM
830 bss = dev[0].get_bss(apdev[0]['bssid'])
831 if "[WPS-PBC]" not in bss['flags']:
832 raise Exception("WPS-PBC flag missing")
833 if "FAIL" in hapd.request("WPS_CANCEL"):
834 raise Exception("WPS_CANCEL failed")
835 dev[0].scan(freq="2412")
84a40841 836 dev[0].scan(freq="2412")
71afe834
JM
837 bss = dev[0].get_bss(apdev[0]['bssid'])
838 if "[WPS-PBC]" in bss['flags']:
839 raise Exception("WPS-PBC flag not cleared")
840
841 logger.info("Verify PIN enable/cancel")
842 hapd.request("WPS_PIN any 12345670")
843 dev[0].scan(freq="2412")
84a40841 844 dev[0].scan(freq="2412")
71afe834
JM
845 bss = dev[0].get_bss(apdev[0]['bssid'])
846 if "[WPS-AUTH]" not in bss['flags']:
847 raise Exception("WPS-AUTH flag missing")
848 if "FAIL" in hapd.request("WPS_CANCEL"):
849 raise Exception("WPS_CANCEL failed")
850 dev[0].scan(freq="2412")
84a40841 851 dev[0].scan(freq="2412")
71afe834
JM
852 bss = dev[0].get_bss(apdev[0]['bssid'])
853 if "[WPS-AUTH]" in bss['flags']:
854 raise Exception("WPS-AUTH flag not cleared")
855
6edaee9c
JM
856def test_ap_wps_er_add_enrollee(dev, apdev):
857 """WPS ER configuring AP and adding a new enrollee using PIN"""
be9f1562
JM
858 try:
859 _test_ap_wps_er_add_enrollee(dev, apdev)
860 finally:
861 dev[0].request("WPS_ER_STOP")
862
863def _test_ap_wps_er_add_enrollee(dev, apdev):
6edaee9c
JM
864 ssid = "wps-er-add-enrollee"
865 ap_pin = "12345670"
866 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
867 hostapd.add_ap(apdev[0]['ifname'],
868 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
869 "device_name": "Wireless AP", "manufacturer": "Company",
870 "model_name": "WAP", "model_number": "123",
871 "serial_number": "12345", "device_type": "6-0050F204-1",
872 "os_version": "01020300",
873 "config_methods": "label push_button",
874 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
875 logger.info("WPS configuration step")
876 new_passphrase = "1234567890"
877 dev[0].dump_monitor()
33d0b157 878 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c
JM
879 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
880 new_passphrase)
881 status = dev[0].get_status()
882 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
883 raise Exception("Not fully connected")
884 if status['ssid'] != ssid:
885 raise Exception("Unexpected SSID")
886 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
887 raise Exception("Unexpected encryption configuration")
888 if status['key_mgmt'] != 'WPA2-PSK':
889 raise Exception("Unexpected key_mgmt")
890
891 logger.info("Start ER")
892 dev[0].request("WPS_ER_START ifname=lo")
893 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
894 if ev is None:
895 raise Exception("AP discovery timed out")
896 if ap_uuid not in ev:
897 raise Exception("Expected AP UUID not found")
898
899 logger.info("Learn AP configuration through UPnP")
900 dev[0].dump_monitor()
901 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
902 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
903 if ev is None:
904 raise Exception("AP learn timed out")
905 if ap_uuid not in ev:
906 raise Exception("Expected AP UUID not in settings")
907 if "ssid=" + ssid not in ev:
908 raise Exception("Expected SSID not in settings")
909 if "key=" + new_passphrase not in ev:
910 raise Exception("Expected passphrase not in settings")
33d0b157
JM
911 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
912 if ev is None:
913 raise Exception("WPS-FAIL after AP learn timed out")
914 time.sleep(0.1)
6edaee9c
JM
915
916 logger.info("Add Enrollee using ER")
917 pin = dev[1].wps_read_pin()
918 dev[0].dump_monitor()
919 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
33d0b157 920 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 921 dev[1].dump_monitor()
33d0b157 922 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
846be889 923 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
6edaee9c
JM
924 if ev is None:
925 raise Exception("Enrollee did not report success")
5f35a5e2 926 dev[1].wait_connected(timeout=15)
6edaee9c
JM
927 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
928 if ev is None:
929 raise Exception("WPS ER did not report success")
930 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
931
11c26f1b
JM
932 logger.info("Add a specific Enrollee using ER")
933 pin = dev[2].wps_read_pin()
934 addr2 = dev[2].p2p_interface_addr()
935 dev[0].dump_monitor()
33d0b157 936 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
11c26f1b 937 dev[2].dump_monitor()
33d0b157 938 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
11c26f1b
JM
939 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
940 if ev is None:
941 raise Exception("Enrollee not seen")
942 if addr2 not in ev:
943 raise Exception("Unexpected Enrollee MAC address")
944 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
5f35a5e2 945 dev[2].wait_connected(timeout=30)
11c26f1b
JM
946 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
947 if ev is None:
948 raise Exception("WPS ER did not report success")
949
38ae43de
JM
950 logger.info("Verify registrar selection behavior")
951 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
952 dev[1].request("DISCONNECT")
5f35a5e2 953 dev[1].wait_disconnected(timeout=10)
84a40841 954 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
38ae43de
JM
955 dev[1].scan(freq="2412")
956 bss = dev[1].get_bss(apdev[0]['bssid'])
957 if "[WPS-AUTH]" not in bss['flags']:
321c7f60
JM
958 # It is possible for scan to miss an update especially when running
959 # tests under load with multiple VMs, so allow another attempt.
960 dev[1].scan(freq="2412")
961 bss = dev[1].get_bss(apdev[0]['bssid'])
962 if "[WPS-AUTH]" not in bss['flags']:
963 raise Exception("WPS-AUTH flag missing")
38ae43de
JM
964
965 logger.info("Stop ER")
966 dev[0].dump_monitor()
967 dev[0].request("WPS_ER_STOP")
968 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
969 if ev is None:
970 raise Exception("WPS ER unsubscription timed out")
8697cbc0 971 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
befd671c 972 # a bit before verifying that the scan results have changed.
8697cbc0 973 time.sleep(0.2)
38ae43de 974
befd671c
JM
975 for i in range(0, 10):
976 dev[1].request("BSS_FLUSH 0")
977 dev[1].scan(freq="2412", only_new=True)
978 bss = dev[1].get_bss(apdev[0]['bssid'])
979 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
980 break
981 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
982 time.sleep(0.1)
38ae43de
JM
983 if "[WPS-AUTH]" in bss['flags']:
984 raise Exception("WPS-AUTH flag not removed")
985
c965ae03
JM
986def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
987 """WPS ER adding a new enrollee identified by UUID"""
988 try:
989 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
990 finally:
991 dev[0].request("WPS_ER_STOP")
992
993def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
994 ssid = "wps-er-add-enrollee"
995 ap_pin = "12345670"
996 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
997 hostapd.add_ap(apdev[0]['ifname'],
998 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
999 "wpa_passphrase": "12345678", "wpa": "2",
1000 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1001 "device_name": "Wireless AP", "manufacturer": "Company",
1002 "model_name": "WAP", "model_number": "123",
1003 "serial_number": "12345", "device_type": "6-0050F204-1",
1004 "os_version": "01020300",
1005 "config_methods": "label push_button",
1006 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1007 logger.info("WPS configuration step")
1008 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1009 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1010
1011 logger.info("Start ER")
1012 dev[0].request("WPS_ER_START ifname=lo")
1013 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1014 if ev is None:
1015 raise Exception("AP discovery timed out")
1016 if ap_uuid not in ev:
1017 raise Exception("Expected AP UUID not found")
1018
1019 logger.info("Learn AP configuration through UPnP")
1020 dev[0].dump_monitor()
1021 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1022 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1023 if ev is None:
1024 raise Exception("AP learn timed out")
1025 if ap_uuid not in ev:
1026 raise Exception("Expected AP UUID not in settings")
1027 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1028 if ev is None:
1029 raise Exception("WPS-FAIL after AP learn timed out")
1030 time.sleep(0.1)
1031
1032 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1033 addr1 = dev[1].p2p_interface_addr()
1034 dev[0].dump_monitor()
1035 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1036 dev[1].dump_monitor()
1037 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1038 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1039 if ev is None:
1040 raise Exception("Enrollee not seen")
1041 if addr1 not in ev:
1042 raise Exception("Unexpected Enrollee MAC address")
1043 uuid = ev.split(' ')[1]
1044 dev[0].request("WPS_ER_PBC " + uuid)
1045 dev[1].wait_connected(timeout=30)
1046 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1047 if ev is None:
1048 raise Exception("WPS ER did not report success")
1049
1050 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1051 pin = dev[2].wps_read_pin()
1052 addr2 = dev[2].p2p_interface_addr()
1053 dev[0].dump_monitor()
1054 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1055 dev[2].dump_monitor()
1056 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1057 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1058 if ev is None:
1059 raise Exception("Enrollee not seen")
1060 if addr2 not in ev:
1061 raise Exception("Unexpected Enrollee MAC address")
1062 uuid = ev.split(' ')[1]
1063 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1064 dev[2].wait_connected(timeout=30)
1065 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1066 if ev is None:
1067 raise Exception("WPS ER did not report success")
1068
1069 logger.info("Stop ER")
1070 dev[0].dump_monitor()
1071 dev[0].request("WPS_ER_STOP")
1072
6edaee9c
JM
1073def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1074 """WPS ER connected to AP and adding a new enrollee using PBC"""
be9f1562
JM
1075 try:
1076 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1077 finally:
1078 dev[0].request("WPS_ER_STOP")
1079
1080def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
6edaee9c
JM
1081 ssid = "wps-er-add-enrollee-pbc"
1082 ap_pin = "12345670"
1083 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1084 hostapd.add_ap(apdev[0]['ifname'],
1085 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1086 "wpa_passphrase": "12345678", "wpa": "2",
1087 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1088 "device_name": "Wireless AP", "manufacturer": "Company",
1089 "model_name": "WAP", "model_number": "123",
1090 "serial_number": "12345", "device_type": "6-0050F204-1",
1091 "os_version": "01020300",
1092 "config_methods": "label push_button",
1093 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1094 logger.info("Learn AP configuration")
33d0b157 1095 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1096 dev[0].dump_monitor()
6edaee9c
JM
1097 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1098 status = dev[0].get_status()
1099 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1100 raise Exception("Not fully connected")
1101
1102 logger.info("Start ER")
1103 dev[0].request("WPS_ER_START ifname=lo")
1104 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1105 if ev is None:
1106 raise Exception("AP discovery timed out")
1107 if ap_uuid not in ev:
1108 raise Exception("Expected AP UUID not found")
1109
d6b916c9
JM
1110 enrollee = dev[1].p2p_interface_addr()
1111
1112 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1113 raise Exception("Unknown UUID not reported")
6edaee9c
JM
1114
1115 logger.info("Add Enrollee using ER and PBC")
1116 dev[0].dump_monitor()
6edaee9c
JM
1117 dev[1].dump_monitor()
1118 dev[1].request("WPS_PBC")
1119
8674c022
JM
1120 for i in range(0, 2):
1121 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1122 if ev is None:
1123 raise Exception("Enrollee discovery timed out")
1124 if enrollee in ev:
1125 break
1126 if i == 1:
1127 raise Exception("Expected Enrollee not found")
d6b916c9
JM
1128 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1129 raise Exception("Unknown UUID not reported")
1130 logger.info("Use learned network configuration on ER")
1131 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1132 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1133 raise Exception("WPS_ER_PBC failed")
6edaee9c
JM
1134
1135 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1136 if ev is None:
1137 raise Exception("Enrollee did not report success")
5f35a5e2 1138 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1139 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1140 if ev is None:
1141 raise Exception("WPS ER did not report success")
1142 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
bff3ac5b 1143
d6b916c9
JM
1144def test_ap_wps_er_pbc_overlap(dev, apdev):
1145 """WPS ER connected to AP and PBC session overlap"""
be9f1562
JM
1146 try:
1147 _test_ap_wps_er_pbc_overlap(dev, apdev)
1148 finally:
1149 dev[0].request("WPS_ER_STOP")
1150
1151def _test_ap_wps_er_pbc_overlap(dev, apdev):
d6b916c9
JM
1152 ssid = "wps-er-add-enrollee-pbc"
1153 ap_pin = "12345670"
1154 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1155 hostapd.add_ap(apdev[0]['ifname'],
1156 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1157 "wpa_passphrase": "12345678", "wpa": "2",
1158 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1159 "device_name": "Wireless AP", "manufacturer": "Company",
1160 "model_name": "WAP", "model_number": "123",
1161 "serial_number": "12345", "device_type": "6-0050F204-1",
1162 "os_version": "01020300",
1163 "config_methods": "label push_button",
1164 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1165 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1166 dev[0].dump_monitor()
1167 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1168
fba25c99
JM
1169 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1170 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1171 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1172 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1173
d6b916c9
JM
1174 dev[0].dump_monitor()
1175 dev[0].request("WPS_ER_START ifname=lo")
1176
1177 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1178 if ev is None:
1179 raise Exception("AP discovery timed out")
1180 if ap_uuid not in ev:
1181 raise Exception("Expected AP UUID not found")
1182
800bcf4e
JM
1183 # verify BSSID selection of the AP instead of UUID
1184 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1185 raise Exception("Could not select AP based on BSSID")
1186
fba25c99 1187 dev[0].dump_monitor()
d6b916c9
JM
1188 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1189 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1190 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1191 if ev is None:
1192 raise Exception("PBC scan failed")
1193 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1194 if ev is None:
1195 raise Exception("PBC scan failed")
fba25c99
JM
1196 found1 = False
1197 found2 = False
1198 addr1 = dev[1].own_addr()
1199 addr2 = dev[2].own_addr()
1200 for i in range(3):
d6b916c9
JM
1201 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1202 if ev is None:
1203 raise Exception("Enrollee discovery timed out")
fba25c99
JM
1204 if addr1 in ev:
1205 found1 = True
1206 if found2:
1207 break
1208 if addr2 in ev:
1209 found2 = True
1210 if found1:
1211 break
d6b916c9
JM
1212 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1213 raise Exception("PBC overlap not reported")
1214 dev[1].request("WPS_CANCEL")
1215 dev[2].request("WPS_CANCEL")
1216 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1217 raise Exception("Invalid WPS_ER_PBC accepted")
1218
1f020f5e
JM
1219def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1220 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
be9f1562
JM
1221 try:
1222 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1223 finally:
1224 dev[0].request("WPS_ER_STOP")
1225
1226def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1f020f5e
JM
1227 ssid = "wps-er-add-enrollee-pbc"
1228 ap_pin = "12345670"
1229 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1230 hostapd.add_ap(apdev[0]['ifname'],
1231 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1232 "wpa_passphrase": "12345678", "wpa": "2",
1233 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1234 "device_name": "Wireless AP", "manufacturer": "Company",
1235 "model_name": "WAP", "model_number": "123",
1236 "serial_number": "12345", "device_type": "6-0050F204-1",
1237 "os_version": "01020300",
1238 "config_methods": "label push_button",
1239 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1240 logger.info("Learn AP configuration")
1241 dev[0].request("SET wps_version_number 0x10")
33d0b157 1242 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e
JM
1243 dev[0].dump_monitor()
1244 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1245 status = dev[0].get_status()
1246 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1247 raise Exception("Not fully connected")
1248
1249 logger.info("Start ER")
1250 dev[0].request("WPS_ER_START ifname=lo")
1251 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1252 if ev is None:
1253 raise Exception("AP discovery timed out")
1254 if ap_uuid not in ev:
1255 raise Exception("Expected AP UUID not found")
1256
1257 logger.info("Use learned network configuration on ER")
1258 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1259
1260 logger.info("Add Enrollee using ER and PIN")
1261 enrollee = dev[1].p2p_interface_addr()
1262 pin = dev[1].wps_read_pin()
1263 dev[0].dump_monitor()
1264 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
33d0b157 1265 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e 1266 dev[1].dump_monitor()
33d0b157 1267 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1268 dev[1].wait_connected(timeout=30)
1f020f5e
JM
1269 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1270 if ev is None:
1271 raise Exception("WPS ER did not report success")
1272
be923570
JM
1273def test_ap_wps_er_config_ap(dev, apdev):
1274 """WPS ER configuring AP over UPnP"""
be9f1562
JM
1275 try:
1276 _test_ap_wps_er_config_ap(dev, apdev)
1277 finally:
1278 dev[0].request("WPS_ER_STOP")
1279
1280def _test_ap_wps_er_config_ap(dev, apdev):
be923570
JM
1281 ssid = "wps-er-ap-config"
1282 ap_pin = "12345670"
1283 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1284 hostapd.add_ap(apdev[0]['ifname'],
1285 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1286 "wpa_passphrase": "12345678", "wpa": "2",
1287 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1288 "device_name": "Wireless AP", "manufacturer": "Company",
1289 "model_name": "WAP", "model_number": "123",
1290 "serial_number": "12345", "device_type": "6-0050F204-1",
1291 "os_version": "01020300",
1292 "config_methods": "label push_button",
1293 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1294
1295 logger.info("Connect ER to the AP")
1296 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1297
1298 logger.info("WPS configuration step")
1299 dev[0].request("WPS_ER_START ifname=lo")
1300 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1301 if ev is None:
1302 raise Exception("AP discovery timed out")
1303 if ap_uuid not in ev:
1304 raise Exception("Expected AP UUID not found")
1305 new_passphrase = "1234567890"
1306 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1307 ssid.encode("hex") + " WPA2PSK CCMP " +
1308 new_passphrase.encode("hex"))
1309 ev = dev[0].wait_event(["WPS-SUCCESS"])
1310 if ev is None:
1311 raise Exception("WPS ER configuration operation timed out")
5f35a5e2 1312 dev[0].wait_disconnected(timeout=10)
be923570
JM
1313 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1314
8f8c2fe8
JM
1315 logger.info("WPS ER restart")
1316 dev[0].request("WPS_ER_START")
1317 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1318 if ev is None:
1319 raise Exception("AP discovery timed out on ER restart")
1320 if ap_uuid not in ev:
1321 raise Exception("Expected AP UUID not found on ER restart")
1322 if "OK" not in dev[0].request("WPS_ER_STOP"):
1323 raise Exception("WPS_ER_STOP failed")
1324 if "OK" not in dev[0].request("WPS_ER_STOP"):
1325 raise Exception("WPS_ER_STOP failed")
1326
bff3ac5b
JM
1327def test_ap_wps_fragmentation(dev, apdev):
1328 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1329 ssid = "test-wps-fragmentation"
9602b355 1330 appin = "12345670"
bff3ac5b
JM
1331 hostapd.add_ap(apdev[0]['ifname'],
1332 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1333 "wpa_passphrase": "12345678", "wpa": "3",
1334 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9602b355 1335 "wpa_pairwise": "TKIP", "ap_pin": appin,
bff3ac5b
JM
1336 "fragment_size": "50" })
1337 hapd = hostapd.Hostapd(apdev[0]['ifname'])
9602b355 1338 logger.info("WPS provisioning step (PBC)")
bff3ac5b 1339 hapd.request("WPS_PBC")
33d0b157 1340 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
bff3ac5b
JM
1341 dev[0].dump_monitor()
1342 dev[0].request("SET wps_fragment_size 50")
33d0b157 1343 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1344 dev[0].wait_connected(timeout=30)
bff3ac5b
JM
1345 status = dev[0].get_status()
1346 if status['wpa_state'] != 'COMPLETED':
9602b355
JM
1347 raise Exception("Not fully connected")
1348 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1349 raise Exception("Unexpected encryption configuration")
1350 if status['key_mgmt'] != 'WPA2-PSK':
1351 raise Exception("Unexpected key_mgmt")
1352
1353 logger.info("WPS provisioning step (PIN)")
1354 pin = dev[1].wps_read_pin()
1355 hapd.request("WPS_PIN any " + pin)
33d0b157 1356 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355 1357 dev[1].request("SET wps_fragment_size 50")
33d0b157 1358 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1359 dev[1].wait_connected(timeout=30)
9602b355
JM
1360 status = dev[1].get_status()
1361 if status['wpa_state'] != 'COMPLETED':
1362 raise Exception("Not fully connected")
1363 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1364 raise Exception("Unexpected encryption configuration")
1365 if status['key_mgmt'] != 'WPA2-PSK':
1366 raise Exception("Unexpected key_mgmt")
1367
1368 logger.info("WPS connection as registrar")
33d0b157 1369 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355
JM
1370 dev[2].request("SET wps_fragment_size 50")
1371 dev[2].wps_reg(apdev[0]['bssid'], appin)
1372 status = dev[2].get_status()
1373 if status['wpa_state'] != 'COMPLETED':
bff3ac5b
JM
1374 raise Exception("Not fully connected")
1375 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1376 raise Exception("Unexpected encryption configuration")
1377 if status['key_mgmt'] != 'WPA2-PSK':
1378 raise Exception("Unexpected key_mgmt")
10ea6848
JM
1379
1380def test_ap_wps_new_version_sta(dev, apdev):
1381 """WPS compatibility with new version number on the station"""
1382 ssid = "test-wps-ver"
1383 hostapd.add_ap(apdev[0]['ifname'],
1384 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1385 "wpa_passphrase": "12345678", "wpa": "2",
1386 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1387 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1388 logger.info("WPS provisioning step")
1389 hapd.request("WPS_PBC")
33d0b157 1390 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848
JM
1391 dev[0].dump_monitor()
1392 dev[0].request("SET wps_version_number 0x43")
dccafedb 1393 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
33d0b157 1394 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1395 dev[0].wait_connected(timeout=30)
10ea6848
JM
1396
1397def test_ap_wps_new_version_ap(dev, apdev):
1398 """WPS compatibility with new version number on the AP"""
1399 ssid = "test-wps-ver"
1400 hostapd.add_ap(apdev[0]['ifname'],
1401 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1402 "wpa_passphrase": "12345678", "wpa": "2",
1403 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1404 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1405 logger.info("WPS provisioning step")
1406 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1407 raise Exception("Failed to enable test functionality")
1408 hapd.request("WPS_PBC")
33d0b157 1409 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848 1410 dev[0].dump_monitor()
33d0b157 1411 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1412 dev[0].wait_connected(timeout=30)
10ea6848 1413 hapd.request("SET wps_version_number 0x20")
3bdf7d7f
JM
1414
1415def test_ap_wps_check_pin(dev, apdev):
1416 """Verify PIN checking through control interface"""
1417 hostapd.add_ap(apdev[0]['ifname'],
1418 { "ssid": "wps", "eap_server": "1", "wps_state": "2",
1419 "wpa_passphrase": "12345678", "wpa": "2",
1420 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1421 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1422 for t in [ ("12345670", "12345670"),
1423 ("12345678", "FAIL-CHECKSUM"),
df58939c 1424 ("12345", "FAIL"),
6e12eaa4 1425 ("123456789", "FAIL"),
3bdf7d7f
JM
1426 ("1234-5670", "12345670"),
1427 ("1234 5670", "12345670"),
1428 ("1-2.3:4 5670", "12345670") ]:
1429 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1430 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
1431 if res != res2:
1432 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
1433 if res != t[1]:
1434 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
9ba1fcb0 1435
ac786d67
JM
1436 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
1437 raise Exception("Unexpected WPS_CHECK_PIN success")
1438 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
1439 raise Exception("Unexpected WPS_CHECK_PIN success")
1440
acd9b45a
JM
1441 for i in range(0, 10):
1442 pin = dev[0].request("WPS_PIN get")
1443 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
1444 if pin != rpin:
1445 raise Exception("Random PIN validation failed for " + pin)
1446
9ba1fcb0
JM
1447def test_ap_wps_wep_config(dev, apdev):
1448 """WPS 2.0 AP rejecting WEP configuration"""
1449 ssid = "test-wps-config"
1450 appin = "12345670"
1451 hostapd.add_ap(apdev[0]['ifname'],
1452 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1453 "ap_pin": appin})
1454 hapd = hostapd.Hostapd(apdev[0]['ifname'])
33d0b157 1455 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
9ba1fcb0
JM
1456 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
1457 "hello", no_wait=True)
1458 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
1459 if ev is None:
1460 raise Exception("WPS-FAIL timed out")
1461 if "reason=2" not in ev:
1462 raise Exception("Unexpected reason code in WPS-FAIL")
1463 status = hapd.request("WPS_GET_STATUS")
1464 if "Last WPS result: Failed" not in status:
1465 raise Exception("WPS failure result not shown correctly")
1466 if "Failure Reason: WEP Prohibited" not in status:
1467 raise Exception("Failure reason not reported correctly")
1468 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
1469 raise Exception("Peer address not shown correctly")
1013a576 1470
11d78bb1
JM
1471def test_ap_wps_wep_enroll(dev, apdev):
1472 """WPS 2.0 STA rejecting WEP configuration"""
1473 ssid = "test-wps-wep"
1474 hostapd.add_ap(apdev[0]['ifname'],
1475 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1476 "skip_cred_build": "1", "extra_cred": "wps-wep-cred" })
1477 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1478 hapd.request("WPS_PBC")
33d0b157
JM
1479 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1480 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
11d78bb1
JM
1481 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1482 if ev is None:
1483 raise Exception("WPS-FAIL event timed out")
1484 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
1485 raise Exception("Unexpected WPS-FAIL event: " + ev)
1486
1013a576
JM
1487def test_ap_wps_ie_fragmentation(dev, apdev):
1488 """WPS AP using fragmented WPS IE"""
1489 ssid = "test-wps-ie-fragmentation"
1490 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1491 "wpa_passphrase": "12345678", "wpa": "2",
1492 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1493 "device_name": "1234567890abcdef1234567890abcdef",
1494 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
1495 "model_name": "1234567890abcdef1234567890abcdef",
1496 "model_number": "1234567890abcdef1234567890abcdef",
1497 "serial_number": "1234567890abcdef1234567890abcdef" }
1498 hostapd.add_ap(apdev[0]['ifname'], params)
1499 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1500 hapd.request("WPS_PBC")
33d0b157
JM
1501 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1502 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1503 dev[0].wait_connected(timeout=30)
1013a576
JM
1504 bss = dev[0].get_bss(apdev[0]['bssid'])
1505 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8 1506 logger.info("Device Name not received correctly")
d7a68ad6 1507 logger.info(bss)
cf3f0ec8
JM
1508 # This can fail if Probe Response frame is missed and Beacon frame was
1509 # used to fill in the BSS entry. This can happen, e.g., during heavy
1510 # load every now and then and is not really an error, so try to
1511 # workaround by runnign another scan.
1512 dev[0].scan(freq="2412", only_new=True)
1513 bss = dev[0].get_bss(apdev[0]['bssid'])
84a40841 1514 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8
JM
1515 logger.info(bss)
1516 raise Exception("Device Name not received correctly")
1013a576
JM
1517 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
1518 raise Exception("Unexpected number of WPS IEs")
44ff0400 1519
2035b170
JM
1520def get_psk(pskfile):
1521 psks = {}
1522 with open(pskfile, "r") as f:
1523 lines = f.read().splitlines()
1524 for l in lines:
1525 if l == "# WPA PSKs":
1526 continue
1527 (addr,psk) = l.split(' ')
1528 psks[addr] = psk
1529 return psks
1530
1531def test_ap_wps_per_station_psk(dev, apdev):
1532 """WPS PBC provisioning with per-station PSK"""
1d21a5be
B
1533 addr0 = dev[0].own_addr()
1534 addr1 = dev[1].own_addr()
1535 addr2 = dev[2].own_addr()
2035b170
JM
1536 ssid = "wps"
1537 appin = "12345670"
1538 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1539 try:
1540 os.remove(pskfile)
1541 except:
1542 pass
1543
1544 try:
1545 with open(pskfile, "w") as f:
1546 f.write("# WPA PSKs\n")
1547
1548 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1549 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1550 "rsn_pairwise": "CCMP", "ap_pin": appin,
1551 "wpa_psk_file": pskfile }
1552 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1553
1554 logger.info("First enrollee")
1555 hapd.request("WPS_PBC")
33d0b157
JM
1556 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1557 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1558 dev[0].wait_connected(timeout=30)
2035b170
JM
1559
1560 logger.info("Second enrollee")
1561 hapd.request("WPS_PBC")
33d0b157
JM
1562 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1563 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1564 dev[1].wait_connected(timeout=30)
2035b170
JM
1565
1566 logger.info("External registrar")
33d0b157 1567 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
1568 dev[2].wps_reg(apdev[0]['bssid'], appin)
1569
1570 logger.info("Verifying PSK results")
1571 psks = get_psk(pskfile)
1572 if addr0 not in psks:
1573 raise Exception("No PSK recorded for sta0")
1574 if addr1 not in psks:
1575 raise Exception("No PSK recorded for sta1")
1576 if addr2 not in psks:
1577 raise Exception("No PSK recorded for sta2")
1578 if psks[addr0] == psks[addr1]:
1579 raise Exception("Same PSK recorded for sta0 and sta1")
1580 if psks[addr0] == psks[addr2]:
1581 raise Exception("Same PSK recorded for sta0 and sta2")
1582 if psks[addr1] == psks[addr2]:
1583 raise Exception("Same PSK recorded for sta1 and sta2")
1584
1585 dev[0].request("REMOVE_NETWORK all")
1586 logger.info("Second external registrar")
33d0b157 1587 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
1588 dev[0].wps_reg(apdev[0]['bssid'], appin)
1589 psks2 = get_psk(pskfile)
1590 if addr0 not in psks2:
1591 raise Exception("No PSK recorded for sta0(reg)")
1592 if psks[addr0] == psks2[addr0]:
1593 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
1594 finally:
1595 os.remove(pskfile)
1596
373cce55
JM
1597def test_ap_wps_per_station_psk_failure(dev, apdev):
1598 """WPS PBC provisioning with per-station PSK (file not writable)"""
1599 addr0 = dev[0].p2p_dev_addr()
1600 addr1 = dev[1].p2p_dev_addr()
1601 addr2 = dev[2].p2p_dev_addr()
1602 ssid = "wps"
1603 appin = "12345670"
1604 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
1605 try:
1606 os.remove(pskfile)
1607 except:
1608 pass
1609
1610 try:
1611 with open(pskfile, "w") as f:
1612 f.write("# WPA PSKs\n")
1613
1614 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1615 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
1616 "rsn_pairwise": "CCMP", "ap_pin": appin,
1617 "wpa_psk_file": pskfile }
1618 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
1619 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
1620 raise Exception("Failed to set wpa_psk_file")
1621
1622 logger.info("First enrollee")
1623 hapd.request("WPS_PBC")
33d0b157
JM
1624 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1625 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1626 dev[0].wait_connected(timeout=30)
373cce55
JM
1627
1628 logger.info("Second enrollee")
1629 hapd.request("WPS_PBC")
33d0b157
JM
1630 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1631 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1632 dev[1].wait_connected(timeout=30)
373cce55
JM
1633
1634 logger.info("External registrar")
33d0b157 1635 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
373cce55
JM
1636 dev[2].wps_reg(apdev[0]['bssid'], appin)
1637
1638 logger.info("Verifying PSK results")
1639 psks = get_psk(pskfile)
1640 if len(psks) > 0:
1641 raise Exception("PSK recorded unexpectedly")
1642 finally:
1643 os.remove(pskfile)
1644
e8518757
JM
1645def test_ap_wps_pin_request_file(dev, apdev):
1646 """WPS PIN provisioning with configured AP"""
1647 ssid = "wps"
1648 pinfile = "/tmp/ap_wps_pin_request_file.log"
1649 if os.path.exists(pinfile):
b638f703 1650 os.remove(pinfile)
e8518757
JM
1651 hostapd.add_ap(apdev[0]['ifname'],
1652 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1653 "wps_pin_requests": pinfile,
1654 "wpa_passphrase": "12345678", "wpa": "2",
1655 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1656 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1657 uuid = dev[0].get_status_field("uuid")
1658 pin = dev[0].wps_read_pin()
1659 try:
33d0b157
JM
1660 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1661 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
e8518757
JM
1662 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
1663 if ev is None:
1664 raise Exception("PIN needed event not shown")
1665 if uuid not in ev:
1666 raise Exception("UUID mismatch")
1667 dev[0].request("WPS_CANCEL")
1668 success = False
1669 with open(pinfile, "r") as f:
1670 lines = f.readlines()
1671 for l in lines:
1672 if uuid in l:
1673 success = True
1674 break
1675 if not success:
1676 raise Exception("PIN request entry not in the log file")
1677 finally:
b638f703
JM
1678 try:
1679 os.remove(pinfile)
1680 except:
1681 pass
e8518757 1682
56887c35
JM
1683def test_ap_wps_auto_setup_with_config_file(dev, apdev):
1684 """WPS auto-setup with configuration file"""
1685 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
1686 ifname = apdev[0]['ifname']
1687 try:
1688 with open(conffile, "w") as f:
1689 f.write("driver=nl80211\n")
1690 f.write("hw_mode=g\n")
1691 f.write("channel=1\n")
1692 f.write("ieee80211n=1\n")
1693 f.write("interface=%s\n" % ifname)
1694 f.write("ctrl_interface=/var/run/hostapd\n")
1695 f.write("ssid=wps\n")
1696 f.write("eap_server=1\n")
1697 f.write("wps_state=1\n")
1698 hostapd.add_bss('phy3', ifname, conffile)
1699 hapd = hostapd.Hostapd(ifname)
1700 hapd.request("WPS_PBC")
33d0b157
JM
1701 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
1702 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1703 dev[0].wait_connected(timeout=30)
56887c35
JM
1704 with open(conffile, "r") as f:
1705 lines = f.read().splitlines()
1706 vals = dict()
1707 for l in lines:
1708 try:
1709 [name,value] = l.split('=', 1)
1710 vals[name] = value
1711 except ValueError, e:
1712 if "# WPS configuration" in l:
1713 pass
1714 else:
1715 raise Exception("Unexpected configuration line: " + l)
1716 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
1717 raise Exception("Incorrect configuration: " + str(vals))
1718 finally:
b638f703
JM
1719 try:
1720 os.remove(conffile)
1721 except:
1722 pass
56887c35 1723
91f3cf69
JM
1724def test_ap_wps_pbc_timeout(dev, apdev, params):
1725 """wpa_supplicant PBC walk time [long]"""
1726 if not params['long']:
81e787b7 1727 raise HwsimSkip("Skip test case with long duration due to --long not specified")
91f3cf69
JM
1728 ssid = "test-wps"
1729 hostapd.add_ap(apdev[0]['ifname'],
1730 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
1731 hapd = hostapd.Hostapd(apdev[0]['ifname'])
1732 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
1733 if "OK" not in dev[0].request("WPS_PBC"):
1734 raise Exception("WPS_PBC failed")
1735 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=150)
1736 if ev is None:
1737 raise Exception("WPS-TIMEOUT not reported")
1738
44ff0400
JM
1739def add_ssdp_ap(ifname, ap_uuid):
1740 ssid = "wps-ssdp"
1741 ap_pin = "12345670"
1742 hostapd.add_ap(ifname,
1743 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1744 "wpa_passphrase": "12345678", "wpa": "2",
1745 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1746 "device_name": "Wireless AP", "manufacturer": "Company",
1747 "model_name": "WAP", "model_number": "123",
1748 "serial_number": "12345", "device_type": "6-0050F204-1",
1749 "os_version": "01020300",
1750 "config_methods": "label push_button",
1751 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
1752 "friendly_name": "WPS Access Point",
1753 "manufacturer_url": "http://www.example.com/",
1754 "model_description": "Wireless Access Point",
1755 "model_url": "http://www.example.com/model/",
1756 "upc": "123456789012" })
1757
1758def ssdp_send(msg, no_recv=False):
1759 socket.setdefaulttimeout(1)
1760 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1761 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1762 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1763 sock.bind(("127.0.0.1", 0))
1764 sock.sendto(msg, ("239.255.255.250", 1900))
1765 if no_recv:
1766 return None
1767 return sock.recv(1000)
1768
1769def ssdp_send_msearch(st):
1770 msg = '\r\n'.join([
1771 'M-SEARCH * HTTP/1.1',
1772 'HOST: 239.255.255.250:1900',
1773 'MX: 1',
1774 'MAN: "ssdp:discover"',
1775 'ST: ' + st,
1776 '', ''])
47c549fd 1777 return ssdp_send(msg)
44ff0400
JM
1778
1779def test_ap_wps_ssdp_msearch(dev, apdev):
1780 """WPS AP and SSDP M-SEARCH messages"""
1781 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1782 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1783
1784 msg = '\r\n'.join([
1785 'M-SEARCH * HTTP/1.1',
1786 'Host: 239.255.255.250:1900',
1787 'Mx: 1',
1788 'Man: "ssdp:discover"',
1789 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
1790 '', ''])
1791 ssdp_send(msg)
1792
1793 msg = '\r\n'.join([
1794 'M-SEARCH * HTTP/1.1',
1795 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
1796 'mx: \t1\t\t ',
1797 'man: \t \t "ssdp:discover" ',
1798 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
1799 '', ''])
1800 ssdp_send(msg)
1801
1802 ssdp_send_msearch("ssdp:all")
1803 ssdp_send_msearch("upnp:rootdevice")
1804 ssdp_send_msearch("uuid:" + ap_uuid)
1805 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
1806 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1");
1807
1808 msg = '\r\n'.join([
1809 'M-SEARCH * HTTP/1.1',
1810 'HOST:\t239.255.255.250:1900',
1811 'MAN: "ssdp:discover"',
1812 'MX: 130',
1813 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1814 '', ''])
1815 ssdp_send(msg, no_recv=True)
1816
1817def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
1818 """WPS AP and invalid SSDP M-SEARCH messages"""
1819 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1820 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1821
1822 socket.setdefaulttimeout(1)
1823 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
1824 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1825 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
1826 sock.bind(("127.0.0.1", 0))
1827
1828 logger.debug("Missing MX")
1829 msg = '\r\n'.join([
1830 'M-SEARCH * HTTP/1.1',
1831 'HOST: 239.255.255.250:1900',
1832 'MAN: "ssdp:discover"',
1833 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1834 '', ''])
1835 sock.sendto(msg, ("239.255.255.250", 1900))
1836
1837 logger.debug("Negative MX")
1838 msg = '\r\n'.join([
1839 'M-SEARCH * HTTP/1.1',
1840 'HOST: 239.255.255.250:1900',
1841 'MX: -1',
1842 'MAN: "ssdp:discover"',
1843 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1844 '', ''])
1845 sock.sendto(msg, ("239.255.255.250", 1900))
1846
1847 logger.debug("Invalid MX")
1848 msg = '\r\n'.join([
1849 'M-SEARCH * HTTP/1.1',
1850 'HOST: 239.255.255.250:1900',
1851 'MX; 1',
1852 'MAN: "ssdp:discover"',
1853 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1854 '', ''])
1855 sock.sendto(msg, ("239.255.255.250", 1900))
1856
1857 logger.debug("Missing MAN")
1858 msg = '\r\n'.join([
1859 'M-SEARCH * HTTP/1.1',
1860 'HOST: 239.255.255.250:1900',
1861 'MX: 1',
1862 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1863 '', ''])
1864 sock.sendto(msg, ("239.255.255.250", 1900))
1865
1866 logger.debug("Invalid MAN")
1867 msg = '\r\n'.join([
1868 'M-SEARCH * HTTP/1.1',
1869 'HOST: 239.255.255.250:1900',
1870 'MX: 1',
1871 'MAN: foo',
1872 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1873 '', ''])
1874 sock.sendto(msg, ("239.255.255.250", 1900))
1875 msg = '\r\n'.join([
1876 'M-SEARCH * HTTP/1.1',
1877 'HOST: 239.255.255.250:1900',
1878 'MX: 1',
1879 'MAN; "ssdp:discover"',
1880 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1881 '', ''])
1882 sock.sendto(msg, ("239.255.255.250", 1900))
1883
1884 logger.debug("Missing HOST")
1885 msg = '\r\n'.join([
1886 'M-SEARCH * HTTP/1.1',
1887 'MAN: "ssdp:discover"',
1888 'MX: 1',
1889 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1890 '', ''])
1891 sock.sendto(msg, ("239.255.255.250", 1900))
1892
1893 logger.debug("Missing ST")
1894 msg = '\r\n'.join([
1895 'M-SEARCH * HTTP/1.1',
1896 'HOST: 239.255.255.250:1900',
1897 'MAN: "ssdp:discover"',
1898 'MX: 1',
1899 '', ''])
1900 sock.sendto(msg, ("239.255.255.250", 1900))
1901
1902 logger.debug("Mismatching ST")
1903 msg = '\r\n'.join([
1904 'M-SEARCH * HTTP/1.1',
1905 'HOST: 239.255.255.250:1900',
1906 'MAN: "ssdp:discover"',
1907 'MX: 1',
1908 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
1909 '', ''])
1910 sock.sendto(msg, ("239.255.255.250", 1900))
1911 msg = '\r\n'.join([
1912 'M-SEARCH * HTTP/1.1',
1913 'HOST: 239.255.255.250:1900',
1914 'MAN: "ssdp:discover"',
1915 'MX: 1',
1916 'ST: foo:bar',
1917 '', ''])
1918 sock.sendto(msg, ("239.255.255.250", 1900))
1919 msg = '\r\n'.join([
1920 'M-SEARCH * HTTP/1.1',
1921 'HOST: 239.255.255.250:1900',
1922 'MAN: "ssdp:discover"',
1923 'MX: 1',
1924 'ST: foobar',
1925 '', ''])
1926 sock.sendto(msg, ("239.255.255.250", 1900))
1927
1928 logger.debug("Invalid ST")
1929 msg = '\r\n'.join([
1930 'M-SEARCH * HTTP/1.1',
1931 'HOST: 239.255.255.250:1900',
1932 'MAN: "ssdp:discover"',
1933 'MX: 1',
1934 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
1935 '', ''])
1936 sock.sendto(msg, ("239.255.255.250", 1900))
1937
1938 logger.debug("Invalid M-SEARCH")
1939 msg = '\r\n'.join([
1940 'M+SEARCH * HTTP/1.1',
1941 'HOST: 239.255.255.250:1900',
1942 'MAN: "ssdp:discover"',
1943 'MX: 1',
1944 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1945 '', ''])
1946 sock.sendto(msg, ("239.255.255.250", 1900))
1947 msg = '\r\n'.join([
1948 'M-SEARCH-* HTTP/1.1',
1949 'HOST: 239.255.255.250:1900',
1950 'MAN: "ssdp:discover"',
1951 'MX: 1',
1952 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1953 '', ''])
1954 sock.sendto(msg, ("239.255.255.250", 1900))
1955
1956 logger.debug("Invalid message format")
1957 sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
1958 msg = '\r'.join([
1959 'M-SEARCH * HTTP/1.1',
1960 'HOST: 239.255.255.250:1900',
1961 'MAN: "ssdp:discover"',
1962 'MX: 1',
1963 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1964 '', ''])
1965 sock.sendto(msg, ("239.255.255.250", 1900))
1966
1967 try:
1968 r = sock.recv(1000)
1969 raise Exception("Unexpected M-SEARCH response: " + r)
1970 except socket.timeout:
1971 pass
1972
1973 logger.debug("Valid M-SEARCH")
1974 msg = '\r\n'.join([
1975 'M-SEARCH * HTTP/1.1',
1976 'HOST: 239.255.255.250:1900',
1977 'MAN: "ssdp:discover"',
1978 'MX: 1',
1979 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
1980 '', ''])
1981 sock.sendto(msg, ("239.255.255.250", 1900))
1982
1983 try:
1984 r = sock.recv(1000)
1985 pass
1986 except socket.timeout:
1987 raise Exception("No SSDP response")
1988
1989def test_ap_wps_ssdp_burst(dev, apdev):
1990 """WPS AP and SSDP burst"""
1991 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1992 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
1993
1994 msg = '\r\n'.join([
1995 'M-SEARCH * HTTP/1.1',
1996 'HOST: 239.255.255.250:1900',
1997 'MAN: "ssdp:discover"',
1998 'MX: 1',
1999 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2000 '', ''])
2001 socket.setdefaulttimeout(1)
2002 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2003 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2004 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2005 sock.bind(("127.0.0.1", 0))
2006 for i in range(0, 25):
2007 sock.sendto(msg, ("239.255.255.250", 1900))
2008 resp = 0
2009 while True:
2010 try:
2011 r = sock.recv(1000)
2012 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2013 raise Exception("Unexpected message: " + r)
2014 resp += 1
2015 except socket.timeout:
2016 break
2017 if resp < 20:
2018 raise Exception("Too few SSDP responses")
2019
2020 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2021 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2022 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2023 sock.bind(("127.0.0.1", 0))
2024 for i in range(0, 25):
2025 sock.sendto(msg, ("239.255.255.250", 1900))
2026 while True:
2027 try:
2028 r = sock.recv(1000)
2029 if ap_uuid in r:
2030 break
2031 except socket.timeout:
2032 raise Exception("No SSDP response")
47c549fd
JM
2033
2034def ssdp_get_location(uuid):
2035 res = ssdp_send_msearch("uuid:" + uuid)
2036 location = None
2037 for l in res.splitlines():
2038 if l.lower().startswith("location:"):
2039 location = l.split(':', 1)[1].strip()
2040 break
2041 if location is None:
2042 raise Exception("No UPnP location found")
2043 return location
2044
2045def upnp_get_urls(location):
2046 conn = urllib.urlopen(location)
2047 tree = ET.parse(conn)
2048 root = tree.getroot()
2049 urn = '{urn:schemas-upnp-org:device-1-0}'
2050 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2051 res = {}
2052 res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
2053 res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
2054 res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
2055 return res
2056
2057def upnp_soap_action(conn, path, action, include_soap_action=True, soap_action_override=None):
2058 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2059 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2060 ET.register_namespace('soapenv', soapns)
2061 ET.register_namespace('wfa', wpsns)
2062 attrib = {}
2063 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2064 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2065 body = ET.SubElement(root, "{%s}Body" % soapns)
2066 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
2067 tree = ET.ElementTree(root)
2068 soap = StringIO.StringIO()
2069 tree.write(soap, xml_declaration=True, encoding='utf-8')
2070
2071 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2072 if include_soap_action:
2073 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2074 elif soap_action_override:
2075 headers["SOAPAction"] = soap_action_override
2076 conn.request("POST", path, soap.getvalue(), headers)
2077 return conn.getresponse()
2078
2079def test_ap_wps_upnp(dev, apdev):
2080 """WPS AP and UPnP operations"""
2081 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2082 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2083
2084 location = ssdp_get_location(ap_uuid)
2085 urls = upnp_get_urls(location)
2086
2087 conn = urllib.urlopen(urls['scpd_url'])
2088 scpd = conn.read()
2089
2090 conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"))
2091 if conn.getcode() != 404:
2092 raise Exception("Unexpected HTTP response to GET unknown URL")
2093
2094 url = urlparse.urlparse(location)
2095 conn = httplib.HTTPConnection(url.netloc)
2096 #conn.set_debuglevel(1)
2097 headers = { "Content-type": 'text/xml; charset="utf-8"',
2098 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2099 conn.request("POST", "hello", "\r\n\r\n", headers)
2100 resp = conn.getresponse()
2101 if resp.status != 404:
5c267d71 2102 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2103
2104 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2105 resp = conn.getresponse()
2106 if resp.status != 501:
5c267d71 2107 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2108
2109 headers = { "Content-type": 'text/xml; charset="utf-8"',
2110 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2111 ctrlurl = urlparse.urlparse(urls['control_url'])
2112 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2113 resp = conn.getresponse()
2114 if resp.status != 401:
5c267d71 2115 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2116
2117 logger.debug("GetDeviceInfo without SOAPAction header")
2118 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2119 include_soap_action=False)
2120 if resp.status != 401:
5c267d71 2121 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2122
2123 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2124 for act in [ "foo",
2125 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2126 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2127 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2128 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2129 include_soap_action=False,
2130 soap_action_override=act)
2131 if resp.status != 401:
5c267d71 2132 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2133
2134 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2135 if resp.status != 200:
5c267d71 2136 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2137 dev = resp.read()
2138 if "NewDeviceInfo" not in dev:
2139 raise Exception("Unexpected GetDeviceInfo response")
2140
2141 logger.debug("PutMessage without required parameters")
2142 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2143 if resp.status != 600:
5c267d71 2144 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2145
2146 logger.debug("PutWLANResponse without required parameters")
2147 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2148 if resp.status != 600:
5c267d71 2149 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2150
2151 logger.debug("SetSelectedRegistrar from unregistered ER")
2152 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2153 if resp.status != 501:
5c267d71 2154 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2155
2156 logger.debug("Unknown action")
2157 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2158 if resp.status != 401:
5c267d71 2159 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2160
2161def test_ap_wps_upnp_subscribe(dev, apdev):
2162 """WPS AP and UPnP event subscription"""
2163 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2164 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2165
2166 location = ssdp_get_location(ap_uuid)
2167 urls = upnp_get_urls(location)
2168 eventurl = urlparse.urlparse(urls['event_sub_url'])
2169
2170 url = urlparse.urlparse(location)
2171 conn = httplib.HTTPConnection(url.netloc)
2172 #conn.set_debuglevel(1)
2173 headers = { "callback": '<http://127.0.0.1:12345/event>',
2174 "timeout": "Second-1234" }
2175 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2176 resp = conn.getresponse()
2177 if resp.status != 412:
5c267d71 2178 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2179
2180 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2181 resp = conn.getresponse()
2182 if resp.status != 412:
5c267d71 2183 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2184
2185 headers = { "NT": "upnp:event",
2186 "timeout": "Second-1234" }
2187 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2188 resp = conn.getresponse()
2189 if resp.status != 412:
5c267d71 2190 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2191
2192 headers = { "callback": '<http://127.0.0.1:12345/event>',
2193 "NT": "upnp:foobar",
2194 "timeout": "Second-1234" }
2195 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2196 resp = conn.getresponse()
2197 if resp.status != 400:
5c267d71 2198 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2199
2200 logger.debug("Valid subscription")
2201 headers = { "callback": '<http://127.0.0.1:12345/event>',
2202 "NT": "upnp:event",
2203 "timeout": "Second-1234" }
2204 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2205 resp = conn.getresponse()
2206 if resp.status != 200:
5c267d71 2207 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2208 sid = resp.getheader("sid")
2209 logger.debug("Subscription SID " + sid)
2210
2211 logger.debug("Invalid re-subscription")
2212 headers = { "NT": "upnp:event",
2213 "sid": "123456734567854",
2214 "timeout": "Second-1234" }
2215 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2216 resp = conn.getresponse()
2217 if resp.status != 400:
5c267d71 2218 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2219
2220 logger.debug("Invalid re-subscription")
2221 headers = { "NT": "upnp:event",
2222 "sid": "uuid:123456734567854",
2223 "timeout": "Second-1234" }
2224 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2225 resp = conn.getresponse()
2226 if resp.status != 400:
5c267d71 2227 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2228
2229 logger.debug("Invalid re-subscription")
2230 headers = { "callback": '<http://127.0.0.1:12345/event>',
2231 "NT": "upnp:event",
2232 "sid": sid,
2233 "timeout": "Second-1234" }
2234 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2235 resp = conn.getresponse()
2236 if resp.status != 400:
5c267d71 2237 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2238
2239 logger.debug("SID mismatch in re-subscription")
2240 headers = { "NT": "upnp:event",
2241 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2242 "timeout": "Second-1234" }
2243 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2244 resp = conn.getresponse()
2245 if resp.status != 412:
5c267d71 2246 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2247
2248 logger.debug("Valid re-subscription")
2249 headers = { "NT": "upnp:event",
2250 "sid": sid,
2251 "timeout": "Second-1234" }
2252 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2253 resp = conn.getresponse()
2254 if resp.status != 200:
5c267d71 2255 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2256 sid2 = resp.getheader("sid")
2257 logger.debug("Subscription SID " + sid2)
2258
2259 if sid != sid2:
2260 raise Exception("Unexpected SID change")
2261
2262 logger.debug("Valid re-subscription")
2263 headers = { "NT": "upnp:event",
2264 "sid": "uuid: \t \t" + sid.split(':')[1],
2265 "timeout": "Second-1234" }
2266 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2267 resp = conn.getresponse()
2268 if resp.status != 200:
5c267d71 2269 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2270
2271 logger.debug("Invalid unsubscription")
2272 headers = { "sid": sid }
2273 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
2274 resp = conn.getresponse()
2275 if resp.status != 412:
5c267d71 2276 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2277 headers = { "foo": "bar" }
2278 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2279 resp = conn.getresponse()
2280 if resp.status != 412:
5c267d71 2281 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2282
2283 logger.debug("Valid unsubscription")
2284 headers = { "sid": sid }
2285 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2286 resp = conn.getresponse()
2287 if resp.status != 200:
5c267d71 2288 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2289
2290 logger.debug("Unsubscription for not existing SID")
2291 headers = { "sid": sid }
2292 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2293 resp = conn.getresponse()
2294 if resp.status != 412:
5c267d71 2295 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2296
2297 logger.debug("Invalid unsubscription")
2298 headers = { "sid": " \t \tfoo" }
2299 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2300 resp = conn.getresponse()
2301 if resp.status != 400:
5c267d71 2302 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2303
2304 logger.debug("Invalid unsubscription")
2305 headers = { "sid": "uuid:\t \tfoo" }
2306 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2307 resp = conn.getresponse()
2308 if resp.status != 400:
5c267d71 2309 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2310
2311 logger.debug("Invalid unsubscription")
2312 headers = { "NT": "upnp:event",
2313 "sid": sid }
2314 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2315 resp = conn.getresponse()
2316 if resp.status != 400:
5c267d71 2317 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2318 headers = { "callback": '<http://127.0.0.1:12345/event>',
2319 "sid": sid }
2320 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2321 resp = conn.getresponse()
2322 if resp.status != 400:
5c267d71 2323 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2324
2325 logger.debug("Valid subscription with multiple callbacks")
2326 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>',
2327 "NT": "upnp:event",
2328 "timeout": "Second-1234" }
2329 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2330 resp = conn.getresponse()
2331 if resp.status != 200:
5c267d71 2332 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2333 sid = resp.getheader("sid")
2334 logger.debug("Subscription SID " + sid)
d352c407 2335
b2047531
JM
2336def test_ap_wps_upnp_http_proto(dev, apdev):
2337 """WPS AP and UPnP/HTTP protocol testing"""
2338 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2339 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2340
2341 location = ssdp_get_location(ap_uuid)
2342
2343 url = urlparse.urlparse(location)
81f8e7e9 2344 conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
b2047531
JM
2345 #conn.set_debuglevel(1)
2346
2347 conn.request("HEAD", "hello")
2348 resp = conn.getresponse()
2349 if resp.status != 501:
2350 raise Exception("Unexpected response to HEAD: " + str(resp.status))
2351 conn.close()
2352
2353 for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
2354 try:
2355 conn.request(cmd, "hello")
2356 resp = conn.getresponse()
2357 except Exception, e:
2358 pass
2359 conn.close()
2360
2361 headers = { "Content-Length": 'abc' }
2362 conn.request("HEAD", "hello", "\r\n\r\n", headers)
2363 try:
2364 resp = conn.getresponse()
2365 except Exception, e:
2366 pass
2367 conn.close()
2368
2369 headers = { "Content-Length": '-10' }
2370 conn.request("HEAD", "hello", "\r\n\r\n", headers)
2371 try:
2372 resp = conn.getresponse()
2373 except Exception, e:
2374 pass
2375 conn.close()
2376
2377 headers = { "Content-Length": '10000000000000' }
2378 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
2379 try:
2380 resp = conn.getresponse()
2381 except Exception, e:
2382 pass
2383 conn.close()
2384
2385 headers = { "Transfer-Encoding": 'abc' }
2386 conn.request("HEAD", "hello", "\r\n\r\n", headers)
2387 resp = conn.getresponse()
2388 if resp.status != 501:
2389 raise Exception("Unexpected response to HEAD: " + str(resp.status))
2390 conn.close()
2391
2392 headers = { "Transfer-Encoding": 'chunked' }
2393 conn.request("HEAD", "hello", "\r\n\r\n", headers)
2394 resp = conn.getresponse()
2395 if resp.status != 501:
2396 raise Exception("Unexpected response to HEAD: " + str(resp.status))
2397 conn.close()
2398
2399 # Too long a header
2400 conn.request("HEAD", 5000 * 'A')
2401 try:
2402 resp = conn.getresponse()
2403 except Exception, e:
2404 pass
2405 conn.close()
2406
2407 # Long URL but within header length limits
2408 conn.request("HEAD", 3000 * 'A')
2409 resp = conn.getresponse()
2410 if resp.status != 501:
2411 raise Exception("Unexpected response to HEAD: " + str(resp.status))
2412 conn.close()
2413
2414 headers = { "Content-Length": '20' }
2415 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
2416 try:
2417 resp = conn.getresponse()
2418 except Exception, e:
2419 pass
2420 conn.close()
2421
2422 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
2423 resp = conn.getresponse()
2424 if resp.status != 404:
5c267d71 2425 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
2426 conn.close()
2427
2428 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
2429 try:
2430 resp = conn.getresponse()
2431 except Exception, e:
2432 pass
2433 conn.close()
2434
2435def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
2436 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
2437 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2438 add_ssdp_ap(apdev[0]['ifname'], ap_uuid)
2439
2440 location = ssdp_get_location(ap_uuid)
2441
2442 url = urlparse.urlparse(location)
2443 conn = httplib.HTTPConnection(url.netloc)
2444 #conn.set_debuglevel(1)
2445
2446 headers = { "Transfer-Encoding": 'chunked' }
2447 conn.request("POST", "hello",
2448 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
2449 headers)
2450 resp = conn.getresponse()
2451 if resp.status != 404:
5c267d71 2452 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
2453 conn.close()
2454
2455 conn.putrequest("POST", "hello")
2456 conn.putheader('Transfer-Encoding', 'chunked')
2457 conn.endheaders()
2458 conn.send("a\r\nabcdefghij\r\n")
2459 time.sleep(0.1)
2460 conn.send("2\r\nkl\r\n")
2461 conn.send("0\r\n\r\n")
2462 resp = conn.getresponse()
2463 if resp.status != 404:
5c267d71 2464 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
2465 conn.close()
2466
2467 conn.putrequest("POST", "hello")
2468 conn.putheader('Transfer-Encoding', 'chunked')
2469 conn.endheaders()
2470 completed = False
2471 try:
2472 for i in range(20000):
2473 conn.send("1\r\nZ\r\n")
2474 conn.send("0\r\n\r\n")
2475 resp = conn.getresponse()
2476 completed = True
2477 except Exception, e:
2478 pass
2479 conn.close()
2480 if completed:
2481 raise Exception("Too long chunked request did not result in connection reset")
2482
2483 headers = { "Transfer-Encoding": 'chunked' }
2484 conn.request("POST", "hello", "80000000\r\na", headers)
2485 try:
2486 resp = conn.getresponse()
2487 except Exception, e:
2488 pass
2489 conn.close()
2490
2491 conn.request("POST", "hello", "10000000\r\na", headers)
2492 try:
2493 resp = conn.getresponse()
2494 except Exception, e:
2495 pass
2496 conn.close()
2497
d352c407
JM
2498def test_ap_wps_disabled(dev, apdev):
2499 """WPS operations while WPS is disabled"""
2500 ssid = "test-wps-disabled"
2501 hostapd.add_ap(apdev[0]['ifname'], { "ssid": ssid })
2502 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2503 if "FAIL" not in hapd.request("WPS_PBC"):
2504 raise Exception("WPS_PBC succeeded unexpectedly")
2505 if "FAIL" not in hapd.request("WPS_CANCEL"):
2506 raise Exception("WPS_CANCEL succeeded unexpectedly")
a0fd2ae6
JM
2507
2508def test_ap_wps_mixed_cred(dev, apdev):
2509 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
2510 ssid = "test-wps-wep"
2511 hostapd.add_ap(apdev[0]['ifname'],
2512 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2513 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" })
2514 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2515 hapd.request("WPS_PBC")
33d0b157
JM
2516 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2517 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
9ed53f5e 2518 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
a0fd2ae6
JM
2519 if ev is None:
2520 raise Exception("WPS-SUCCESS event timed out")
2521 nets = dev[0].list_networks()
2522 if len(nets) != 1:
2523 raise Exception("Unexpected number of network blocks")
2524 id = nets[0]['id']
2525 proto = dev[0].get_network(id, "proto")
2526 if proto != "WPA RSN":
2527 raise Exception("Unexpected merged proto field value: " + proto)
2528 pairwise = dev[0].get_network(id, "pairwise")
72a8e30b 2529 if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
a0fd2ae6 2530 raise Exception("Unexpected merged pairwise field value: " + pairwise)
e5a79e3f
JM
2531
2532def test_ap_wps_while_connected(dev, apdev):
2533 """WPS PBC provisioning while connected to another AP"""
2534 ssid = "test-wps-conf"
2535 hostapd.add_ap(apdev[0]['ifname'],
2536 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2537 "wpa_passphrase": "12345678", "wpa": "2",
2538 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2539 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2540
2541 hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
2542 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
2543
2544 logger.info("WPS provisioning step")
2545 hapd.request("WPS_PBC")
2546 dev[0].dump_monitor()
33d0b157 2547 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2548 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
2549 status = dev[0].get_status()
2550 if status['bssid'] != apdev[0]['bssid']:
2551 raise Exception("Unexpected BSSID")
2552
2553def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
2554 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
2555 ssid = "test-wps-conf"
2556 hostapd.add_ap(apdev[0]['ifname'],
2557 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2558 "wpa_passphrase": "12345678", "wpa": "2",
2559 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2560 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2561
2562 hostapd.add_ap(apdev[1]['ifname'], { "ssid": "open" })
2563
2564 try:
2565 dev[0].request("STA_AUTOCONNECT 0")
2566 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
2567
2568 logger.info("WPS provisioning step")
2569 hapd.request("WPS_PBC")
2570 dev[0].dump_monitor()
33d0b157 2571 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2572 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
2573 status = dev[0].get_status()
2574 if status['bssid'] != apdev[0]['bssid']:
2575 raise Exception("Unexpected BSSID")
2576 finally:
2577 dev[0].request("STA_AUTOCONNECT 1")
3f08d1cd
JM
2578
2579def test_ap_wps_from_event(dev, apdev):
2580 """WPS PBC event on AP to enable PBC"""
2581 ssid = "test-wps-conf"
2582 hapd = hostapd.add_ap(apdev[0]['ifname'],
2583 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2584 "wpa_passphrase": "12345678", "wpa": "2",
2585 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
33d0b157 2586 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3f08d1cd 2587 dev[0].dump_monitor()
33d0b157
JM
2588 hapd.dump_monitor()
2589 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3f08d1cd
JM
2590
2591 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
2592 if ev is None:
2593 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
2594 vals = ev.split(' ')
2595 if vals[1] != dev[0].p2p_interface_addr():
2596 raise Exception("Unexpected enrollee address: " + vals[1])
2597 if vals[5] != '4':
2598 raise Exception("Unexpected Device Password Id: " + vals[5])
2599 hapd.request("WPS_PBC")
5f35a5e2 2600 dev[0].wait_connected(timeout=30)
1531402e
JM
2601
2602def test_ap_wps_ap_scan_2(dev, apdev):
2603 """AP_SCAN 2 for WPS"""
2604 ssid = "test-wps-conf"
2605 hapd = hostapd.add_ap(apdev[0]['ifname'],
2606 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2607 "wpa_passphrase": "12345678", "wpa": "2",
2608 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2609 hapd.request("WPS_PBC")
2610
2611 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
2612 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
2613
2614 if "OK" not in wpas.request("AP_SCAN 2"):
2615 raise Exception("Failed to set AP_SCAN 2")
2616
e51c8b2e 2617 wpas.flush_scan_cache()
33d0b157
JM
2618 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
2619 wpas.request("WPS_PBC " + apdev[0]['bssid'])
1531402e
JM
2620 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
2621 if ev is None:
2622 raise Exception("WPS-SUCCESS event timed out")
5f35a5e2 2623 wpas.wait_connected(timeout=30)
1531402e
JM
2624 wpas.request("DISCONNECT")
2625 wpas.request("BSS_FLUSH 0")
2626 wpas.dump_monitor()
2627 wpas.request("REASSOCIATE")
5f35a5e2 2628 wpas.wait_connected(timeout=30)
a08fdb17
JM
2629
2630def test_ap_wps_eapol_workaround(dev, apdev):
2631 """EAPOL workaround code path for 802.1X header length mismatch"""
2632 ssid = "test-wps"
2633 hostapd.add_ap(apdev[0]['ifname'],
2634 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
2635 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2636 bssid = apdev[0]['bssid']
2637 hapd.request("SET ext_eapol_frame_io 1")
2638 dev[0].request("SET ext_eapol_frame_io 1")
2639 hapd.request("WPS_PBC")
2640 dev[0].request("WPS_PBC")
2641
2642 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
2643 if ev is None:
2644 raise Exception("Timeout on EAPOL-TX from hostapd")
2645
2646 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
2647 if "OK" not in res:
2648 raise Exception("EAPOL_RX to wpa_supplicant failed")
46dea617
JM
2649
2650def test_ap_wps_iteration(dev, apdev):
2651 """WPS PIN and iterate through APs without selected registrar"""
2652 ssid = "test-wps-conf"
2653 hapd = hostapd.add_ap(apdev[0]['ifname'],
2654 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2655 "wpa_passphrase": "12345678", "wpa": "2",
2656 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2657
2658 ssid2 = "test-wps-conf2"
2659 hapd2 = hostapd.add_ap(apdev[1]['ifname'],
2660 { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
2661 "wpa_passphrase": "12345678", "wpa": "2",
2662 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2663
2664 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2665 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
2666 dev[0].dump_monitor()
2667 pin = dev[0].request("WPS_PIN any")
2668
2669 # Wait for iteration through all WPS APs to happen before enabling any
2670 # Registrar.
2671 for i in range(2):
2672 ev = dev[0].wait_event(["Associated with"], timeout=30)
2673 if ev is None:
2674 raise Exception("No association seen")
2675 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
2676 if ev is None:
2677 raise Exception("No M2D from AP")
2678 dev[0].wait_disconnected()
2679
2680 # Verify that each AP requested PIN
2681 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
2682 if ev is None:
2683 raise Exception("No WPS-PIN-NEEDED event from AP")
2684 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
2685 if ev is None:
2686 raise Exception("No WPS-PIN-NEEDED event from AP2")
2687
2688 # Provide PIN to one of the APs and verify that connection gets formed
2689 hapd.request("WPS_PIN any " + pin)
2690 dev[0].wait_connected(timeout=30)
2272f5aa
JM
2691
2692def test_ap_wps_iteration_error(dev, apdev):
2693 """WPS AP iteration on no Selected Registrar and error case with an AP"""
2694 ssid = "test-wps-conf-pin"
2695 hapd = hostapd.add_ap(apdev[0]['ifname'],
2696 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2697 "wpa_passphrase": "12345678", "wpa": "2",
2698 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2699 "wps_independent": "1" })
2700 hapd.request("SET ext_eapol_frame_io 1")
2701 bssid = apdev[0]['bssid']
2702 pin = dev[0].wps_read_pin()
2703 dev[0].request("WPS_PIN any " + pin)
2704
2705 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
2706 if ev is None:
2707 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
2708 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
2709
2710 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
2711 if ev is None:
2712 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
2713 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
2714 if ev is None:
2715 raise Exception("No CTRL-EVENT-EAP-STARTED")
2716
2717 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
2718 # a case with an incorrectly behaving WPS AP.
2719
2720 # Start the real target AP and activate registrar on it.
2721 hapd2 = hostapd.add_ap(apdev[1]['ifname'],
2722 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2723 "wpa_passphrase": "12345678", "wpa": "2",
2724 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2725 "wps_independent": "1" })
2726 hapd2.request("WPS_PIN any " + pin)
2727
2728 dev[0].wait_disconnected(timeout=15)
2729 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
2730 if ev is None:
2731 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
2732 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
2733 if ev is None:
2734 raise Exception("No WPS-CRED-RECEIVED for the second AP")
2735 dev[0].wait_connected(timeout=15)
d6f6a86a
JM
2736
2737def test_ap_wps_priority(dev, apdev):
2738 """WPS PIN provisioning with configured AP and wps_priority"""
2739 ssid = "test-wps-conf-pin"
2740 hostapd.add_ap(apdev[0]['ifname'],
2741 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2742 "wpa_passphrase": "12345678", "wpa": "2",
2743 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2744 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2745 logger.info("WPS provisioning step")
2746 pin = dev[0].wps_read_pin()
2747 hapd.request("WPS_PIN any " + pin)
2748 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2749 dev[0].dump_monitor()
2750 try:
2751 dev[0].request("SET wps_priority 6")
2752 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
2753 dev[0].wait_connected(timeout=30)
2754 netw = dev[0].list_networks()
2755 prio = dev[0].get_network(netw[0]['id'], 'priority')
2756 if prio != '6':
2757 raise Exception("Unexpected network priority: " + prio)
2758 finally:
2759 dev[0].request("SET wps_priority 0")
2c3a0190 2760
df1d01cf
JM
2761def test_ap_wps_and_non_wps(dev, apdev):
2762 """WPS and non-WPS AP in single hostapd process"""
2763 params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
2764 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2765
2766 params = { "ssid": "no wps" }
2767 hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
2768
2769 appin = hapd.request("WPS_AP_PIN random")
2770 if "FAIL" in appin:
2771 raise Exception("Could not generate random AP PIN")
2772 if appin not in hapd.request("WPS_AP_PIN get"):
2773 raise Exception("Could not fetch current AP PIN")
2774
2775 if "FAIL" in hapd.request("WPS_PBC"):
2776 raise Exception("WPS_PBC failed")
2777 if "FAIL" in hapd.request("WPS_CANCEL"):
2778 raise Exception("WPS_CANCEL failed")
2779
2c3a0190
JM
2780def test_ap_wps_init_oom(dev, apdev):
2781 """Initial AP configuration and OOM during PSK generation"""
2782 ssid = "test-wps"
2783 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
2784 hapd = hostapd.add_ap(apdev[0]['ifname'], params)
2785
2786 with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
2787 pin = dev[0].wps_read_pin()
2788 hapd.request("WPS_PIN any " + pin)
2789 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2790 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
2791 dev[0].wait_disconnected()
2792
2793 hapd.request("WPS_PIN any " + pin)
2794 dev[0].wait_connected(timeout=30)
ccf4d764
JM
2795
2796def test_ap_wps_er_oom(dev, apdev):
2797 """WPS ER OOM in XML processing"""
2798 try:
2799 _test_ap_wps_er_oom(dev, apdev)
2800 finally:
2801 dev[0].request("WPS_ER_STOP")
2802 dev[1].request("WPS_CANCEL")
2803 dev[0].request("DISCONNECT")
2804
2805def _test_ap_wps_er_oom(dev, apdev):
2806 ssid = "wps-er-ap-config"
2807 ap_pin = "12345670"
2808 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2809 hostapd.add_ap(apdev[0]['ifname'],
2810 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2811 "wpa_passphrase": "12345678", "wpa": "2",
2812 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2813 "device_name": "Wireless AP", "manufacturer": "Company",
2814 "model_name": "WAP", "model_number": "123",
2815 "serial_number": "12345", "device_type": "6-0050F204-1",
2816 "os_version": "01020300",
2817 "config_methods": "label push_button",
2818 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
2819
2820 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
2821
2822 with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
2823 dev[0].request("WPS_ER_START ifname=lo")
2824 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
2825 if ev is not None:
2826 raise Exception("Unexpected AP discovery")
2827
2828 dev[0].request("WPS_ER_STOP")
2829 dev[0].request("WPS_ER_START ifname=lo")
2830 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
2831 if ev is None:
2832 raise Exception("AP discovery timed out")
2833
2834 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2835 with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
2836 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2837 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
2838 if ev is None:
2839 raise Exception("PBC scan failed")
2840 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
2841 if ev is None:
2842 raise Exception("Enrollee discovery timed out")
2602a2ff 2843
c965ae03
JM
2844def test_ap_wps_er_init_oom(dev, apdev):
2845 """WPS ER and OOM during init"""
2846 try:
2847 _test_ap_wps_er_init_oom(dev, apdev)
2848 finally:
2849 dev[0].request("WPS_ER_STOP")
2850
2851def _test_ap_wps_er_init_oom(dev, apdev):
2852 with alloc_fail(dev[0], 1, "wps_er_init"):
2853 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
2854 raise Exception("WPS_ER_START succeeded during OOM")
2855 with alloc_fail(dev[0], 1, "http_server_init"):
2856 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
2857 raise Exception("WPS_ER_START succeeded during OOM")
2858 with alloc_fail(dev[0], 2, "http_server_init"):
2859 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
2860 raise Exception("WPS_ER_START succeeded during OOM")
2861 with alloc_fail(dev[0], 1, "eloop_register_sock;wps_er_ssdp_init"):
2862 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
2863 raise Exception("WPS_ER_START succeeded during OOM")
2864 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
2865 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
2866 raise Exception("WPS_ER_START succeeded during os_get_random failure")
2867
2602a2ff
JM
2868def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
2869 """WPS events and wpa_cli action script"""
8936b095
JM
2870 logdir = os.path.abspath(test_params['logdir'])
2871 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
2872 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
2873 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
2602a2ff
JM
2874
2875 with open(actionfile, 'w') as f:
2876 f.write('#!/bin/sh\n')
2877 f.write('echo $* >> %s\n' % logfile)
2878 # Kill the process and wait some time before returning to allow all the
2879 # pending events to be processed with some of this happening after the
2880 # eloop SIGALRM signal has been scheduled.
2881 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
2882
8936b095
JM
2883 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
2884 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
2602a2ff
JM
2885
2886 ssid = "test-wps-conf"
2887 hostapd.add_ap(apdev[0]['ifname'],
2888 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2889 "wpa_passphrase": "12345678", "wpa": "2",
2890 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2891 hapd = hostapd.Hostapd(apdev[0]['ifname'])
2892
2893 prg = os.path.join(test_params['logdir'],
2894 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
2895 if not os.path.exists(prg):
2896 prg = '../../wpa_supplicant/wpa_cli'
2897 arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
2898 subprocess.call(arg)
2899
2900 arg = [ 'ps', 'ax' ]
2901 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
2902 out = cmd.communicate()[0]
2903 cmd.wait()
2904 logger.debug("Processes:\n" + out)
2905 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
2906 raise Exception("Did not see wpa_cli running")
2907
2908 hapd.request("WPS_PIN any 12345670")
2909 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2910 dev[0].dump_monitor()
2911 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
2912 dev[0].wait_connected(timeout=30)
2913
2914 for i in range(30):
2915 if not os.path.exists(pidfile):
2916 break
2917 time.sleep(0.1)
2918
2919 if not os.path.exists(logfile):
2920 raise Exception("wpa_cli action results file not found")
2921 with open(logfile, 'r') as f:
2922 res = f.read()
2923 if "WPS-SUCCESS" not in res:
2924 raise Exception("WPS-SUCCESS event not seen in action file")
2925
2926 arg = [ 'ps', 'ax' ]
2927 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
2928 out = cmd.communicate()[0]
2929 cmd.wait()
2930 logger.debug("Remaining processes:\n" + out)
2931 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
2932 raise Exception("wpa_cli still running")
2933
2934 if os.path.exists(pidfile):
2935 raise Exception("PID file not removed")
c965ae03
JM
2936
2937def test_ap_wps_er_ssdp_proto(dev, apdev):
2938 """WPS ER SSDP protocol testing"""
2939 try:
2940 _test_ap_wps_er_ssdp_proto(dev, apdev)
2941 finally:
2942 dev[0].request("WPS_ER_STOP")
2943
2944def _test_ap_wps_er_ssdp_proto(dev, apdev):
2945 socket.setdefaulttimeout(1)
2946 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2947 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2948 sock.bind(("239.255.255.250", 1900))
2949 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
2950 raise Exception("Invalid filter accepted")
2951 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
2952 raise Exception("WPS_ER_START with filter failed")
2953 (msg,addr) = sock.recvfrom(1000)
2954 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
2955 if "M-SEARCH" not in msg:
2956 raise Exception("Not an M-SEARCH")
2957 sock.sendto("FOO", addr)
2958 time.sleep(0.1)
2959 dev[0].request("WPS_ER_STOP")
2960
2961 dev[0].request("WPS_ER_START ifname=lo")
2962 (msg,addr) = sock.recvfrom(1000)
2963 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
2964 if "M-SEARCH" not in msg:
2965 raise Exception("Not an M-SEARCH")
2966 sock.sendto("FOO", addr)
2967 sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
2968 sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
2969 sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
2970 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
2971 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
2972 sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
2973 sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
2974 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
2975 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
2976 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
2977 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
2978 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nNTS:ssdp:byebye\r\n\r\n", addr)
2979 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
2980 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
2981 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
2982 time.sleep(0.1)
2983 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
2984 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
2985 time.sleep(0.1)
2986
2987 # Add an AP with bogus URL
2988 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\ncache-control:max-age=1\r\n\r\n", addr)
2989 # Update timeout on AP without updating URL
2990 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
2991 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
2992 if ev is None:
2993 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
2994
2995 # Add an AP with a valid URL (but no server listing to it)
2996 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
2997 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
2998 if ev is None:
2999 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3000
3001 sock.close()
3002
3003wps_event_url = None
3004
4c3ae1c0
JM
3005def gen_upnp_info(eventSubURL='wps_event'):
3006 payload = '''<?xml version="1.0"?>
c965ae03
JM
3007<root xmlns="urn:schemas-upnp-org:device-1-0">
3008<specVersion>
3009<major>1</major>
3010<minor>0</minor>
3011</specVersion>
3012<device>
3013<deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
3014<friendlyName>WPS Access Point</friendlyName>
3015<manufacturer>Company</manufacturer>
3016<modelName>WAP</modelName>
3017<modelNumber>123</modelNumber>
3018<serialNumber>12345</serialNumber>
3019<UDN>uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e</UDN>
3020<serviceList>
3021<service>
3022<serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
3023<serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
3024<SCPDURL>wps_scpd.xml</SCPDURL>
3025<controlURL>wps_control</controlURL>
4c3ae1c0
JM
3026'''
3027 if eventSubURL:
3028 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>'
3029 payload += '''</service>
c965ae03
JM
3030</serviceList>
3031</device>
3032</root>
3033'''
4c3ae1c0
JM
3034 hdr = 'HTTP/1.1 200 OK\r\n' + \
3035 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3036 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3037 'Connection: close\r\n' + \
3038 'Content-Length: ' + str(len(payload)) + '\r\n' + \
3039 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3040 return hdr + payload
3041
3042def gen_wps_control():
3043 payload = '''<?xml version="1.0"?>
c965ae03
JM
3044<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
3045<s:Body>
3046<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
3047<NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
3048Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
3049+FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
30507zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
3051KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
3052AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
3053AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
3054AAYANyoAASA=
3055</NewDeviceInfo>
3056</u:GetDeviceInfoResponse>
3057</s:Body>
3058</s:Envelope>
3059'''
4c3ae1c0
JM
3060 hdr = 'HTTP/1.1 200 OK\r\n' + \
3061 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3062 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3063 'Connection: close\r\n' + \
3064 'Content-Length: ' + str(len(payload)) + '\r\n' + \
3065 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3066 return hdr + payload
3067
3068def gen_wps_event():
3069 payload = ""
3070 hdr = 'HTTP/1.1 200 OK\r\n' + \
3071 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3072 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3073 'Connection: close\r\n' + \
3074 'Content-Length: ' + str(len(payload)) + '\r\n' + \
3075 'SID: uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a\r\n' + \
3076 'Timeout: Second-1801\r\n' + \
3077 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3078 return hdr + payload
3079
3080class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
3081 def handle(self):
3082 data = self.rfile.readline().strip()
3083 logger.info("HTTP server received: " + data)
3084 while True:
3085 hdr = self.rfile.readline().strip()
3086 if len(hdr) == 0:
3087 break
3088 logger.info("HTTP header: " + hdr)
3089 if "CALLBACK:" in hdr:
3090 global wps_event_url
3091 wps_event_url = hdr.split(' ')[1].strip('<>')
3092
3093 if "GET /foo.xml" in data:
3094 self.wfile.write(gen_upnp_info())
3095
3096 if "POST /wps_control" in data:
3097 self.wfile.write(gen_wps_control())
c965ae03
JM
3098
3099 if "SUBSCRIBE /wps_event" in data:
4c3ae1c0 3100 self.wfile.write(gen_wps_event())
c965ae03 3101
4c3ae1c0
JM
3102class MyTCPServer(SocketServer.TCPServer):
3103 def __init__(self, addr, handler):
3104 self.allow_reuse_address = True
3105 SocketServer.TCPServer.__init__(self, addr, handler)
c965ae03 3106
4c3ae1c0 3107def wps_er_start(dev, http_server):
c965ae03
JM
3108 socket.setdefaulttimeout(1)
3109 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3110 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3111 sock.bind(("239.255.255.250", 1900))
4c3ae1c0 3112 dev.request("WPS_ER_START ifname=lo")
c965ae03
JM
3113 (msg,addr) = sock.recvfrom(1000)
3114 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3115 if "M-SEARCH" not in msg:
3116 raise Exception("Not an M-SEARCH")
3117
3118 # Add an AP with a valid URL and server listing to it
4c3ae1c0 3119 server = MyTCPServer(("127.0.0.1", 12345), http_server)
c965ae03
JM
3120 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:http://127.0.0.1:12345/foo.xml\r\ncache-control:max-age=1\r\n\r\n", addr)
3121 server.timeout = 1
4c3ae1c0
JM
3122 return server,sock
3123
3124def wps_er_stop(dev, sock, server, on_alloc_fail=False):
3125 sock.close()
3126 server.server_close()
3127
3128 if on_alloc_fail:
3129 done = False
3130 for i in range(50):
3131 res = dev.request("GET_ALLOC_FAIL")
3132 if res.startswith("0:"):
3133 done = True
3134 break
3135 time.sleep(0.1)
3136 if not done:
3137 raise Exception("No allocation failure reported")
3138 else:
3139 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3140 if ev is None:
3141 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3142 dev.request("WPS_ER_STOP")
3143
3144def test_ap_wps_er_http_proto(dev, apdev):
3145 """WPS ER HTTP protocol testing"""
3146 try:
3147 _test_ap_wps_er_http_proto(dev, apdev)
3148 finally:
3149 dev[0].request("WPS_ER_STOP")
3150
3151def _test_ap_wps_er_http_proto(dev, apdev):
3152 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
3153 server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
c965ae03
JM
3154 global wps_event_url
3155 wps_event_url = None
3156 server.handle_request()
3157 server.handle_request()
3158 server.handle_request()
3159 server.server_close()
3160 if wps_event_url is None:
3161 raise Exception("Did not get event URL")
3162 logger.info("Event URL: " + wps_event_url)
3163
3164 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3165 if ev is None:
3166 raise Exception("No WPS-ER-AP-ADD event")
3167 if uuid not in ev:
3168 raise Exception("UUID mismatch")
3169
3170 sock.close()
3171
3172 logger.info("Valid Probe Request notification")
3173 url = urlparse.urlparse(wps_event_url)
3174 conn = httplib.HTTPConnection(url.netloc)
3175 payload = '''<?xml version="1.0" encoding="utf-8"?>
3176<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
3177<e:property><STAStatus>1</STAStatus></e:property>
3178<e:property><APStatus>1</APStatus></e:property>
3179<e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
3180EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
3181RGV2aWNlIEEQSQAGADcqAAEg
3182</WLANEvent></e:property>
3183</e:propertyset>
3184'''
3185 headers = { "Content-type": 'text/xml; charset="utf-8"',
3186 "Server": "Unspecified, UPnP/1.0, Unspecified",
3187 "HOST": url.netloc,
3188 "NT": "upnp:event",
3189 "SID": "uuid:" + uuid,
3190 "SEQ": "0",
3191 "Content-Length": str(len(payload)) }
3192 conn.request("NOTIFY", url.path, payload, headers)
3193 resp = conn.getresponse()
3194 if resp.status != 200:
3195 raise Exception("Unexpected HTTP response: %d" % resp.status)
3196
3197 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
3198 if ev is None:
3199 raise Exception("No WPS-ER-ENROLLEE-ADD event")
3200 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
3201 raise Exception("No Enrollee UUID match")
3202
3203 logger.info("Incorrect event URL AP id")
3204 conn = httplib.HTTPConnection(url.netloc)
3205 conn.request("NOTIFY", url.path + '123', payload, headers)
3206 resp = conn.getresponse()
3207 if resp.status != 404:
3208 raise Exception("Unexpected HTTP response: %d" % resp.status)
3209
3210 logger.info("Missing AP id")
3211 conn = httplib.HTTPConnection(url.netloc)
3212 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
3213 payload, headers)
3214 time.sleep(0.1)
3215
3216 logger.info("Incorrect event URL event id")
3217 conn = httplib.HTTPConnection(url.netloc)
3218 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
3219 time.sleep(0.1)
3220
3221 logger.info("Incorrect event URL prefix")
3222 conn = httplib.HTTPConnection(url.netloc)
3223 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
3224 resp = conn.getresponse()
3225 if resp.status != 404:
3226 raise Exception("Unexpected HTTP response: %d" % resp.status)
3227
3228 logger.info("Unsupported request")
3229 conn = httplib.HTTPConnection(url.netloc)
3230 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
3231 resp = conn.getresponse()
3232 if resp.status != 501:
3233 raise Exception("Unexpected HTTP response: %d" % resp.status)
3234
3235 logger.info("Unsupported request and OOM")
3236 with alloc_fail(dev[0], 1, "wps_er_http_req"):
3237 conn = httplib.HTTPConnection(url.netloc)
3238 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
3239 time.sleep(0.5)
4c3ae1c0
JM
3240
3241class WPSAPHTTPServer2(SocketServer.StreamRequestHandler):
3242 def handle(self):
3243 data = self.rfile.readline().strip()
3244 logger.info("HTTP server received: " + data)
3245 while True:
3246 hdr = self.rfile.readline().strip()
3247 if len(hdr) == 0:
3248 break
3249 logger.info("HTTP header: " + hdr)
3250
3251 if "GET /foo.xml" in data:
3252 self.wfile.write(gen_upnp_info(eventSubURL=None))
3253
3254 if "POST /wps_control" in data:
3255 self.wfile.write(gen_wps_control())
3256
3257def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
3258 """WPS ER HTTP protocol testing - no eventSubURL"""
3259 try:
3260 _test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev)
3261 finally:
3262 dev[0].request("WPS_ER_STOP")
3263
3264def _test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
3265 server,sock = wps_er_start(dev[0], WPSAPHTTPServer2)
3266 server.handle_request()
3267 server.handle_request()
3268 wps_er_stop(dev[0], sock, server)
3269
3270class WPSAPHTTPServer3(SocketServer.StreamRequestHandler):
3271 def handle(self):
3272 data = self.rfile.readline().strip()
3273 logger.info("HTTP server received: " + data)
3274 while True:
3275 hdr = self.rfile.readline().strip()
3276 if len(hdr) == 0:
3277 break
3278 logger.info("HTTP header: " + hdr)
3279
3280 if "GET /foo.xml" in data:
3281 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
3282
3283 if "POST /wps_control" in data:
3284 self.wfile.write(gen_wps_control())
3285
3286def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
3287 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
3288 try:
3289 _test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev)
3290 finally:
3291 dev[0].request("WPS_ER_STOP")
3292
3293def _test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
3294 server,sock = wps_er_start(dev[0], WPSAPHTTPServer3)
3295 server.handle_request()
3296 server.handle_request()
3297 wps_er_stop(dev[0], sock, server)
3298
3299def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
3300 """WPS ER HTTP protocol testing - subscribe OOM"""
3301 try:
3302 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
3303 finally:
3304 dev[0].request("WPS_ER_STOP")
3305
3306def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
3307 tests = [ (1, "http_client_url_parse"),
3308 (1, "wpabuf_alloc;wps_er_subscribe"),
3309 (1, "http_client_addr"),
3310 (1, "eloop_register_sock;http_client_addr"),
3311 (1, "eloop_register_timeout;http_client_addr") ]
3312 for count,func in tests:
3313 with alloc_fail(dev[0], count, func):
3314 server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
3315 server.handle_request()
3316 server.handle_request()
3317 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)