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