]> git.ipfire.org Git - thirdparty/hostap.git/blame - tests/hwsim/test_ap_wps.py
tests: Invalid WMM_AC_ADDTS parameter
[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
9fd6804d 7from remotehost import remote_compatible
6aaa661a 8import base64
476daa05 9import binascii
7511ead0
JM
10from Crypto.Cipher import AES
11import hashlib
12import hmac
2035b170 13import os
302b7a1b 14import time
2602a2ff 15import stat
302b7a1b
JM
16import subprocess
17import logging
c9aa4308 18logger = logging.getLogger()
1013a576 19import re
44ff0400 20import socket
7511ead0 21import struct
47c549fd
JM
22import httplib
23import urlparse
24import urllib
25import xml.etree.ElementTree as ET
26import StringIO
c965ae03 27import SocketServer
302b7a1b
JM
28
29import hwsim_utils
30import hostapd
1531402e 31from wpasupplicant import WpaSupplicant
c965ae03 32from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
1e35aa15 33from utils import wait_fail_trigger
d8e5a55f 34from test_ap_eap import int_eap_server_params
302b7a1b 35
24b7f282
JM
36def wps_start_ap(apdev, ssid="test-wps-conf"):
37 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
38 "wpa_passphrase": "12345678", "wpa": "2",
39 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
afc26df2 40 return hostapd.add_ap(apdev, params)
24b7f282 41
9fd6804d 42@remote_compatible
ae3ad328 43def test_ap_wps_init(dev, apdev):
302b7a1b
JM
44 """Initial AP configuration with first WPS Enrollee"""
45 ssid = "test-wps"
6f334bf7
JD
46 hapd = hostapd.add_ap(apdev[0],
47 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
302b7a1b
JM
48 logger.info("WPS provisioning step")
49 hapd.request("WPS_PBC")
d671a420
JM
50 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
51 raise Exception("PBC status not shown correctly")
b9018833
JM
52
53 id = dev[0].add_network()
54 dev[0].set_network_quoted(id, "ssid", "home")
55 dev[0].set_network_quoted(id, "psk", "12345678")
56 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
57
58 id = dev[0].add_network()
59 dev[0].set_network_quoted(id, "ssid", "home2")
60 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
61 dev[0].set_network(id, "key_mgmt", "NONE")
62 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
63
302b7a1b 64 dev[0].request("WPS_PBC")
5f35a5e2 65 dev[0].wait_connected(timeout=30)
302b7a1b 66 status = dev[0].get_status()
ae3ad328 67 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
68 raise Exception("Not fully connected")
69 if status['ssid'] != ssid:
70 raise Exception("Unexpected SSID")
71 if status['pairwise_cipher'] != 'CCMP':
72 raise Exception("Unexpected encryption configuration")
73 if status['key_mgmt'] != 'WPA2-PSK':
74 raise Exception("Unexpected key_mgmt")
75
d671a420
JM
76 status = hapd.request("WPS_GET_STATUS")
77 if "PBC Status: Disabled" not in status:
78 raise Exception("PBC status not shown correctly")
79 if "Last WPS result: Success" not in status:
80 raise Exception("Last WPS result not shown correctly")
81 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
82 raise Exception("Peer address not shown correctly")
75b25ece
JM
83 conf = hapd.request("GET_CONFIG")
84 if "wps_state=configured" not in conf:
85 raise Exception("AP not in WPS configured state")
742408af
JM
86 if "wpa=3" not in conf:
87 raise Exception("AP not in WPA+WPA2 configuration")
75b25ece
JM
88 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
89 raise Exception("Unexpected rsn_pairwise_cipher")
90 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
91 raise Exception("Unexpected wpa_pairwise_cipher")
92 if "group_cipher=TKIP" not in conf:
93 raise Exception("Unexpected group_cipher")
d671a420 94
b9018833
JM
95 if len(dev[0].list_networks()) != 3:
96 raise Exception("Unexpected number of network blocks")
97
18030dc0
JM
98def test_ap_wps_init_2ap_pbc(dev, apdev):
99 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
100 ssid = "test-wps"
101 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
6f334bf7 102 hapd = hostapd.add_ap(apdev[0], params)
8b8a1864 103 hostapd.add_ap(apdev[1], params)
18030dc0
JM
104 logger.info("WPS provisioning step")
105 hapd.request("WPS_PBC")
84a40841
JM
106 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
107 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
108 bss = dev[0].get_bss(apdev[0]['bssid'])
109 if "[WPS-PBC]" not in bss['flags']:
110 raise Exception("WPS-PBC flag missing from AP1")
111 bss = dev[0].get_bss(apdev[1]['bssid'])
112 if "[WPS-PBC]" not in bss['flags']:
113 raise Exception("WPS-PBC flag missing from AP2")
114 dev[0].dump_monitor()
f19d87f1 115 dev[0].request("SET wps_cred_processing 2")
18030dc0 116 dev[0].request("WPS_PBC")
f19d87f1
JM
117 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
118 dev[0].request("SET wps_cred_processing 0")
119 if ev is None:
120 raise Exception("WPS cred event not seen")
121 if "100e" not in ev:
122 raise Exception("WPS attributes not included in the cred event")
5f35a5e2 123 dev[0].wait_connected(timeout=30)
18030dc0 124
84a40841
JM
125 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
126 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
127 bss = dev[1].get_bss(apdev[0]['bssid'])
128 if "[WPS-PBC]" in bss['flags']:
129 raise Exception("WPS-PBC flag not cleared from AP1")
130 bss = dev[1].get_bss(apdev[1]['bssid'])
131 if "[WPS-PBC]" in bss['flags']:
0bde923c 132 raise Exception("WPS-PBC flag not cleared from AP2")
18030dc0
JM
133
134def test_ap_wps_init_2ap_pin(dev, apdev):
135 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
136 ssid = "test-wps"
137 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
6f334bf7 138 hapd = hostapd.add_ap(apdev[0], params)
8b8a1864 139 hostapd.add_ap(apdev[1], params)
18030dc0
JM
140 logger.info("WPS provisioning step")
141 pin = dev[0].wps_read_pin()
142 hapd.request("WPS_PIN any " + pin)
84a40841
JM
143 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
144 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
145 bss = dev[0].get_bss(apdev[0]['bssid'])
146 if "[WPS-AUTH]" not in bss['flags']:
147 raise Exception("WPS-AUTH flag missing from AP1")
148 bss = dev[0].get_bss(apdev[1]['bssid'])
149 if "[WPS-AUTH]" not in bss['flags']:
150 raise Exception("WPS-AUTH flag missing from AP2")
151 dev[0].dump_monitor()
152 dev[0].request("WPS_PIN any " + pin)
5f35a5e2 153 dev[0].wait_connected(timeout=30)
18030dc0 154
84a40841
JM
155 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
156 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
18030dc0
JM
157 bss = dev[1].get_bss(apdev[0]['bssid'])
158 if "[WPS-AUTH]" in bss['flags']:
159 raise Exception("WPS-AUTH flag not cleared from AP1")
160 bss = dev[1].get_bss(apdev[1]['bssid'])
161 if "[WPS-AUTH]" in bss['flags']:
0bde923c 162 raise Exception("WPS-AUTH flag not cleared from AP2")
18030dc0 163
9fd6804d 164@remote_compatible
35831e94
JM
165def test_ap_wps_init_through_wps_config(dev, apdev):
166 """Initial AP configuration using wps_config command"""
167 ssid = "test-wps-init-config"
6f334bf7
JD
168 hapd = hostapd.add_ap(apdev[0],
169 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
35831e94
JM
170 if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
171 raise Exception("WPS_CONFIG command failed")
180cd73d
JM
172 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
173 if ev is None:
174 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
175 # It takes some time for the AP to update Beacon and Probe Response frames,
176 # so wait here before requesting the scan to be started to avoid adding
177 # extra five second wait to the test due to fetching obsolete scan results.
178 hapd.ping()
179 time.sleep(0.2)
35831e94
JM
180 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
181 pairwise="CCMP", group="CCMP")
182
82358a2a
JM
183 if "FAIL" not in hapd.request("WPS_CONFIG foo"):
184 raise Exception("Invalid WPS_CONFIG accepted")
185
9fd6804d 186@remote_compatible
fbf6b717
JM
187def test_ap_wps_init_through_wps_config_2(dev, apdev):
188 """AP configuration using wps_config and wps_cred_processing=2"""
189 ssid = "test-wps-init-config"
6f334bf7
JD
190 hapd = hostapd.add_ap(apdev[0],
191 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
192 "wps_cred_processing": "2" })
fbf6b717
JM
193 if "FAIL" in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "12345678".encode("hex")):
194 raise Exception("WPS_CONFIG command failed")
195 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
196 if ev is None:
197 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
198 if "100e" not in ev:
199 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
200
9fd6804d 201@remote_compatible
e1eb0e9e
JM
202def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
203 """AP configuration using wps_config command with invalid passphrase"""
204 ssid = "test-wps-init-config"
6f334bf7
JD
205 hapd = hostapd.add_ap(apdev[0],
206 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
e1eb0e9e
JM
207 if "FAIL" not in hapd.request("WPS_CONFIG " + ssid.encode("hex") + " WPA2PSK CCMP " + "1234567".encode("hex")):
208 raise Exception("Invalid WPS_CONFIG command accepted")
209
ae3ad328 210def test_ap_wps_conf(dev, apdev):
302b7a1b
JM
211 """WPS PBC provisioning with configured AP"""
212 ssid = "test-wps-conf"
6f334bf7
JD
213 hapd = hostapd.add_ap(apdev[0],
214 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
215 "wpa_passphrase": "12345678", "wpa": "2",
216 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
217 logger.info("WPS provisioning step")
218 hapd.request("WPS_PBC")
33d0b157 219 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 220 dev[0].dump_monitor()
33d0b157 221 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 222 dev[0].wait_connected(timeout=30)
302b7a1b 223 status = dev[0].get_status()
ae3ad328 224 if status['wpa_state'] != 'COMPLETED':
302b7a1b 225 raise Exception("Not fully connected")
ae3ad328
JM
226 if status['bssid'] != apdev[0]['bssid']:
227 raise Exception("Unexpected BSSID")
302b7a1b
JM
228 if status['ssid'] != ssid:
229 raise Exception("Unexpected SSID")
230 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
231 raise Exception("Unexpected encryption configuration")
232 if status['key_mgmt'] != 'WPA2-PSK':
233 raise Exception("Unexpected key_mgmt")
234
097cd9cd
JM
235 sta = hapd.get_sta(dev[0].p2p_interface_addr())
236 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
237 raise Exception("Device name not available in STA command")
238
daad14cc
JM
239def test_ap_wps_conf_5ghz(dev, apdev):
240 """WPS PBC provisioning with configured AP on 5 GHz band"""
241 try:
9d7fdac5 242 hapd = None
daad14cc
JM
243 ssid = "test-wps-conf"
244 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
245 "wpa_passphrase": "12345678", "wpa": "2",
246 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
247 "country_code": "FI", "hw_mode": "a", "channel": "36" }
8b8a1864 248 hapd = hostapd.add_ap(apdev[0], params)
daad14cc
JM
249 logger.info("WPS provisioning step")
250 hapd.request("WPS_PBC")
33d0b157
JM
251 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
252 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 253 dev[0].wait_connected(timeout=30)
daad14cc
JM
254
255 sta = hapd.get_sta(dev[0].p2p_interface_addr())
256 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
257 raise Exception("Device name not available in STA command")
258 finally:
9d7fdac5
JM
259 dev[0].request("DISCONNECT")
260 if hapd:
261 hapd.request("DISABLE")
c4668009 262 subprocess.call(['iw', 'reg', 'set', '00'])
9d7fdac5 263 dev[0].flush_scan_cache()
daad14cc
JM
264
265def test_ap_wps_conf_chan14(dev, apdev):
266 """WPS PBC provisioning with configured AP on channel 14"""
267 try:
9d7fdac5 268 hapd = None
daad14cc
JM
269 ssid = "test-wps-conf"
270 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
271 "wpa_passphrase": "12345678", "wpa": "2",
272 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
273 "country_code": "JP", "hw_mode": "b", "channel": "14" }
8b8a1864 274 hapd = hostapd.add_ap(apdev[0], params)
daad14cc
JM
275 logger.info("WPS provisioning step")
276 hapd.request("WPS_PBC")
277 dev[0].request("WPS_PBC")
5f35a5e2 278 dev[0].wait_connected(timeout=30)
daad14cc
JM
279
280 sta = hapd.get_sta(dev[0].p2p_interface_addr())
281 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
282 raise Exception("Device name not available in STA command")
283 finally:
9d7fdac5
JM
284 dev[0].request("DISCONNECT")
285 if hapd:
286 hapd.request("DISABLE")
c4668009 287 subprocess.call(['iw', 'reg', 'set', '00'])
9d7fdac5 288 dev[0].flush_scan_cache()
daad14cc 289
9fd6804d 290@remote_compatible
04e62788
JM
291def test_ap_wps_twice(dev, apdev):
292 """WPS provisioning with twice to change passphrase"""
293 ssid = "test-wps-twice"
294 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
295 "wpa_passphrase": "12345678", "wpa": "2",
296 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
01703a9f 297 hapd = hostapd.add_ap(apdev[0], params)
04e62788
JM
298 logger.info("WPS provisioning step")
299 hapd.request("WPS_PBC")
33d0b157 300 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
04e62788 301 dev[0].dump_monitor()
33d0b157 302 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 303 dev[0].wait_connected(timeout=30)
04e62788
JM
304 dev[0].request("DISCONNECT")
305
306 logger.info("Restart AP with different passphrase and re-run WPS")
01703a9f 307 hostapd.remove_bss(apdev[0])
04e62788 308 params['wpa_passphrase'] = 'another passphrase'
01703a9f 309 hapd = hostapd.add_ap(apdev[0], params)
04e62788
JM
310 logger.info("WPS provisioning step")
311 hapd.request("WPS_PBC")
312 dev[0].dump_monitor()
33d0b157 313 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 314 dev[0].wait_connected(timeout=30)
04e62788
JM
315 networks = dev[0].list_networks()
316 if len(networks) > 1:
317 raise Exception("Unexpected duplicated network block present")
318
9fd6804d 319@remote_compatible
d658205a
JM
320def test_ap_wps_incorrect_pin(dev, apdev):
321 """WPS PIN provisioning with incorrect PIN"""
322 ssid = "test-wps-incorrect-pin"
6f334bf7
JD
323 hapd = hostapd.add_ap(apdev[0],
324 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
325 "wpa_passphrase": "12345678", "wpa": "2",
326 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d658205a
JM
327
328 logger.info("WPS provisioning attempt 1")
329 hapd.request("WPS_PIN any 12345670")
33d0b157 330 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
d658205a 331 dev[0].dump_monitor()
33d0b157 332 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
d658205a
JM
333 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
334 if ev is None:
335 raise Exception("WPS operation timed out")
336 if "config_error=18" not in ev:
337 raise Exception("Incorrect config_error reported")
338 if "msg=8" not in ev:
339 raise Exception("PIN error detected on incorrect message")
5f35a5e2 340 dev[0].wait_disconnected(timeout=10)
d658205a
JM
341 dev[0].request("WPS_CANCEL")
342 # if a scan was in progress, wait for it to complete before trying WPS again
343 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
344
d671a420
JM
345 status = hapd.request("WPS_GET_STATUS")
346 if "Last WPS result: Failed" not in status:
347 raise Exception("WPS failure result not shown correctly")
348
d658205a
JM
349 logger.info("WPS provisioning attempt 2")
350 hapd.request("WPS_PIN any 12345670")
351 dev[0].dump_monitor()
33d0b157 352 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
d658205a
JM
353 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
354 if ev is None:
355 raise Exception("WPS operation timed out")
356 if "config_error=18" not in ev:
357 raise Exception("Incorrect config_error reported")
358 if "msg=10" not in ev:
359 raise Exception("PIN error detected on incorrect message")
5f35a5e2 360 dev[0].wait_disconnected(timeout=10)
d658205a 361
9fd6804d 362@remote_compatible
ae3ad328 363def test_ap_wps_conf_pin(dev, apdev):
302b7a1b
JM
364 """WPS PIN provisioning with configured AP"""
365 ssid = "test-wps-conf-pin"
6f334bf7
JD
366 hapd = hostapd.add_ap(apdev[0],
367 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
368 "wpa_passphrase": "12345678", "wpa": "2",
369 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
370 logger.info("WPS provisioning step")
371 pin = dev[0].wps_read_pin()
372 hapd.request("WPS_PIN any " + pin)
33d0b157 373 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 374 dev[0].dump_monitor()
33d0b157 375 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 376 dev[0].wait_connected(timeout=30)
302b7a1b 377 status = dev[0].get_status()
ae3ad328 378 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
379 raise Exception("Not fully connected")
380 if status['ssid'] != ssid:
381 raise Exception("Unexpected SSID")
382 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
383 raise Exception("Unexpected encryption configuration")
384 if status['key_mgmt'] != 'WPA2-PSK':
385 raise Exception("Unexpected key_mgmt")
386
84a40841 387 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
362ba6de
JM
388 bss = dev[1].get_bss(apdev[0]['bssid'])
389 if "[WPS-AUTH]" in bss['flags']:
390 raise Exception("WPS-AUTH flag not cleared")
a60a6d6b 391 logger.info("Try to connect from another station using the same PIN")
33d0b157 392 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
a60a6d6b
JM
393 ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
394 if ev is None:
395 raise Exception("Operation timed out")
396 if "WPS-M2D" not in ev:
397 raise Exception("Unexpected WPS operation started")
6e12eaa4 398 hapd.request("WPS_PIN any " + pin)
5f35a5e2 399 dev[1].wait_connected(timeout=30)
362ba6de 400
ff518fbd
JM
401def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
402 """WPS PIN provisioning with configured AP (WPA+WPA2)"""
403 ssid = "test-wps-conf-pin-mixed"
6f334bf7
JD
404 hapd = hostapd.add_ap(apdev[0],
405 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
406 "wpa_passphrase": "12345678", "wpa": "3",
407 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
408 "wpa_pairwise": "TKIP" })
ff518fbd
JM
409
410 logger.info("WPS provisioning step")
411 pin = dev[0].wps_read_pin()
412 hapd.request("WPS_PIN any " + pin)
413 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
414 dev[0].dump_monitor()
415 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
416 dev[0].wait_connected(timeout=30)
417 status = dev[0].get_status()
418 dev[0].request("REMOVE_NETWORK all")
419 dev[0].wait_disconnected()
420 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
421 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
422
423 logger.info("WPS provisioning step (auth_types=0x1b)")
424 if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
425 raise Exception("Failed to set wps_force_auth_types 0x1b")
426 pin = dev[0].wps_read_pin()
427 hapd.request("WPS_PIN any " + pin)
428 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
429 dev[0].dump_monitor()
430 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
431 dev[0].wait_connected(timeout=30)
432 status = dev[0].get_status()
433 dev[0].request("REMOVE_NETWORK all")
434 dev[0].wait_disconnected()
435 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
436 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
437
438 logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
439 if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
440 raise Exception("Failed to set wps_force_auth_types 0")
441 if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
442 raise Exception("Failed to set wps_force_encr_types 0")
443 pin = dev[0].wps_read_pin()
444 hapd.request("WPS_PIN any " + pin)
445 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
446 dev[0].dump_monitor()
447 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
448 dev[0].wait_connected(timeout=30)
449 status = dev[0].get_status()
450 dev[0].request("REMOVE_NETWORK all")
451 dev[0].wait_disconnected()
452 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
453 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
454
455 dev[0].request("SET wps_force_auth_types ")
456 dev[0].request("SET wps_force_encr_types ")
457
9fd6804d 458@remote_compatible
6257f9c0
JM
459def test_ap_wps_conf_pin_v1(dev, apdev):
460 """WPS PIN provisioning with configured WPS v1.0 AP"""
461 ssid = "test-wps-conf-pin-v1"
6f334bf7
JD
462 hapd = hostapd.add_ap(apdev[0],
463 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
464 "wpa_passphrase": "12345678", "wpa": "2",
465 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
6257f9c0
JM
466 logger.info("WPS provisioning step")
467 pin = dev[0].wps_read_pin()
468 hapd.request("SET wps_version_number 0x10")
469 hapd.request("WPS_PIN any " + pin)
470 found = False
471 for i in range(0, 10):
472 dev[0].scan(freq="2412")
473 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
474 found = True
475 break
476 if not found:
477 hapd.request("SET wps_version_number 0x20")
478 raise Exception("WPS-PIN flag not seen in scan results")
479 dev[0].dump_monitor()
33d0b157 480 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 481 dev[0].wait_connected(timeout=30)
6257f9c0 482 hapd.request("SET wps_version_number 0x20")
6257f9c0 483
9fd6804d 484@remote_compatible
e9129860
JM
485def test_ap_wps_conf_pin_2sta(dev, apdev):
486 """Two stations trying to use WPS PIN at the same time"""
487 ssid = "test-wps-conf-pin2"
6f334bf7
JD
488 hapd = hostapd.add_ap(apdev[0],
489 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
490 "wpa_passphrase": "12345678", "wpa": "2",
491 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e9129860
JM
492 logger.info("WPS provisioning step")
493 pin = "12345670"
494 pin2 = "55554444"
495 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
496 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
e9129860 497 dev[0].dump_monitor()
e9129860 498 dev[1].dump_monitor()
33d0b157
JM
499 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
500 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
501 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
502 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2
JM
503 dev[0].wait_connected(timeout=30)
504 dev[1].wait_connected(timeout=30)
0489e880 505
9fd6804d 506@remote_compatible
0489e880
JM
507def test_ap_wps_conf_pin_timeout(dev, apdev):
508 """WPS PIN provisioning with configured AP timing out PIN"""
509 ssid = "test-wps-conf-pin"
6f334bf7
JD
510 hapd = hostapd.add_ap(apdev[0],
511 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
512 "wpa_passphrase": "12345678", "wpa": "2",
513 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
0489e880
JM
514 addr = dev[0].p2p_interface_addr()
515 pin = dev[0].wps_read_pin()
516 if "FAIL" not in hapd.request("WPS_PIN "):
517 raise Exception("Unexpected success on invalid WPS_PIN")
518 hapd.request("WPS_PIN any " + pin + " 1")
33d0b157 519 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
0489e880 520 time.sleep(1.1)
33d0b157 521 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
0489e880
JM
522 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
523 if ev is None:
524 raise Exception("WPS-PIN-NEEDED event timed out")
525 ev = dev[0].wait_event(["WPS-M2D"])
526 if ev is None:
527 raise Exception("M2D not reported")
528 dev[0].request("WPS_CANCEL")
529
530 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
33d0b157 531 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 532 dev[0].wait_connected(timeout=30)
e9129860 533
ae3ad328 534def test_ap_wps_reg_connect(dev, apdev):
302b7a1b 535 """WPS registrar using AP PIN to connect"""
803edd1c 536 ssid = "test-wps-reg-ap-pin"
302b7a1b 537 appin = "12345670"
8b8a1864 538 hostapd.add_ap(apdev[0],
302b7a1b
JM
539 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
540 "wpa_passphrase": "12345678", "wpa": "2",
541 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
542 "ap_pin": appin})
543 logger.info("WPS provisioning step")
302b7a1b 544 dev[0].dump_monitor()
33d0b157 545 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 546 dev[0].wps_reg(apdev[0]['bssid'], appin)
302b7a1b 547 status = dev[0].get_status()
ae3ad328 548 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
549 raise Exception("Not fully connected")
550 if status['ssid'] != ssid:
551 raise Exception("Unexpected SSID")
552 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
553 raise Exception("Unexpected encryption configuration")
554 if status['key_mgmt'] != 'WPA2-PSK':
555 raise Exception("Unexpected key_mgmt")
556
e60be3b3
JM
557def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
558 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
559 ssid = "test-wps-reg-ap-pin"
560 appin = "12345670"
8b8a1864 561 hostapd.add_ap(apdev[0],
e60be3b3
JM
562 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
563 "wpa_passphrase": "12345678", "wpa": "3",
564 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
565 "wpa_pairwise": "TKIP", "ap_pin": appin})
566 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
567 dev[0].wps_reg(apdev[0]['bssid'], appin)
568 status = dev[0].get_status()
569 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
570 raise Exception("Not fully connected")
571 if status['ssid'] != ssid:
572 raise Exception("Unexpected SSID")
573 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
574 raise Exception("Unexpected encryption configuration")
575 if status['key_mgmt'] != 'WPA2-PSK':
576 raise Exception("Unexpected key_mgmt")
577
7511ead0
JM
578def test_ap_wps_reg_override_ap_settings(dev, apdev):
579 """WPS registrar and ap_settings override"""
580 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
581 try:
582 os.remove(ap_settings)
583 except:
584 pass
585 # Override AP Settings with values that point to another AP
586 data = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
587 data += build_wsc_attr(ATTR_SSID, "test")
588 data += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
589 data += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
590 data += build_wsc_attr(ATTR_NETWORK_KEY, '')
591 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
592 with open(ap_settings, "w") as f:
593 f.write(data)
594 ssid = "test-wps-reg-ap-pin"
595 appin = "12345670"
8b8a1864 596 hostapd.add_ap(apdev[0],
7511ead0
JM
597 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
598 "wpa_passphrase": "12345678", "wpa": "2",
599 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
600 "ap_pin": appin, "ap_settings": ap_settings })
8b8a1864 601 hapd2 = hostapd.add_ap(apdev[1], { "ssid": "test" })
7511ead0
JM
602 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
603 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
604 dev[0].wps_reg(apdev[0]['bssid'], appin)
605 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
606 os.remove(ap_settings)
607 if ev is None:
608 raise Exception("No connection with the other AP")
609
9488858f
JM
610def check_wps_reg_failure(dev, ap, appin):
611 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
612 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
613 if ev is None:
614 raise Exception("WPS operation timed out")
615 if "WPS-SUCCESS" in ev:
616 raise Exception("WPS operation succeeded unexpectedly")
617 if "config_error=15" not in ev:
618 raise Exception("WPS setup locked state was not reported correctly")
619
e4357b19
JM
620def test_ap_wps_random_ap_pin(dev, apdev):
621 """WPS registrar using random AP PIN"""
622 ssid = "test-wps-reg-random-ap-pin"
623 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
6f334bf7
JD
624 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
625 "wpa_passphrase": "12345678", "wpa": "2",
626 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
627 "device_name": "Wireless AP", "manufacturer": "Company",
628 "model_name": "WAP", "model_number": "123",
629 "serial_number": "12345", "device_type": "6-0050F204-1",
630 "os_version": "01020300",
631 "config_methods": "label push_button",
632 "uuid": ap_uuid, "upnp_iface": "lo" }
633 hapd = hostapd.add_ap(apdev[0], params)
e4357b19
JM
634 appin = hapd.request("WPS_AP_PIN random")
635 if "FAIL" in appin:
636 raise Exception("Could not generate random AP PIN")
637 if appin not in hapd.request("WPS_AP_PIN get"):
638 raise Exception("Could not fetch current AP PIN")
639 logger.info("WPS provisioning step")
33d0b157 640 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
e4357b19
JM
641 dev[0].wps_reg(apdev[0]['bssid'], appin)
642
643 hapd.request("WPS_AP_PIN disable")
644 logger.info("WPS provisioning step with AP PIN disabled")
33d0b157 645 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9488858f
JM
646 check_wps_reg_failure(dev[1], apdev[0], appin)
647
648 logger.info("WPS provisioning step with AP PIN reset")
649 appin = "12345670"
650 hapd.request("WPS_AP_PIN set " + appin)
651 dev[1].wps_reg(apdev[0]['bssid'], appin)
652 dev[0].request("REMOVE_NETWORK all")
653 dev[1].request("REMOVE_NETWORK all")
5f35a5e2
JM
654 dev[0].wait_disconnected(timeout=10)
655 dev[1].wait_disconnected(timeout=10)
9488858f
JM
656
657 logger.info("WPS provisioning step after AP PIN timeout")
658 hapd.request("WPS_AP_PIN disable")
659 appin = hapd.request("WPS_AP_PIN random 1")
660 time.sleep(1.1)
661 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
662 raise Exception("AP PIN unexpectedly still enabled")
663 check_wps_reg_failure(dev[0], apdev[0], appin)
664
665 logger.info("WPS provisioning step after AP PIN timeout(2)")
666 hapd.request("WPS_AP_PIN disable")
667 appin = "12345670"
668 hapd.request("WPS_AP_PIN set " + appin + " 1")
669 time.sleep(1.1)
670 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
671 raise Exception("AP PIN unexpectedly still enabled")
672 check_wps_reg_failure(dev[1], apdev[0], appin)
e4357b19 673
24b7f282 674 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
20c48fd9 675 hapd.request("WPS_AP_PIN random 1")
24b7f282
JM
676 hapd.request("WPS_AP_PIN disable")
677
678 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
679 hapd.request("WPS_AP_PIN set 12345670")
680 hapd.request("WPS_AP_PIN disable")
681
82358a2a
JM
682 if "FAIL" not in hapd.request("WPS_AP_PIN set"):
683 raise Exception("Invalid WPS_AP_PIN accepted")
684 if "FAIL" not in hapd.request("WPS_AP_PIN foo"):
685 raise Exception("Invalid WPS_AP_PIN accepted")
686
ae3ad328 687def test_ap_wps_reg_config(dev, apdev):
4b727c5c 688 """WPS registrar configuring an AP using AP PIN"""
302b7a1b
JM
689 ssid = "test-wps-init-ap-pin"
690 appin = "12345670"
8b8a1864 691 hostapd.add_ap(apdev[0],
302b7a1b
JM
692 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
693 "ap_pin": appin})
694 logger.info("WPS configuration step")
33d0b157 695 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
302b7a1b
JM
696 dev[0].dump_monitor()
697 new_ssid = "wps-new-ssid"
698 new_passphrase = "1234567890"
6edaee9c
JM
699 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
700 new_passphrase)
302b7a1b 701 status = dev[0].get_status()
ae3ad328 702 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
703 raise Exception("Not fully connected")
704 if status['ssid'] != new_ssid:
705 raise Exception("Unexpected SSID")
706 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
707 raise Exception("Unexpected encryption configuration")
708 if status['key_mgmt'] != 'WPA2-PSK':
709 raise Exception("Unexpected key_mgmt")
710
375afd7c
JM
711 logger.info("Re-configure back to open")
712 dev[0].request("REMOVE_NETWORK all")
243dcc4a 713 dev[0].flush_scan_cache()
375afd7c
JM
714 dev[0].dump_monitor()
715 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
716 status = dev[0].get_status()
717 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
718 raise Exception("Not fully connected")
719 if status['ssid'] != "wps-open":
720 raise Exception("Unexpected SSID")
721 if status['key_mgmt'] != 'NONE':
722 raise Exception("Unexpected key_mgmt")
723
4b727c5c
JM
724def test_ap_wps_reg_config_ext_processing(dev, apdev):
725 """WPS registrar configuring an AP with external config processing"""
726 ssid = "test-wps-init-ap-pin"
727 appin = "12345670"
728 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
729 "wps_cred_processing": "1", "ap_pin": appin}
8b8a1864 730 hapd = hostapd.add_ap(apdev[0], params)
33d0b157 731 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4b727c5c
JM
732 new_ssid = "wps-new-ssid"
733 new_passphrase = "1234567890"
734 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
735 new_passphrase, no_wait=True)
736 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
737 if ev is None:
738 raise Exception("WPS registrar operation timed out")
739 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
740 if ev is None:
741 raise Exception("WPS configuration timed out")
742 if "1026" not in ev:
743 raise Exception("AP Settings missing from event")
744 hapd.request("SET wps_cred_processing 0")
745 if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
746 raise Exception("WPS_CONFIG command failed")
5f35a5e2 747 dev[0].wait_connected(timeout=15)
4b727c5c 748
eeefe187
JM
749def test_ap_wps_reg_config_tkip(dev, apdev):
750 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
a1eabc74 751 skip_with_fips(dev[0])
eeefe187
JM
752 ssid = "test-wps-init-ap"
753 appin = "12345670"
8b8a1864 754 hostapd.add_ap(apdev[0],
eeefe187
JM
755 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
756 "ap_pin": appin})
757 logger.info("WPS configuration step")
eeefe187 758 dev[0].request("SET wps_version_number 0x10")
33d0b157 759 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
eeefe187
JM
760 dev[0].dump_monitor()
761 new_ssid = "wps-new-ssid-with-tkip"
762 new_passphrase = "1234567890"
763 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
764 new_passphrase)
765 logger.info("Re-connect to verify WPA2 mixed mode")
766 dev[0].request("DISCONNECT")
767 id = 0
768 dev[0].set_network(id, "pairwise", "CCMP")
769 dev[0].set_network(id, "proto", "RSN")
770 dev[0].connect_network(id)
771 status = dev[0].get_status()
772 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
3c086180 773 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
eeefe187
JM
774 if status['ssid'] != new_ssid:
775 raise Exception("Unexpected SSID")
776 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
777 raise Exception("Unexpected encryption configuration")
778 if status['key_mgmt'] != 'WPA2-PSK':
779 raise Exception("Unexpected key_mgmt")
780
6645ff50
JM
781def test_ap_wps_setup_locked(dev, apdev):
782 """WPS registrar locking up AP setup on AP PIN failures"""
783 ssid = "test-wps-incorrect-ap-pin"
784 appin = "12345670"
6f334bf7
JD
785 hapd = hostapd.add_ap(apdev[0],
786 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
787 "wpa_passphrase": "12345678", "wpa": "2",
788 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
789 "ap_pin": appin})
6645ff50
JM
790 new_ssid = "wps-new-ssid-test"
791 new_passphrase = "1234567890"
792
33d0b157 793 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6645ff50
JM
794 ap_setup_locked=False
795 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
796 dev[0].dump_monitor()
797 logger.info("Try incorrect AP PIN - attempt " + pin)
798 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
799 "CCMP", new_passphrase, no_wait=True)
800 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
801 if ev is None:
802 raise Exception("Timeout on receiving WPS operation failure event")
803 if "CTRL-EVENT-CONNECTED" in ev:
804 raise Exception("Unexpected connection")
805 if "config_error=15" in ev:
806 logger.info("AP Setup Locked")
807 ap_setup_locked=True
808 elif "config_error=18" not in ev:
809 raise Exception("config_error=18 not reported")
5f35a5e2 810 dev[0].wait_disconnected(timeout=10)
6645ff50
JM
811 time.sleep(0.1)
812 if not ap_setup_locked:
813 raise Exception("AP setup was not locked")
24b7f282
JM
814 dev[0].request("WPS_CANCEL")
815 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
816 only_new=True)
817 bss = dev[0].get_bss(apdev[0]['bssid'])
818 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
819 logger.info("BSS: " + str(bss))
820 raise Exception("AP Setup Locked not indicated in scan results")
6645ff50 821
d671a420
JM
822 status = hapd.request("WPS_GET_STATUS")
823 if "Last WPS result: Failed" not in status:
824 raise Exception("WPS failure result not shown correctly")
825 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
826 raise Exception("Peer address not shown correctly")
827
6645ff50
JM
828 time.sleep(0.5)
829 dev[0].dump_monitor()
830 logger.info("WPS provisioning step")
831 pin = dev[0].wps_read_pin()
6645ff50 832 hapd.request("WPS_PIN any " + pin)
33d0b157 833 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
6645ff50
JM
834 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
835 if ev is None:
836 raise Exception("WPS success was not reported")
5f35a5e2 837 dev[0].wait_connected(timeout=30)
6645ff50 838
c1cec68b
JM
839 appin = hapd.request("WPS_AP_PIN random")
840 if "FAIL" in appin:
841 raise Exception("Could not generate random AP PIN")
842 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
843 if ev is None:
844 raise Exception("Failed to unlock AP PIN")
845
33c9b8d8
JM
846def test_ap_wps_setup_locked_timeout(dev, apdev):
847 """WPS re-enabling AP PIN after timeout"""
848 ssid = "test-wps-incorrect-ap-pin"
849 appin = "12345670"
6f334bf7
JD
850 hapd = hostapd.add_ap(apdev[0],
851 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
852 "wpa_passphrase": "12345678", "wpa": "2",
853 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
854 "ap_pin": appin})
33c9b8d8
JM
855 new_ssid = "wps-new-ssid-test"
856 new_passphrase = "1234567890"
857
33d0b157 858 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
33c9b8d8
JM
859 ap_setup_locked=False
860 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
861 dev[0].dump_monitor()
862 logger.info("Try incorrect AP PIN - attempt " + pin)
863 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
864 "CCMP", new_passphrase, no_wait=True)
9ed53f5e 865 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
33c9b8d8
JM
866 if ev is None:
867 raise Exception("Timeout on receiving WPS operation failure event")
868 if "CTRL-EVENT-CONNECTED" in ev:
869 raise Exception("Unexpected connection")
870 if "config_error=15" in ev:
871 logger.info("AP Setup Locked")
872 ap_setup_locked=True
873 break
874 elif "config_error=18" not in ev:
875 raise Exception("config_error=18 not reported")
5f35a5e2 876 dev[0].wait_disconnected(timeout=10)
33c9b8d8
JM
877 time.sleep(0.1)
878 if not ap_setup_locked:
879 raise Exception("AP setup was not locked")
33c9b8d8
JM
880 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
881 if ev is None:
882 raise Exception("AP PIN did not get unlocked on 60 second timeout")
883
4c355e3e
JM
884def test_ap_wps_setup_locked_2(dev, apdev):
885 """WPS AP configured for special ap_setup_locked=2 mode"""
886 ssid = "test-wps-ap-pin"
887 appin = "12345670"
888 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
889 "wpa_passphrase": "12345678", "wpa": "2",
890 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
891 "ap_pin": appin, "ap_setup_locked": "2" }
8b8a1864 892 hapd = hostapd.add_ap(apdev[0], params)
4c355e3e
JM
893 new_ssid = "wps-new-ssid-test"
894 new_passphrase = "1234567890"
895
896 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
897 dev[0].wps_reg(apdev[0]['bssid'], appin)
898 dev[0].request("REMOVE_NETWORK all")
899 dev[0].wait_disconnected()
900
901 hapd.dump_monitor()
902 dev[0].dump_monitor()
903 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
904 "CCMP", new_passphrase, no_wait=True)
905
906 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
907 if ev is None:
908 raise Exception("hostapd did not report WPS failure")
909 if "msg=12 config_error=15" not in ev:
910 raise Exception("Unexpected failure reason (AP): " + ev)
911
912 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
913 if ev is None:
914 raise Exception("Timeout on receiving WPS operation failure event")
915 if "CTRL-EVENT-CONNECTED" in ev:
916 raise Exception("Unexpected connection")
917 if "config_error=15" not in ev:
918 raise Exception("Unexpected failure reason (STA): " + ev)
919 dev[0].request("WPS_CANCEL")
920 dev[0].wait_disconnected()
921
9fd6804d 922@remote_compatible
ae3ad328 923def test_ap_wps_pbc_overlap_2ap(dev, apdev):
302b7a1b 924 """WPS PBC session overlap with two active APs"""
6f334bf7
JD
925 params = { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
926 "wpa_passphrase": "12345678", "wpa": "2",
927 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
928 "wps_independent": "1"}
929 hapd = hostapd.add_ap(apdev[0], params)
930 params = { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
931 "wpa_passphrase": "123456789", "wpa": "2",
932 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
933 "wps_independent": "1"}
934 hapd2 = hostapd.add_ap(apdev[1], params)
302b7a1b 935 hapd.request("WPS_PBC")
302b7a1b
JM
936 hapd2.request("WPS_PBC")
937 logger.info("WPS provisioning step")
84a40841
JM
938 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
939 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
302b7a1b
JM
940 dev[0].request("WPS_PBC")
941 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
942 if ev is None:
943 raise Exception("PBC session overlap not detected")
492c3a91
JM
944 hapd.request("DISABLE")
945 hapd2.request("DISABLE")
946 dev[0].flush_scan_cache()
302b7a1b 947
9fd6804d 948@remote_compatible
ae3ad328 949def test_ap_wps_pbc_overlap_2sta(dev, apdev):
302b7a1b
JM
950 """WPS PBC session overlap with two active STAs"""
951 ssid = "test-wps-pbc-overlap"
6f334bf7
JD
952 hapd = hostapd.add_ap(apdev[0],
953 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
954 "wpa_passphrase": "12345678", "wpa": "2",
955 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
956 logger.info("WPS provisioning step")
957 hapd.request("WPS_PBC")
33d0b157 958 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 959 dev[0].dump_monitor()
33d0b157 960 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 961 dev[1].dump_monitor()
33d0b157
JM
962 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
963 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
302b7a1b
JM
964 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
965 if ev is None:
966 raise Exception("PBC session overlap not detected (dev0)")
967 if "config_error=12" not in ev:
968 raise Exception("PBC session overlap not correctly reported (dev0)")
492c3a91
JM
969 dev[0].request("WPS_CANCEL")
970 dev[0].request("DISCONNECT")
302b7a1b
JM
971 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
972 if ev is None:
973 raise Exception("PBC session overlap not detected (dev1)")
974 if "config_error=12" not in ev:
975 raise Exception("PBC session overlap not correctly reported (dev1)")
492c3a91
JM
976 dev[1].request("WPS_CANCEL")
977 dev[1].request("DISCONNECT")
11e7eeba
JM
978 hapd.request("WPS_CANCEL")
979 ret = hapd.request("WPS_PBC")
980 if "FAIL" not in ret:
981 raise Exception("PBC mode allowed to be started while PBC overlap still active")
492c3a91
JM
982 hapd.request("DISABLE")
983 dev[0].flush_scan_cache()
984 dev[1].flush_scan_cache()
6edaee9c 985
9fd6804d 986@remote_compatible
71afe834
JM
987def test_ap_wps_cancel(dev, apdev):
988 """WPS AP cancelling enabled config method"""
989 ssid = "test-wps-ap-cancel"
6f334bf7
JD
990 hapd = hostapd.add_ap(apdev[0],
991 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
992 "wpa_passphrase": "12345678", "wpa": "2",
993 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
71afe834 994 bssid = apdev[0]['bssid']
71afe834
JM
995
996 logger.info("Verify PBC enable/cancel")
997 hapd.request("WPS_PBC")
71afe834 998 dev[0].scan(freq="2412")
84a40841 999 dev[0].scan(freq="2412")
71afe834
JM
1000 bss = dev[0].get_bss(apdev[0]['bssid'])
1001 if "[WPS-PBC]" not in bss['flags']:
1002 raise Exception("WPS-PBC flag missing")
1003 if "FAIL" in hapd.request("WPS_CANCEL"):
1004 raise Exception("WPS_CANCEL failed")
1005 dev[0].scan(freq="2412")
84a40841 1006 dev[0].scan(freq="2412")
71afe834
JM
1007 bss = dev[0].get_bss(apdev[0]['bssid'])
1008 if "[WPS-PBC]" in bss['flags']:
1009 raise Exception("WPS-PBC flag not cleared")
1010
1011 logger.info("Verify PIN enable/cancel")
1012 hapd.request("WPS_PIN any 12345670")
1013 dev[0].scan(freq="2412")
84a40841 1014 dev[0].scan(freq="2412")
71afe834
JM
1015 bss = dev[0].get_bss(apdev[0]['bssid'])
1016 if "[WPS-AUTH]" not in bss['flags']:
1017 raise Exception("WPS-AUTH flag missing")
1018 if "FAIL" in hapd.request("WPS_CANCEL"):
1019 raise Exception("WPS_CANCEL failed")
1020 dev[0].scan(freq="2412")
84a40841 1021 dev[0].scan(freq="2412")
71afe834
JM
1022 bss = dev[0].get_bss(apdev[0]['bssid'])
1023 if "[WPS-AUTH]" in bss['flags']:
1024 raise Exception("WPS-AUTH flag not cleared")
1025
6edaee9c
JM
1026def test_ap_wps_er_add_enrollee(dev, apdev):
1027 """WPS ER configuring AP and adding a new enrollee using PIN"""
be9f1562
JM
1028 try:
1029 _test_ap_wps_er_add_enrollee(dev, apdev)
1030 finally:
1031 dev[0].request("WPS_ER_STOP")
1032
1033def _test_ap_wps_er_add_enrollee(dev, apdev):
6edaee9c
JM
1034 ssid = "wps-er-add-enrollee"
1035 ap_pin = "12345670"
1036 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1037 hostapd.add_ap(apdev[0],
6edaee9c
JM
1038 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
1039 "device_name": "Wireless AP", "manufacturer": "Company",
1040 "model_name": "WAP", "model_number": "123",
1041 "serial_number": "12345", "device_type": "6-0050F204-1",
1042 "os_version": "01020300",
24b7f282 1043 'friendly_name': "WPS AP - <>&'\" - TEST",
6edaee9c
JM
1044 "config_methods": "label push_button",
1045 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1046 logger.info("WPS configuration step")
1047 new_passphrase = "1234567890"
1048 dev[0].dump_monitor()
33d0b157 1049 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c
JM
1050 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1051 new_passphrase)
1052 status = dev[0].get_status()
1053 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1054 raise Exception("Not fully connected")
1055 if status['ssid'] != ssid:
1056 raise Exception("Unexpected SSID")
1057 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1058 raise Exception("Unexpected encryption configuration")
1059 if status['key_mgmt'] != 'WPA2-PSK':
1060 raise Exception("Unexpected key_mgmt")
1061
1062 logger.info("Start ER")
1063 dev[0].request("WPS_ER_START ifname=lo")
1064 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1065 if ev is None:
1066 raise Exception("AP discovery timed out")
1067 if ap_uuid not in ev:
1068 raise Exception("Expected AP UUID not found")
24b7f282
JM
1069 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1070 raise Exception("Expected friendly name not found")
6edaee9c
JM
1071
1072 logger.info("Learn AP configuration through UPnP")
1073 dev[0].dump_monitor()
1074 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1075 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1076 if ev is None:
1077 raise Exception("AP learn timed out")
1078 if ap_uuid not in ev:
1079 raise Exception("Expected AP UUID not in settings")
1080 if "ssid=" + ssid not in ev:
1081 raise Exception("Expected SSID not in settings")
1082 if "key=" + new_passphrase not in ev:
1083 raise Exception("Expected passphrase not in settings")
33d0b157
JM
1084 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1085 if ev is None:
1086 raise Exception("WPS-FAIL after AP learn timed out")
1087 time.sleep(0.1)
6edaee9c
JM
1088
1089 logger.info("Add Enrollee using ER")
1090 pin = dev[1].wps_read_pin()
1091 dev[0].dump_monitor()
1092 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
33d0b157 1093 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1094 dev[1].dump_monitor()
33d0b157 1095 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
846be889 1096 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
6edaee9c
JM
1097 if ev is None:
1098 raise Exception("Enrollee did not report success")
5f35a5e2 1099 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1100 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1101 if ev is None:
1102 raise Exception("WPS ER did not report success")
1103 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1104
11c26f1b
JM
1105 logger.info("Add a specific Enrollee using ER")
1106 pin = dev[2].wps_read_pin()
1107 addr2 = dev[2].p2p_interface_addr()
1108 dev[0].dump_monitor()
33d0b157 1109 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
11c26f1b 1110 dev[2].dump_monitor()
33d0b157 1111 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
11c26f1b
JM
1112 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1113 if ev is None:
1114 raise Exception("Enrollee not seen")
1115 if addr2 not in ev:
1116 raise Exception("Unexpected Enrollee MAC address")
1117 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
5f35a5e2 1118 dev[2].wait_connected(timeout=30)
11c26f1b
JM
1119 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1120 if ev is None:
1121 raise Exception("WPS ER did not report success")
1122
38ae43de
JM
1123 logger.info("Verify registrar selection behavior")
1124 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1125 dev[1].request("DISCONNECT")
5f35a5e2 1126 dev[1].wait_disconnected(timeout=10)
84a40841 1127 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
38ae43de
JM
1128 dev[1].scan(freq="2412")
1129 bss = dev[1].get_bss(apdev[0]['bssid'])
1130 if "[WPS-AUTH]" not in bss['flags']:
321c7f60
JM
1131 # It is possible for scan to miss an update especially when running
1132 # tests under load with multiple VMs, so allow another attempt.
1133 dev[1].scan(freq="2412")
1134 bss = dev[1].get_bss(apdev[0]['bssid'])
1135 if "[WPS-AUTH]" not in bss['flags']:
1136 raise Exception("WPS-AUTH flag missing")
38ae43de
JM
1137
1138 logger.info("Stop ER")
1139 dev[0].dump_monitor()
1140 dev[0].request("WPS_ER_STOP")
1141 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1142 if ev is None:
1143 raise Exception("WPS ER unsubscription timed out")
8697cbc0 1144 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
befd671c 1145 # a bit before verifying that the scan results have changed.
8697cbc0 1146 time.sleep(0.2)
38ae43de 1147
befd671c
JM
1148 for i in range(0, 10):
1149 dev[1].request("BSS_FLUSH 0")
1150 dev[1].scan(freq="2412", only_new=True)
1151 bss = dev[1].get_bss(apdev[0]['bssid'])
1152 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1153 break
1154 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1155 time.sleep(0.1)
38ae43de
JM
1156 if "[WPS-AUTH]" in bss['flags']:
1157 raise Exception("WPS-AUTH flag not removed")
1158
c965ae03
JM
1159def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1160 """WPS ER adding a new enrollee identified by UUID"""
1161 try:
1162 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1163 finally:
1164 dev[0].request("WPS_ER_STOP")
1165
1166def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1167 ssid = "wps-er-add-enrollee"
1168 ap_pin = "12345670"
1169 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1170 hostapd.add_ap(apdev[0],
c965ae03
JM
1171 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1172 "wpa_passphrase": "12345678", "wpa": "2",
1173 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1174 "device_name": "Wireless AP", "manufacturer": "Company",
1175 "model_name": "WAP", "model_number": "123",
1176 "serial_number": "12345", "device_type": "6-0050F204-1",
1177 "os_version": "01020300",
1178 "config_methods": "label push_button",
1179 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1180 logger.info("WPS configuration step")
1181 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1182 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1183
1184 logger.info("Start ER")
1185 dev[0].request("WPS_ER_START ifname=lo")
1186 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1187 if ev is None:
1188 raise Exception("AP discovery timed out")
1189 if ap_uuid not in ev:
1190 raise Exception("Expected AP UUID not found")
1191
1192 logger.info("Learn AP configuration through UPnP")
1193 dev[0].dump_monitor()
1194 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1195 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1196 if ev is None:
1197 raise Exception("AP learn timed out")
1198 if ap_uuid not in ev:
1199 raise Exception("Expected AP UUID not in settings")
1200 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1201 if ev is None:
1202 raise Exception("WPS-FAIL after AP learn timed out")
1203 time.sleep(0.1)
1204
1205 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1206 addr1 = dev[1].p2p_interface_addr()
1207 dev[0].dump_monitor()
1208 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1209 dev[1].dump_monitor()
1210 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1211 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1212 if ev is None:
1213 raise Exception("Enrollee not seen")
1214 if addr1 not in ev:
1215 raise Exception("Unexpected Enrollee MAC address")
1216 uuid = ev.split(' ')[1]
1217 dev[0].request("WPS_ER_PBC " + uuid)
1218 dev[1].wait_connected(timeout=30)
1219 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1220 if ev is None:
1221 raise Exception("WPS ER did not report success")
1222
1223 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1224 pin = dev[2].wps_read_pin()
1225 addr2 = dev[2].p2p_interface_addr()
1226 dev[0].dump_monitor()
1227 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1228 dev[2].dump_monitor()
1229 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1230 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1231 if ev is None:
1232 raise Exception("Enrollee not seen")
1233 if addr2 not in ev:
1234 raise Exception("Unexpected Enrollee MAC address")
1235 uuid = ev.split(' ')[1]
1236 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1237 dev[2].wait_connected(timeout=30)
1238 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1239 if ev is None:
1240 raise Exception("WPS ER did not report success")
1241
ea982de1
JM
1242 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1243 if ev is None:
1244 raise Exception("No Enrollee STA entry timeout seen")
1245
c965ae03
JM
1246 logger.info("Stop ER")
1247 dev[0].dump_monitor()
1248 dev[0].request("WPS_ER_STOP")
1249
61c3d464
JM
1250def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1251 """Multiple WPS ERs adding a new enrollee using PIN"""
1252 try:
1253 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1254 finally:
d887ed3f
JM
1255 for i in range(2):
1256 dev[i].request("WPS_ER_STOP")
61c3d464
JM
1257
1258def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1259 ssid = "wps-er-add-enrollee"
1260 ap_pin = "12345670"
1261 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1262 hostapd.add_ap(apdev[0],
61c3d464
JM
1263 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1264 "wpa_passphrase": "12345678", "wpa": "2",
1265 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1266 "device_name": "Wireless AP", "manufacturer": "Company",
1267 "model_name": "WAP", "model_number": "123",
1268 "serial_number": "12345", "device_type": "6-0050F204-1",
1269 "os_version": "01020300",
1270 'friendly_name': "WPS AP",
1271 "config_methods": "label push_button",
1272 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1273
1274 for i in range(2):
1275 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1276 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
6a5f578c 1277 for i in range(2):
61c3d464
JM
1278 dev[i].request("WPS_ER_START ifname=lo")
1279 for i in range(2):
1280 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1281 if ev is None:
1282 raise Exception("AP discovery timed out")
1283 dev[i].dump_monitor()
6a5f578c 1284 for i in range(2):
61c3d464 1285 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
6a5f578c 1286 for i in range(2):
61c3d464
JM
1287 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1288 if ev is None:
1289 raise Exception("AP learn timed out")
1290 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1291 if ev is None:
1292 raise Exception("WPS-FAIL after AP learn timed out")
1293
1294 time.sleep(0.1)
1295
1296 pin = dev[2].wps_read_pin()
1297 addr = dev[2].own_addr()
1298 dev[0].dump_monitor()
1299 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1300 dev[1].dump_monitor()
1301 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1302
1303 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1304 dev[2].dump_monitor()
1305 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1306 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1307 if ev is None:
1308 raise Exception("Enrollee did not report success")
1309 dev[2].wait_connected(timeout=15)
1310
6edaee9c
JM
1311def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1312 """WPS ER connected to AP and adding a new enrollee using PBC"""
be9f1562
JM
1313 try:
1314 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1315 finally:
1316 dev[0].request("WPS_ER_STOP")
1317
1318def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
6edaee9c
JM
1319 ssid = "wps-er-add-enrollee-pbc"
1320 ap_pin = "12345670"
1321 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1322 hostapd.add_ap(apdev[0],
6edaee9c
JM
1323 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1324 "wpa_passphrase": "12345678", "wpa": "2",
1325 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1326 "device_name": "Wireless AP", "manufacturer": "Company",
1327 "model_name": "WAP", "model_number": "123",
1328 "serial_number": "12345", "device_type": "6-0050F204-1",
1329 "os_version": "01020300",
1330 "config_methods": "label push_button",
1331 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1332 logger.info("Learn AP configuration")
33d0b157 1333 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1334 dev[0].dump_monitor()
6edaee9c
JM
1335 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1336 status = dev[0].get_status()
1337 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1338 raise Exception("Not fully connected")
1339
1340 logger.info("Start ER")
1341 dev[0].request("WPS_ER_START ifname=lo")
1342 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1343 if ev is None:
1344 raise Exception("AP discovery timed out")
1345 if ap_uuid not in ev:
1346 raise Exception("Expected AP UUID not found")
1347
d6b916c9
JM
1348 enrollee = dev[1].p2p_interface_addr()
1349
1350 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1351 raise Exception("Unknown UUID not reported")
6edaee9c
JM
1352
1353 logger.info("Add Enrollee using ER and PBC")
1354 dev[0].dump_monitor()
6edaee9c
JM
1355 dev[1].dump_monitor()
1356 dev[1].request("WPS_PBC")
1357
8674c022
JM
1358 for i in range(0, 2):
1359 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1360 if ev is None:
1361 raise Exception("Enrollee discovery timed out")
1362 if enrollee in ev:
1363 break
1364 if i == 1:
1365 raise Exception("Expected Enrollee not found")
d6b916c9
JM
1366 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1367 raise Exception("Unknown UUID not reported")
1368 logger.info("Use learned network configuration on ER")
1369 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1370 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1371 raise Exception("WPS_ER_PBC failed")
6edaee9c
JM
1372
1373 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1374 if ev is None:
1375 raise Exception("Enrollee did not report success")
5f35a5e2 1376 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1377 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1378 if ev is None:
1379 raise Exception("WPS ER did not report success")
1380 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
bff3ac5b 1381
d6b916c9
JM
1382def test_ap_wps_er_pbc_overlap(dev, apdev):
1383 """WPS ER connected to AP and PBC session overlap"""
be9f1562
JM
1384 try:
1385 _test_ap_wps_er_pbc_overlap(dev, apdev)
1386 finally:
1387 dev[0].request("WPS_ER_STOP")
1388
1389def _test_ap_wps_er_pbc_overlap(dev, apdev):
d6b916c9
JM
1390 ssid = "wps-er-add-enrollee-pbc"
1391 ap_pin = "12345670"
1392 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1393 hostapd.add_ap(apdev[0],
d6b916c9
JM
1394 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1395 "wpa_passphrase": "12345678", "wpa": "2",
1396 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1397 "device_name": "Wireless AP", "manufacturer": "Company",
1398 "model_name": "WAP", "model_number": "123",
1399 "serial_number": "12345", "device_type": "6-0050F204-1",
1400 "os_version": "01020300",
1401 "config_methods": "label push_button",
1402 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1403 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1404 dev[0].dump_monitor()
1405 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1406
fba25c99
JM
1407 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1408 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1409 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1410 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1411
d6b916c9
JM
1412 dev[0].dump_monitor()
1413 dev[0].request("WPS_ER_START ifname=lo")
1414
1415 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1416 if ev is None:
1417 raise Exception("AP discovery timed out")
1418 if ap_uuid not in ev:
1419 raise Exception("Expected AP UUID not found")
1420
800bcf4e
JM
1421 # verify BSSID selection of the AP instead of UUID
1422 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1423 raise Exception("Could not select AP based on BSSID")
1424
fba25c99 1425 dev[0].dump_monitor()
d6b916c9
JM
1426 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1427 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1428 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1429 if ev is None:
1430 raise Exception("PBC scan failed")
1431 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1432 if ev is None:
1433 raise Exception("PBC scan failed")
fba25c99
JM
1434 found1 = False
1435 found2 = False
1436 addr1 = dev[1].own_addr()
1437 addr2 = dev[2].own_addr()
1438 for i in range(3):
d6b916c9
JM
1439 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1440 if ev is None:
1441 raise Exception("Enrollee discovery timed out")
fba25c99
JM
1442 if addr1 in ev:
1443 found1 = True
1444 if found2:
1445 break
1446 if addr2 in ev:
1447 found2 = True
1448 if found1:
1449 break
d6b916c9
JM
1450 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1451 raise Exception("PBC overlap not reported")
1452 dev[1].request("WPS_CANCEL")
1453 dev[2].request("WPS_CANCEL")
1454 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1455 raise Exception("Invalid WPS_ER_PBC accepted")
1456
1f020f5e
JM
1457def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1458 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
be9f1562
JM
1459 try:
1460 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1461 finally:
1462 dev[0].request("WPS_ER_STOP")
1463
1464def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1f020f5e
JM
1465 ssid = "wps-er-add-enrollee-pbc"
1466 ap_pin = "12345670"
1467 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1468 hostapd.add_ap(apdev[0],
1f020f5e
JM
1469 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1470 "wpa_passphrase": "12345678", "wpa": "2",
1471 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1472 "device_name": "Wireless AP", "manufacturer": "Company",
1473 "model_name": "WAP", "model_number": "123",
1474 "serial_number": "12345", "device_type": "6-0050F204-1",
1475 "os_version": "01020300",
1476 "config_methods": "label push_button",
1477 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1478 logger.info("Learn AP configuration")
1479 dev[0].request("SET wps_version_number 0x10")
33d0b157 1480 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e
JM
1481 dev[0].dump_monitor()
1482 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1483 status = dev[0].get_status()
1484 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1485 raise Exception("Not fully connected")
1486
1487 logger.info("Start ER")
1488 dev[0].request("WPS_ER_START ifname=lo")
1489 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1490 if ev is None:
1491 raise Exception("AP discovery timed out")
1492 if ap_uuid not in ev:
1493 raise Exception("Expected AP UUID not found")
1494
1495 logger.info("Use learned network configuration on ER")
1496 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1497
1498 logger.info("Add Enrollee using ER and PIN")
1499 enrollee = dev[1].p2p_interface_addr()
1500 pin = dev[1].wps_read_pin()
1501 dev[0].dump_monitor()
1502 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
33d0b157 1503 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e 1504 dev[1].dump_monitor()
33d0b157 1505 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1506 dev[1].wait_connected(timeout=30)
1f020f5e
JM
1507 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1508 if ev is None:
1509 raise Exception("WPS ER did not report success")
1510
9fd6804d 1511@remote_compatible
be923570
JM
1512def test_ap_wps_er_config_ap(dev, apdev):
1513 """WPS ER configuring AP over UPnP"""
be9f1562
JM
1514 try:
1515 _test_ap_wps_er_config_ap(dev, apdev)
1516 finally:
1517 dev[0].request("WPS_ER_STOP")
1518
1519def _test_ap_wps_er_config_ap(dev, apdev):
be923570
JM
1520 ssid = "wps-er-ap-config"
1521 ap_pin = "12345670"
1522 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1523 hostapd.add_ap(apdev[0],
be923570
JM
1524 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1525 "wpa_passphrase": "12345678", "wpa": "2",
1526 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1527 "device_name": "Wireless AP", "manufacturer": "Company",
1528 "model_name": "WAP", "model_number": "123",
1529 "serial_number": "12345", "device_type": "6-0050F204-1",
1530 "os_version": "01020300",
1531 "config_methods": "label push_button",
1532 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1533
1534 logger.info("Connect ER to the AP")
1535 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1536
1537 logger.info("WPS configuration step")
1538 dev[0].request("WPS_ER_START ifname=lo")
1539 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1540 if ev is None:
1541 raise Exception("AP discovery timed out")
1542 if ap_uuid not in ev:
1543 raise Exception("Expected AP UUID not found")
1544 new_passphrase = "1234567890"
1545 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1546 ssid.encode("hex") + " WPA2PSK CCMP " +
1547 new_passphrase.encode("hex"))
1548 ev = dev[0].wait_event(["WPS-SUCCESS"])
1549 if ev is None:
1550 raise Exception("WPS ER configuration operation timed out")
5f35a5e2 1551 dev[0].wait_disconnected(timeout=10)
be923570
JM
1552 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1553
8f8c2fe8
JM
1554 logger.info("WPS ER restart")
1555 dev[0].request("WPS_ER_START")
1556 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1557 if ev is None:
1558 raise Exception("AP discovery timed out on ER restart")
1559 if ap_uuid not in ev:
1560 raise Exception("Expected AP UUID not found on ER restart")
1561 if "OK" not in dev[0].request("WPS_ER_STOP"):
1562 raise Exception("WPS_ER_STOP failed")
1563 if "OK" not in dev[0].request("WPS_ER_STOP"):
1564 raise Exception("WPS_ER_STOP failed")
1565
9fd6804d 1566@remote_compatible
6aaa661a
JM
1567def test_ap_wps_er_cache_ap_settings(dev, apdev):
1568 """WPS ER caching AP settings"""
1569 try:
1570 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1571 finally:
1572 dev[0].request("WPS_ER_STOP")
1573
1574def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1575 ssid = "wps-er-add-enrollee"
1576 ap_pin = "12345670"
1577 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1578 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1579 "wpa_passphrase": "12345678", "wpa": "2",
1580 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1581 "device_name": "Wireless AP", "manufacturer": "Company",
1582 "model_name": "WAP", "model_number": "123",
1583 "serial_number": "12345", "device_type": "6-0050F204-1",
1584 "os_version": "01020300",
1585 "config_methods": "label push_button",
1586 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1587 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a
JM
1588 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1589 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1590 id = int(dev[0].list_networks()[0]['id'])
1591 dev[0].set_network(id, "scan_freq", "2412")
1592
1593 dev[0].request("WPS_ER_START ifname=lo")
1594 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1595 if ev is None:
1596 raise Exception("AP discovery timed out")
1597 if ap_uuid not in ev:
1598 raise Exception("Expected AP UUID not found")
1599
1600 dev[0].dump_monitor()
1601 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1602 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1603 if ev is None:
1604 raise Exception("AP learn timed out")
1605 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1606 if ev is None:
1607 raise Exception("WPS-FAIL after AP learn timed out")
1608 time.sleep(0.1)
1609
1610 hapd.disable()
1611
1612 for i in range(2):
1613 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1614 "CTRL-EVENT-DISCONNECTED" ],
1615 timeout=15)
1616 if ev is None:
1617 raise Exception("AP removal or disconnection timed out")
1618
8b8a1864 1619 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a
JM
1620 for i in range(2):
1621 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1622 timeout=15)
1623 if ev is None:
1624 raise Exception("AP discovery or connection timed out")
1625
1626 pin = dev[1].wps_read_pin()
1627 dev[0].dump_monitor()
1628 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1629
1630 time.sleep(0.2)
1631
1632 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1633 dev[1].dump_monitor()
1634 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1635 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1636 if ev is None:
1637 raise Exception("Enrollee did not report success")
1638 dev[1].wait_connected(timeout=15)
1639 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1640 if ev is None:
1641 raise Exception("WPS ER did not report success")
1642
1643 dev[0].dump_monitor()
1644 dev[0].request("WPS_ER_STOP")
1645
d840350a
JM
1646def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1647 """WPS ER caching AP settings (OOM)"""
1648 try:
1649 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1650 finally:
1651 dev[0].request("WPS_ER_STOP")
1652
1653def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1654 ssid = "wps-er-add-enrollee"
1655 ap_pin = "12345670"
1656 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1657 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1658 "wpa_passphrase": "12345678", "wpa": "2",
1659 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1660 "device_name": "Wireless AP", "manufacturer": "Company",
1661 "model_name": "WAP", "model_number": "123",
1662 "serial_number": "12345", "device_type": "6-0050F204-1",
1663 "os_version": "01020300",
1664 "config_methods": "label push_button",
1665 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1666 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1667 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1668 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1669 id = int(dev[0].list_networks()[0]['id'])
1670 dev[0].set_network(id, "scan_freq", "2412")
1671
1672 dev[0].request("WPS_ER_START ifname=lo")
1673 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1674 if ev is None:
1675 raise Exception("AP discovery timed out")
1676 if ap_uuid not in ev:
1677 raise Exception("Expected AP UUID not found")
1678
1679 dev[0].dump_monitor()
1680 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1681 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1682 if ev is None:
1683 raise Exception("AP learn timed out")
1684 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1685 if ev is None:
1686 raise Exception("WPS-FAIL after AP learn timed out")
1687 time.sleep(0.1)
1688
1689 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1690 hapd.disable()
1691
1692 for i in range(2):
1693 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1694 "CTRL-EVENT-DISCONNECTED" ],
1695 timeout=15)
1696 if ev is None:
1697 raise Exception("AP removal or disconnection timed out")
1698
8b8a1864 1699 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1700 for i in range(2):
1701 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1702 timeout=15)
1703 if ev is None:
1704 raise Exception("AP discovery or connection timed out")
1705
1706 dev[0].request("WPS_ER_STOP")
1707
1708def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1709 """WPS ER caching AP settings (OOM 2)"""
1710 try:
1711 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1712 finally:
1713 dev[0].request("WPS_ER_STOP")
1714
1715def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1716 ssid = "wps-er-add-enrollee"
1717 ap_pin = "12345670"
1718 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1719 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1720 "wpa_passphrase": "12345678", "wpa": "2",
1721 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1722 "device_name": "Wireless AP", "manufacturer": "Company",
1723 "model_name": "WAP", "model_number": "123",
1724 "serial_number": "12345", "device_type": "6-0050F204-1",
1725 "os_version": "01020300",
1726 "config_methods": "label push_button",
1727 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1728 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1729 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1730 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1731 id = int(dev[0].list_networks()[0]['id'])
1732 dev[0].set_network(id, "scan_freq", "2412")
1733
1734 dev[0].request("WPS_ER_START ifname=lo")
1735 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1736 if ev is None:
1737 raise Exception("AP discovery timed out")
1738 if ap_uuid not in ev:
1739 raise Exception("Expected AP UUID not found")
1740
1741 dev[0].dump_monitor()
1742 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1743 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1744 if ev is None:
1745 raise Exception("AP learn timed out")
1746 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1747 if ev is None:
1748 raise Exception("WPS-FAIL after AP learn timed out")
1749 time.sleep(0.1)
1750
1751 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1752 hapd.disable()
1753
1754 for i in range(2):
1755 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1756 "CTRL-EVENT-DISCONNECTED" ],
1757 timeout=15)
1758 if ev is None:
1759 raise Exception("AP removal or disconnection timed out")
1760
8b8a1864 1761 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1762 for i in range(2):
1763 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1764 timeout=15)
1765 if ev is None:
1766 raise Exception("AP discovery or connection timed out")
1767
1768 dev[0].request("WPS_ER_STOP")
1769
eb95ced2
JM
1770def test_ap_wps_er_subscribe_oom(dev, apdev):
1771 """WPS ER subscribe OOM"""
1772 try:
1773 _test_ap_wps_er_subscribe_oom(dev, apdev)
1774 finally:
1775 dev[0].request("WPS_ER_STOP")
1776
1777def _test_ap_wps_er_subscribe_oom(dev, apdev):
1778 ssid = "wps-er-add-enrollee"
1779 ap_pin = "12345670"
1780 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1781 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1782 "wpa_passphrase": "12345678", "wpa": "2",
1783 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1784 "device_name": "Wireless AP", "manufacturer": "Company",
1785 "model_name": "WAP", "model_number": "123",
1786 "serial_number": "12345", "device_type": "6-0050F204-1",
1787 "os_version": "01020300",
1788 "config_methods": "label push_button",
1789 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1790 hapd = hostapd.add_ap(apdev[0], params)
eb95ced2
JM
1791 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1792 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1793 id = int(dev[0].list_networks()[0]['id'])
1794 dev[0].set_network(id, "scan_freq", "2412")
1795
1796 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1797 dev[0].request("WPS_ER_START ifname=lo")
1798 for i in range(50):
1799 res = dev[0].request("GET_ALLOC_FAIL")
1800 if res.startswith("0:"):
1801 break
1802 time.sleep(0.1)
1803 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1804 if ev:
1805 raise Exception("Unexpected AP discovery during OOM")
1806
1807 dev[0].request("WPS_ER_STOP")
1808
db9c88eb
JM
1809def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1810 """WPS ER SetSelectedRegistrar OOM"""
1811 try:
1812 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1813 finally:
1814 dev[0].request("WPS_ER_STOP")
1815
1816def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1817 ssid = "wps-er-add-enrollee"
1818 ap_pin = "12345670"
1819 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1820 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1821 "wpa_passphrase": "12345678", "wpa": "2",
1822 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1823 "device_name": "Wireless AP", "manufacturer": "Company",
1824 "model_name": "WAP", "model_number": "123",
1825 "serial_number": "12345", "device_type": "6-0050F204-1",
1826 "os_version": "01020300",
1827 "config_methods": "label push_button",
1828 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1829 hapd = hostapd.add_ap(apdev[0], params)
db9c88eb
JM
1830 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1831 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1832
1833 dev[0].request("WPS_ER_START ifname=lo")
1834 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1835 if ev is None:
1836 raise Exception("AP not discovered")
1837
1838 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1839 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1840 if ev is None:
1841 raise Exception("AP learn timed out")
1842 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1843 if ev is None:
1844 raise Exception("WPS-FAIL timed out")
1845 time.sleep(0.1)
1846
1847 for func in [ "http_client_url_parse;wps_er_send_set_sel_reg",
1848 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1849 "http_client_addr;wps_er_send_set_sel_reg",
1850 "wpabuf_alloc;wps_er_set_sel_reg" ]:
1851 with alloc_fail(dev[0], 1, func):
1852 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1853 raise Exception("WPS_ER_PBC failed")
1854 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1855 if ev is None:
1856 raise Exception("WPS-PBC-ACTIVE not seen")
1857
1858 dev[0].request("WPS_ER_STOP")
1859
9fd6804d 1860@remote_compatible
ae3eacf7
JM
1861def test_ap_wps_er_learn_oom(dev, apdev):
1862 """WPS ER learn OOM"""
1863 try:
1864 _test_ap_wps_er_learn_oom(dev, apdev)
1865 finally:
1866 dev[0].request("WPS_ER_STOP")
1867
1868def _test_ap_wps_er_learn_oom(dev, apdev):
1869 ssid = "wps-er-add-enrollee"
1870 ap_pin = "12345670"
1871 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1872 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1873 "wpa_passphrase": "12345678", "wpa": "2",
1874 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1875 "device_name": "Wireless AP", "manufacturer": "Company",
1876 "model_name": "WAP", "model_number": "123",
1877 "serial_number": "12345", "device_type": "6-0050F204-1",
1878 "os_version": "01020300",
1879 "config_methods": "label push_button",
1880 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1881 hapd = hostapd.add_ap(apdev[0], params)
ae3eacf7
JM
1882 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1883 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1884
1885 dev[0].request("WPS_ER_START ifname=lo")
1886 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1887 if ev is None:
1888 raise Exception("AP not discovered")
1889
1890 for func in [ "wps_er_http_put_message_cb",
1891 "xml_get_base64_item;wps_er_http_put_message_cb",
1892 "http_client_url_parse;wps_er_ap_put_message",
1893 "wps_er_soap_hdr;wps_er_ap_put_message",
1894 "http_client_addr;wps_er_ap_put_message" ]:
1895 with alloc_fail(dev[0], 1, func):
1896 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1897 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1898 if ev is not None:
1899 raise Exception("AP learn succeeded during OOM")
1900
1901 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1902 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1903 if ev is None:
1904 raise Exception("AP learn did not succeed")
1905
1906 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1907 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1908
1909 dev[0].request("WPS_ER_STOP")
1910
bff3ac5b
JM
1911def test_ap_wps_fragmentation(dev, apdev):
1912 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1913 ssid = "test-wps-fragmentation"
9602b355 1914 appin = "12345670"
6f334bf7
JD
1915 hapd = hostapd.add_ap(apdev[0],
1916 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1917 "wpa_passphrase": "12345678", "wpa": "3",
1918 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1919 "wpa_pairwise": "TKIP", "ap_pin": appin,
1920 "fragment_size": "50" })
9602b355 1921 logger.info("WPS provisioning step (PBC)")
bff3ac5b 1922 hapd.request("WPS_PBC")
33d0b157 1923 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
bff3ac5b
JM
1924 dev[0].dump_monitor()
1925 dev[0].request("SET wps_fragment_size 50")
33d0b157 1926 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1927 dev[0].wait_connected(timeout=30)
bff3ac5b
JM
1928 status = dev[0].get_status()
1929 if status['wpa_state'] != 'COMPLETED':
9602b355
JM
1930 raise Exception("Not fully connected")
1931 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1932 raise Exception("Unexpected encryption configuration")
1933 if status['key_mgmt'] != 'WPA2-PSK':
1934 raise Exception("Unexpected key_mgmt")
1935
1936 logger.info("WPS provisioning step (PIN)")
1937 pin = dev[1].wps_read_pin()
1938 hapd.request("WPS_PIN any " + pin)
33d0b157 1939 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355 1940 dev[1].request("SET wps_fragment_size 50")
33d0b157 1941 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1942 dev[1].wait_connected(timeout=30)
9602b355
JM
1943 status = dev[1].get_status()
1944 if status['wpa_state'] != 'COMPLETED':
1945 raise Exception("Not fully connected")
1946 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1947 raise Exception("Unexpected encryption configuration")
1948 if status['key_mgmt'] != 'WPA2-PSK':
1949 raise Exception("Unexpected key_mgmt")
1950
1951 logger.info("WPS connection as registrar")
33d0b157 1952 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355
JM
1953 dev[2].request("SET wps_fragment_size 50")
1954 dev[2].wps_reg(apdev[0]['bssid'], appin)
1955 status = dev[2].get_status()
1956 if status['wpa_state'] != 'COMPLETED':
bff3ac5b
JM
1957 raise Exception("Not fully connected")
1958 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1959 raise Exception("Unexpected encryption configuration")
1960 if status['key_mgmt'] != 'WPA2-PSK':
1961 raise Exception("Unexpected key_mgmt")
10ea6848 1962
9fd6804d 1963@remote_compatible
10ea6848
JM
1964def test_ap_wps_new_version_sta(dev, apdev):
1965 """WPS compatibility with new version number on the station"""
1966 ssid = "test-wps-ver"
6f334bf7
JD
1967 hapd = hostapd.add_ap(apdev[0],
1968 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1969 "wpa_passphrase": "12345678", "wpa": "2",
1970 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
10ea6848
JM
1971 logger.info("WPS provisioning step")
1972 hapd.request("WPS_PBC")
33d0b157 1973 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848
JM
1974 dev[0].dump_monitor()
1975 dev[0].request("SET wps_version_number 0x43")
dccafedb 1976 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
33d0b157 1977 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1978 dev[0].wait_connected(timeout=30)
10ea6848 1979
9fd6804d 1980@remote_compatible
10ea6848
JM
1981def test_ap_wps_new_version_ap(dev, apdev):
1982 """WPS compatibility with new version number on the AP"""
1983 ssid = "test-wps-ver"
6f334bf7
JD
1984 hapd = hostapd.add_ap(apdev[0],
1985 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1986 "wpa_passphrase": "12345678", "wpa": "2",
1987 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
10ea6848
JM
1988 logger.info("WPS provisioning step")
1989 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
1990 raise Exception("Failed to enable test functionality")
1991 hapd.request("WPS_PBC")
33d0b157 1992 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848 1993 dev[0].dump_monitor()
33d0b157 1994 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1995 dev[0].wait_connected(timeout=30)
10ea6848 1996 hapd.request("SET wps_version_number 0x20")
3bdf7d7f 1997
9fd6804d 1998@remote_compatible
3bdf7d7f
JM
1999def test_ap_wps_check_pin(dev, apdev):
2000 """Verify PIN checking through control interface"""
6f334bf7
JD
2001 hapd = hostapd.add_ap(apdev[0],
2002 { "ssid": "wps", "eap_server": "1", "wps_state": "2",
2003 "wpa_passphrase": "12345678", "wpa": "2",
2004 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
3bdf7d7f
JM
2005 for t in [ ("12345670", "12345670"),
2006 ("12345678", "FAIL-CHECKSUM"),
df58939c 2007 ("12345", "FAIL"),
6e12eaa4 2008 ("123456789", "FAIL"),
3bdf7d7f
JM
2009 ("1234-5670", "12345670"),
2010 ("1234 5670", "12345670"),
2011 ("1-2.3:4 5670", "12345670") ]:
2012 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2013 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2014 if res != res2:
2015 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
2016 if res != t[1]:
2017 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
9ba1fcb0 2018
ac786d67
JM
2019 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
2020 raise Exception("Unexpected WPS_CHECK_PIN success")
2021 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
2022 raise Exception("Unexpected WPS_CHECK_PIN success")
2023
acd9b45a
JM
2024 for i in range(0, 10):
2025 pin = dev[0].request("WPS_PIN get")
2026 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
2027 if pin != rpin:
2028 raise Exception("Random PIN validation failed for " + pin)
2029
9ba1fcb0
JM
2030def test_ap_wps_wep_config(dev, apdev):
2031 """WPS 2.0 AP rejecting WEP configuration"""
2032 ssid = "test-wps-config"
2033 appin = "12345670"
6f334bf7
JD
2034 hapd = hostapd.add_ap(apdev[0],
2035 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2036 "ap_pin": appin})
33d0b157 2037 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
9ba1fcb0
JM
2038 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2039 "hello", no_wait=True)
2040 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2041 if ev is None:
2042 raise Exception("WPS-FAIL timed out")
2043 if "reason=2" not in ev:
2044 raise Exception("Unexpected reason code in WPS-FAIL")
2045 status = hapd.request("WPS_GET_STATUS")
2046 if "Last WPS result: Failed" not in status:
2047 raise Exception("WPS failure result not shown correctly")
2048 if "Failure Reason: WEP Prohibited" not in status:
2049 raise Exception("Failure reason not reported correctly")
2050 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2051 raise Exception("Peer address not shown correctly")
1013a576 2052
11d78bb1
JM
2053def test_ap_wps_wep_enroll(dev, apdev):
2054 """WPS 2.0 STA rejecting WEP configuration"""
2055 ssid = "test-wps-wep"
6f334bf7
JD
2056 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2057 "skip_cred_build": "1", "extra_cred": "wps-wep-cred" }
2058 hapd = hostapd.add_ap(apdev[0], params)
11d78bb1 2059 hapd.request("WPS_PBC")
33d0b157
JM
2060 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2061 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
11d78bb1
JM
2062 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2063 if ev is None:
2064 raise Exception("WPS-FAIL event timed out")
2065 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2066 raise Exception("Unexpected WPS-FAIL event: " + ev)
2067
9fd6804d 2068@remote_compatible
1013a576
JM
2069def test_ap_wps_ie_fragmentation(dev, apdev):
2070 """WPS AP using fragmented WPS IE"""
2071 ssid = "test-wps-ie-fragmentation"
2072 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2073 "wpa_passphrase": "12345678", "wpa": "2",
2074 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2075 "device_name": "1234567890abcdef1234567890abcdef",
2076 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2077 "model_name": "1234567890abcdef1234567890abcdef",
2078 "model_number": "1234567890abcdef1234567890abcdef",
2079 "serial_number": "1234567890abcdef1234567890abcdef" }
6f334bf7 2080 hapd = hostapd.add_ap(apdev[0], params)
1013a576 2081 hapd.request("WPS_PBC")
33d0b157
JM
2082 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2083 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2084 dev[0].wait_connected(timeout=30)
1013a576
JM
2085 bss = dev[0].get_bss(apdev[0]['bssid'])
2086 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8 2087 logger.info("Device Name not received correctly")
d7a68ad6 2088 logger.info(bss)
cf3f0ec8
JM
2089 # This can fail if Probe Response frame is missed and Beacon frame was
2090 # used to fill in the BSS entry. This can happen, e.g., during heavy
2091 # load every now and then and is not really an error, so try to
2092 # workaround by runnign another scan.
2093 dev[0].scan(freq="2412", only_new=True)
2094 bss = dev[0].get_bss(apdev[0]['bssid'])
84a40841 2095 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8
JM
2096 logger.info(bss)
2097 raise Exception("Device Name not received correctly")
1013a576
JM
2098 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2099 raise Exception("Unexpected number of WPS IEs")
44ff0400 2100
2035b170
JM
2101def get_psk(pskfile):
2102 psks = {}
2103 with open(pskfile, "r") as f:
2104 lines = f.read().splitlines()
2105 for l in lines:
2106 if l == "# WPA PSKs":
2107 continue
2108 (addr,psk) = l.split(' ')
2109 psks[addr] = psk
2110 return psks
2111
2112def test_ap_wps_per_station_psk(dev, apdev):
2113 """WPS PBC provisioning with per-station PSK"""
1d21a5be
B
2114 addr0 = dev[0].own_addr()
2115 addr1 = dev[1].own_addr()
2116 addr2 = dev[2].own_addr()
2035b170
JM
2117 ssid = "wps"
2118 appin = "12345670"
2119 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2120 try:
2121 os.remove(pskfile)
2122 except:
2123 pass
2124
4f524e99 2125 hapd = None
2035b170
JM
2126 try:
2127 with open(pskfile, "w") as f:
2128 f.write("# WPA PSKs\n")
2129
2130 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2131 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2132 "rsn_pairwise": "CCMP", "ap_pin": appin,
2133 "wpa_psk_file": pskfile }
8b8a1864 2134 hapd = hostapd.add_ap(apdev[0], params)
2035b170
JM
2135
2136 logger.info("First enrollee")
2137 hapd.request("WPS_PBC")
33d0b157
JM
2138 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2139 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2140 dev[0].wait_connected(timeout=30)
2035b170
JM
2141
2142 logger.info("Second enrollee")
2143 hapd.request("WPS_PBC")
33d0b157
JM
2144 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2145 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2146 dev[1].wait_connected(timeout=30)
2035b170
JM
2147
2148 logger.info("External registrar")
33d0b157 2149 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2150 dev[2].wps_reg(apdev[0]['bssid'], appin)
2151
2152 logger.info("Verifying PSK results")
2153 psks = get_psk(pskfile)
2154 if addr0 not in psks:
2155 raise Exception("No PSK recorded for sta0")
2156 if addr1 not in psks:
2157 raise Exception("No PSK recorded for sta1")
2158 if addr2 not in psks:
2159 raise Exception("No PSK recorded for sta2")
2160 if psks[addr0] == psks[addr1]:
2161 raise Exception("Same PSK recorded for sta0 and sta1")
2162 if psks[addr0] == psks[addr2]:
2163 raise Exception("Same PSK recorded for sta0 and sta2")
2164 if psks[addr1] == psks[addr2]:
2165 raise Exception("Same PSK recorded for sta1 and sta2")
2166
2167 dev[0].request("REMOVE_NETWORK all")
2168 logger.info("Second external registrar")
33d0b157 2169 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2170 dev[0].wps_reg(apdev[0]['bssid'], appin)
2171 psks2 = get_psk(pskfile)
2172 if addr0 not in psks2:
2173 raise Exception("No PSK recorded for sta0(reg)")
2174 if psks[addr0] == psks2[addr0]:
2175 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2176 finally:
2177 os.remove(pskfile)
4f524e99
JM
2178 if hapd:
2179 dev[0].request("DISCONNECT")
2180 dev[1].request("DISCONNECT")
2181 dev[2].request("DISCONNECT")
2182 hapd.disable()
2183 dev[0].flush_scan_cache()
2184 dev[1].flush_scan_cache()
2185 dev[2].flush_scan_cache()
2035b170 2186
373cce55
JM
2187def test_ap_wps_per_station_psk_failure(dev, apdev):
2188 """WPS PBC provisioning with per-station PSK (file not writable)"""
2189 addr0 = dev[0].p2p_dev_addr()
2190 addr1 = dev[1].p2p_dev_addr()
2191 addr2 = dev[2].p2p_dev_addr()
2192 ssid = "wps"
2193 appin = "12345670"
2194 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2195 try:
2196 os.remove(pskfile)
2197 except:
2198 pass
2199
3615bde6 2200 hapd = None
373cce55
JM
2201 try:
2202 with open(pskfile, "w") as f:
2203 f.write("# WPA PSKs\n")
2204
2205 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2206 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2207 "rsn_pairwise": "CCMP", "ap_pin": appin,
2208 "wpa_psk_file": pskfile }
8b8a1864 2209 hapd = hostapd.add_ap(apdev[0], params)
373cce55
JM
2210 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2211 raise Exception("Failed to set wpa_psk_file")
2212
2213 logger.info("First enrollee")
2214 hapd.request("WPS_PBC")
33d0b157
JM
2215 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2216 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2217 dev[0].wait_connected(timeout=30)
373cce55
JM
2218
2219 logger.info("Second enrollee")
2220 hapd.request("WPS_PBC")
33d0b157
JM
2221 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2222 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2223 dev[1].wait_connected(timeout=30)
373cce55
JM
2224
2225 logger.info("External registrar")
33d0b157 2226 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
373cce55
JM
2227 dev[2].wps_reg(apdev[0]['bssid'], appin)
2228
2229 logger.info("Verifying PSK results")
2230 psks = get_psk(pskfile)
2231 if len(psks) > 0:
2232 raise Exception("PSK recorded unexpectedly")
2233 finally:
3615bde6
JM
2234 if hapd:
2235 for i in range(3):
2236 dev[i].request("DISCONNECT")
2237 hapd.disable()
2238 for i in range(3):
2239 dev[i].flush_scan_cache()
373cce55
JM
2240 os.remove(pskfile)
2241
e8518757
JM
2242def test_ap_wps_pin_request_file(dev, apdev):
2243 """WPS PIN provisioning with configured AP"""
2244 ssid = "wps"
2245 pinfile = "/tmp/ap_wps_pin_request_file.log"
2246 if os.path.exists(pinfile):
b638f703 2247 os.remove(pinfile)
6f334bf7
JD
2248 hapd = hostapd.add_ap(apdev[0],
2249 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2250 "wps_pin_requests": pinfile,
2251 "wpa_passphrase": "12345678", "wpa": "2",
2252 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e8518757
JM
2253 uuid = dev[0].get_status_field("uuid")
2254 pin = dev[0].wps_read_pin()
2255 try:
33d0b157
JM
2256 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2257 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
e8518757
JM
2258 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2259 if ev is None:
2260 raise Exception("PIN needed event not shown")
2261 if uuid not in ev:
2262 raise Exception("UUID mismatch")
2263 dev[0].request("WPS_CANCEL")
2264 success = False
2265 with open(pinfile, "r") as f:
2266 lines = f.readlines()
2267 for l in lines:
2268 if uuid in l:
2269 success = True
2270 break
2271 if not success:
2272 raise Exception("PIN request entry not in the log file")
2273 finally:
b638f703
JM
2274 try:
2275 os.remove(pinfile)
2276 except:
2277 pass
e8518757 2278
56887c35
JM
2279def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2280 """WPS auto-setup with configuration file"""
2281 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2282 ifname = apdev[0]['ifname']
2283 try:
2284 with open(conffile, "w") as f:
2285 f.write("driver=nl80211\n")
2286 f.write("hw_mode=g\n")
2287 f.write("channel=1\n")
2288 f.write("ieee80211n=1\n")
2289 f.write("interface=%s\n" % ifname)
2290 f.write("ctrl_interface=/var/run/hostapd\n")
2291 f.write("ssid=wps\n")
2292 f.write("eap_server=1\n")
2293 f.write("wps_state=1\n")
5148b392 2294 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
56887c35 2295 hapd.request("WPS_PBC")
33d0b157
JM
2296 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2297 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2298 dev[0].wait_connected(timeout=30)
56887c35
JM
2299 with open(conffile, "r") as f:
2300 lines = f.read().splitlines()
2301 vals = dict()
2302 for l in lines:
2303 try:
2304 [name,value] = l.split('=', 1)
2305 vals[name] = value
2306 except ValueError, e:
2307 if "# WPS configuration" in l:
2308 pass
2309 else:
2310 raise Exception("Unexpected configuration line: " + l)
2311 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2312 raise Exception("Incorrect configuration: " + str(vals))
2313 finally:
b638f703
JM
2314 try:
2315 os.remove(conffile)
2316 except:
2317 pass
56887c35 2318
91f3cf69 2319def test_ap_wps_pbc_timeout(dev, apdev, params):
31e56b95 2320 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
91f3cf69 2321 if not params['long']:
81e787b7 2322 raise HwsimSkip("Skip test case with long duration due to --long not specified")
31e56b95 2323 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2324 hapd = add_ssdp_ap(apdev[0], ap_uuid)
31e56b95
JM
2325
2326 location = ssdp_get_location(ap_uuid)
2327 urls = upnp_get_urls(location)
2328 eventurl = urlparse.urlparse(urls['event_sub_url'])
2329 ctrlurl = urlparse.urlparse(urls['control_url'])
2330
2331 url = urlparse.urlparse(location)
2332 conn = httplib.HTTPConnection(url.netloc)
2333
2334 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
2335 def handle(self):
2336 data = self.rfile.readline().strip()
2337 logger.debug(data)
2338 self.wfile.write(gen_wps_event())
2339
2340 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2341 server.timeout = 1
2342
2343 headers = { "callback": '<http://127.0.0.1:12345/event>',
2344 "NT": "upnp:event",
2345 "timeout": "Second-1234" }
2346 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2347 resp = conn.getresponse()
2348 if resp.status != 200:
2349 raise Exception("Unexpected HTTP response: %d" % resp.status)
2350 sid = resp.getheader("sid")
2351 logger.debug("Subscription SID " + sid)
2352
2353 msg = '''<?xml version="1.0"?>
2354<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2355<s:Body>
2356<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2357<NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2358VFi5hrLk
2359</NewMessage>
2360</u:SetSelectedRegistrar>
2361</s:Body>
2362</s:Envelope>'''
2363 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2364 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2365 conn.request("POST", ctrlurl.path, msg, headers)
2366 resp = conn.getresponse()
2367 if resp.status != 200:
2368 raise Exception("Unexpected HTTP response: %d" % resp.status)
2369
2370 server.handle_request()
2371
91f3cf69
JM
2372 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2373 if "OK" not in dev[0].request("WPS_PBC"):
2374 raise Exception("WPS_PBC failed")
31e56b95
JM
2375
2376 start = os.times()[4]
2377
2378 server.handle_request()
2379 dev[1].request("BSS_FLUSH 0")
2380 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2381 only_new=True)
2382 bss = dev[1].get_bss(apdev[0]['bssid'])
2383 logger.debug("BSS: " + str(bss))
2384 if '[WPS-AUTH]' not in bss['flags']:
2385 raise Exception("WPS not indicated authorized")
2386
2387 server.handle_request()
2388
2389 wps_timeout_seen = False
2390
2391 while True:
2392 hapd.dump_monitor()
2393 dev[1].dump_monitor()
2394 if not wps_timeout_seen:
2395 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2396 if ev is not None:
2397 logger.info("PBC timeout seen")
2398 wps_timeout_seen = True
2399 else:
2400 dev[0].dump_monitor()
2401 now = os.times()[4]
2402 if now - start > 130:
2403 raise Exception("Selected registration information not removed")
2404 dev[1].request("BSS_FLUSH 0")
2405 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2406 only_new=True)
2407 bss = dev[1].get_bss(apdev[0]['bssid'])
2408 logger.debug("BSS: " + str(bss))
2409 if '[WPS-AUTH]' not in bss['flags']:
2410 break
2411 server.handle_request()
2412
2413 server.server_close()
2414
2415 if wps_timeout_seen:
2416 return
2417
2418 now = os.times()[4]
2419 if now < start + 150:
2420 dur = start + 150 - now
2421 else:
2422 dur = 1
2423 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2424 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
91f3cf69
JM
2425 if ev is None:
2426 raise Exception("WPS-TIMEOUT not reported")
2427
21aa8b7e 2428def add_ssdp_ap(ap, ap_uuid):
44ff0400
JM
2429 ssid = "wps-ssdp"
2430 ap_pin = "12345670"
24b7f282
JM
2431 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2432 "wpa_passphrase": "12345678", "wpa": "2",
2433 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2434 "device_name": "Wireless AP", "manufacturer": "Company",
2435 "model_name": "WAP", "model_number": "123",
2436 "serial_number": "12345", "device_type": "6-0050F204-1",
2437 "os_version": "01020300",
2438 "config_methods": "label push_button",
2439 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2440 "friendly_name": "WPS Access Point",
2441 "manufacturer_url": "http://www.example.com/",
2442 "model_description": "Wireless Access Point",
2443 "model_url": "http://www.example.com/model/",
2444 "upc": "123456789012" }
21aa8b7e 2445 return hostapd.add_ap(ap, params)
44ff0400
JM
2446
2447def ssdp_send(msg, no_recv=False):
2448 socket.setdefaulttimeout(1)
2449 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2450 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2451 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2452 sock.bind(("127.0.0.1", 0))
2453 sock.sendto(msg, ("239.255.255.250", 1900))
2454 if no_recv:
2455 return None
2456 return sock.recv(1000)
2457
96038a5f 2458def ssdp_send_msearch(st, no_recv=False):
44ff0400
JM
2459 msg = '\r\n'.join([
2460 'M-SEARCH * HTTP/1.1',
2461 'HOST: 239.255.255.250:1900',
2462 'MX: 1',
2463 'MAN: "ssdp:discover"',
2464 'ST: ' + st,
2465 '', ''])
96038a5f 2466 return ssdp_send(msg, no_recv=no_recv)
44ff0400
JM
2467
2468def test_ap_wps_ssdp_msearch(dev, apdev):
2469 """WPS AP and SSDP M-SEARCH messages"""
2470 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2471 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2472
2473 msg = '\r\n'.join([
2474 'M-SEARCH * HTTP/1.1',
2475 'Host: 239.255.255.250:1900',
2476 'Mx: 1',
2477 'Man: "ssdp:discover"',
2478 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2479 '', ''])
2480 ssdp_send(msg)
2481
2482 msg = '\r\n'.join([
2483 'M-SEARCH * HTTP/1.1',
2484 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2485 'mx: \t1\t\t ',
2486 'man: \t \t "ssdp:discover" ',
2487 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2488 '', ''])
2489 ssdp_send(msg)
2490
2491 ssdp_send_msearch("ssdp:all")
2492 ssdp_send_msearch("upnp:rootdevice")
2493 ssdp_send_msearch("uuid:" + ap_uuid)
2494 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
bc6e3288 2495 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1")
44ff0400
JM
2496
2497 msg = '\r\n'.join([
2498 'M-SEARCH * HTTP/1.1',
2499 'HOST:\t239.255.255.250:1900',
2500 'MAN: "ssdp:discover"',
2501 'MX: 130',
2502 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2503 '', ''])
2504 ssdp_send(msg, no_recv=True)
2505
2506def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2507 """WPS AP and invalid SSDP M-SEARCH messages"""
2508 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2509 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2510
2511 socket.setdefaulttimeout(1)
2512 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2513 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2514 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2515 sock.bind(("127.0.0.1", 0))
2516
2517 logger.debug("Missing MX")
2518 msg = '\r\n'.join([
2519 'M-SEARCH * HTTP/1.1',
2520 'HOST: 239.255.255.250:1900',
2521 'MAN: "ssdp:discover"',
2522 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2523 '', ''])
2524 sock.sendto(msg, ("239.255.255.250", 1900))
2525
2526 logger.debug("Negative MX")
2527 msg = '\r\n'.join([
2528 'M-SEARCH * HTTP/1.1',
2529 'HOST: 239.255.255.250:1900',
2530 'MX: -1',
2531 'MAN: "ssdp:discover"',
2532 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2533 '', ''])
2534 sock.sendto(msg, ("239.255.255.250", 1900))
2535
2536 logger.debug("Invalid MX")
2537 msg = '\r\n'.join([
2538 'M-SEARCH * HTTP/1.1',
2539 'HOST: 239.255.255.250:1900',
2540 'MX; 1',
2541 'MAN: "ssdp:discover"',
2542 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2543 '', ''])
2544 sock.sendto(msg, ("239.255.255.250", 1900))
2545
2546 logger.debug("Missing MAN")
2547 msg = '\r\n'.join([
2548 'M-SEARCH * HTTP/1.1',
2549 'HOST: 239.255.255.250:1900',
2550 'MX: 1',
2551 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2552 '', ''])
2553 sock.sendto(msg, ("239.255.255.250", 1900))
2554
2555 logger.debug("Invalid MAN")
2556 msg = '\r\n'.join([
2557 'M-SEARCH * HTTP/1.1',
2558 'HOST: 239.255.255.250:1900',
2559 'MX: 1',
2560 'MAN: foo',
2561 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2562 '', ''])
2563 sock.sendto(msg, ("239.255.255.250", 1900))
2564 msg = '\r\n'.join([
2565 'M-SEARCH * HTTP/1.1',
2566 'HOST: 239.255.255.250:1900',
2567 'MX: 1',
2568 'MAN; "ssdp:discover"',
2569 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2570 '', ''])
2571 sock.sendto(msg, ("239.255.255.250", 1900))
2572
2573 logger.debug("Missing HOST")
2574 msg = '\r\n'.join([
2575 'M-SEARCH * HTTP/1.1',
2576 'MAN: "ssdp:discover"',
2577 'MX: 1',
2578 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2579 '', ''])
2580 sock.sendto(msg, ("239.255.255.250", 1900))
2581
2582 logger.debug("Missing ST")
2583 msg = '\r\n'.join([
2584 'M-SEARCH * HTTP/1.1',
2585 'HOST: 239.255.255.250:1900',
2586 'MAN: "ssdp:discover"',
2587 'MX: 1',
2588 '', ''])
2589 sock.sendto(msg, ("239.255.255.250", 1900))
2590
2591 logger.debug("Mismatching ST")
2592 msg = '\r\n'.join([
2593 'M-SEARCH * HTTP/1.1',
2594 'HOST: 239.255.255.250:1900',
2595 'MAN: "ssdp:discover"',
2596 'MX: 1',
2597 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2598 '', ''])
2599 sock.sendto(msg, ("239.255.255.250", 1900))
2600 msg = '\r\n'.join([
2601 'M-SEARCH * HTTP/1.1',
2602 'HOST: 239.255.255.250:1900',
2603 'MAN: "ssdp:discover"',
2604 'MX: 1',
2605 'ST: foo:bar',
2606 '', ''])
2607 sock.sendto(msg, ("239.255.255.250", 1900))
2608 msg = '\r\n'.join([
2609 'M-SEARCH * HTTP/1.1',
2610 'HOST: 239.255.255.250:1900',
2611 'MAN: "ssdp:discover"',
2612 'MX: 1',
2613 'ST: foobar',
2614 '', ''])
2615 sock.sendto(msg, ("239.255.255.250", 1900))
2616
2617 logger.debug("Invalid ST")
2618 msg = '\r\n'.join([
2619 'M-SEARCH * HTTP/1.1',
2620 'HOST: 239.255.255.250:1900',
2621 'MAN: "ssdp:discover"',
2622 'MX: 1',
2623 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2624 '', ''])
2625 sock.sendto(msg, ("239.255.255.250", 1900))
2626
2627 logger.debug("Invalid M-SEARCH")
2628 msg = '\r\n'.join([
2629 'M+SEARCH * HTTP/1.1',
2630 'HOST: 239.255.255.250:1900',
2631 'MAN: "ssdp:discover"',
2632 'MX: 1',
2633 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2634 '', ''])
2635 sock.sendto(msg, ("239.255.255.250", 1900))
2636 msg = '\r\n'.join([
2637 'M-SEARCH-* HTTP/1.1',
2638 'HOST: 239.255.255.250:1900',
2639 'MAN: "ssdp:discover"',
2640 'MX: 1',
2641 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2642 '', ''])
2643 sock.sendto(msg, ("239.255.255.250", 1900))
2644
2645 logger.debug("Invalid message format")
2646 sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2647 msg = '\r'.join([
2648 'M-SEARCH * HTTP/1.1',
2649 'HOST: 239.255.255.250:1900',
2650 'MAN: "ssdp:discover"',
2651 'MX: 1',
2652 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2653 '', ''])
2654 sock.sendto(msg, ("239.255.255.250", 1900))
2655
2656 try:
2657 r = sock.recv(1000)
2658 raise Exception("Unexpected M-SEARCH response: " + r)
2659 except socket.timeout:
2660 pass
2661
2662 logger.debug("Valid M-SEARCH")
2663 msg = '\r\n'.join([
2664 'M-SEARCH * HTTP/1.1',
2665 'HOST: 239.255.255.250:1900',
2666 'MAN: "ssdp:discover"',
2667 'MX: 1',
2668 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2669 '', ''])
2670 sock.sendto(msg, ("239.255.255.250", 1900))
2671
2672 try:
2673 r = sock.recv(1000)
2674 pass
2675 except socket.timeout:
2676 raise Exception("No SSDP response")
2677
2678def test_ap_wps_ssdp_burst(dev, apdev):
2679 """WPS AP and SSDP burst"""
2680 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2681 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2682
2683 msg = '\r\n'.join([
2684 'M-SEARCH * HTTP/1.1',
2685 'HOST: 239.255.255.250:1900',
2686 'MAN: "ssdp:discover"',
2687 'MX: 1',
2688 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2689 '', ''])
2690 socket.setdefaulttimeout(1)
2691 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2692 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2693 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2694 sock.bind(("127.0.0.1", 0))
2695 for i in range(0, 25):
2696 sock.sendto(msg, ("239.255.255.250", 1900))
2697 resp = 0
2698 while True:
2699 try:
2700 r = sock.recv(1000)
2701 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2702 raise Exception("Unexpected message: " + r)
2703 resp += 1
2704 except socket.timeout:
2705 break
2706 if resp < 20:
2707 raise Exception("Too few SSDP responses")
2708
2709 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2710 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2711 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2712 sock.bind(("127.0.0.1", 0))
2713 for i in range(0, 25):
2714 sock.sendto(msg, ("239.255.255.250", 1900))
2715 while True:
2716 try:
2717 r = sock.recv(1000)
2718 if ap_uuid in r:
2719 break
2720 except socket.timeout:
2721 raise Exception("No SSDP response")
47c549fd
JM
2722
2723def ssdp_get_location(uuid):
2724 res = ssdp_send_msearch("uuid:" + uuid)
2725 location = None
2726 for l in res.splitlines():
2727 if l.lower().startswith("location:"):
2728 location = l.split(':', 1)[1].strip()
2729 break
2730 if location is None:
2731 raise Exception("No UPnP location found")
2732 return location
2733
2734def upnp_get_urls(location):
aa713e71 2735 conn = urllib.urlopen(location, proxies={})
47c549fd
JM
2736 tree = ET.parse(conn)
2737 root = tree.getroot()
2738 urn = '{urn:schemas-upnp-org:device-1-0}'
2739 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2740 res = {}
2741 res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
2742 res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
2743 res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
2744 return res
2745
dd124ee8
JM
2746def upnp_soap_action(conn, path, action, include_soap_action=True,
2747 soap_action_override=None, newmsg=None, neweventtype=None,
2748 neweventmac=None):
47c549fd
JM
2749 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2750 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2751 ET.register_namespace('soapenv', soapns)
2752 ET.register_namespace('wfa', wpsns)
2753 attrib = {}
2754 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2755 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2756 body = ET.SubElement(root, "{%s}Body" % soapns)
2757 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
dd124ee8
JM
2758 if newmsg:
2759 msg = ET.SubElement(act, "NewMessage")
2760 msg.text = base64.b64encode(newmsg)
2761 if neweventtype:
2762 msg = ET.SubElement(act, "NewWLANEventType")
2763 msg.text = neweventtype
2764 if neweventmac:
2765 msg = ET.SubElement(act, "NewWLANEventMAC")
2766 msg.text = neweventmac
47c549fd
JM
2767 tree = ET.ElementTree(root)
2768 soap = StringIO.StringIO()
2769 tree.write(soap, xml_declaration=True, encoding='utf-8')
2770
2771 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2772 if include_soap_action:
2773 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2774 elif soap_action_override:
2775 headers["SOAPAction"] = soap_action_override
2776 conn.request("POST", path, soap.getvalue(), headers)
2777 return conn.getresponse()
2778
2779def test_ap_wps_upnp(dev, apdev):
2780 """WPS AP and UPnP operations"""
2781 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2782 add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2783
2784 location = ssdp_get_location(ap_uuid)
2785 urls = upnp_get_urls(location)
2786
aa713e71 2787 conn = urllib.urlopen(urls['scpd_url'], proxies={})
47c549fd
JM
2788 scpd = conn.read()
2789
aa713e71
AO
2790 conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"),
2791 proxies={})
47c549fd
JM
2792 if conn.getcode() != 404:
2793 raise Exception("Unexpected HTTP response to GET unknown URL")
2794
2795 url = urlparse.urlparse(location)
2796 conn = httplib.HTTPConnection(url.netloc)
2797 #conn.set_debuglevel(1)
2798 headers = { "Content-type": 'text/xml; charset="utf-8"',
2799 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2800 conn.request("POST", "hello", "\r\n\r\n", headers)
2801 resp = conn.getresponse()
2802 if resp.status != 404:
5c267d71 2803 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2804
2805 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2806 resp = conn.getresponse()
2807 if resp.status != 501:
5c267d71 2808 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2809
2810 headers = { "Content-type": 'text/xml; charset="utf-8"',
2811 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2812 ctrlurl = urlparse.urlparse(urls['control_url'])
2813 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2814 resp = conn.getresponse()
2815 if resp.status != 401:
5c267d71 2816 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2817
2818 logger.debug("GetDeviceInfo without SOAPAction header")
2819 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2820 include_soap_action=False)
2821 if resp.status != 401:
5c267d71 2822 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2823
2824 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2825 for act in [ "foo",
2826 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2827 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2828 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2829 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2830 include_soap_action=False,
2831 soap_action_override=act)
2832 if resp.status != 401:
5c267d71 2833 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2834
2835 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2836 if resp.status != 200:
5c267d71 2837 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2838 dev = resp.read()
2839 if "NewDeviceInfo" not in dev:
2840 raise Exception("Unexpected GetDeviceInfo response")
2841
2842 logger.debug("PutMessage without required parameters")
2843 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2844 if resp.status != 600:
5c267d71 2845 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2846
2847 logger.debug("PutWLANResponse without required parameters")
2848 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2849 if resp.status != 600:
5c267d71 2850 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2851
2852 logger.debug("SetSelectedRegistrar from unregistered ER")
2853 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2854 if resp.status != 501:
5c267d71 2855 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2856
2857 logger.debug("Unknown action")
2858 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2859 if resp.status != 401:
5c267d71 2860 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2861
2862def test_ap_wps_upnp_subscribe(dev, apdev):
2863 """WPS AP and UPnP event subscription"""
2864 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2865 hapd = add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2866
2867 location = ssdp_get_location(ap_uuid)
2868 urls = upnp_get_urls(location)
2869 eventurl = urlparse.urlparse(urls['event_sub_url'])
2870
2871 url = urlparse.urlparse(location)
2872 conn = httplib.HTTPConnection(url.netloc)
2873 #conn.set_debuglevel(1)
2874 headers = { "callback": '<http://127.0.0.1:12345/event>',
2875 "timeout": "Second-1234" }
2876 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2877 resp = conn.getresponse()
2878 if resp.status != 412:
5c267d71 2879 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2880
2881 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2882 resp = conn.getresponse()
2883 if resp.status != 412:
5c267d71 2884 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2885
2886 headers = { "NT": "upnp:event",
2887 "timeout": "Second-1234" }
2888 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2889 resp = conn.getresponse()
2890 if resp.status != 412:
5c267d71 2891 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2892
2893 headers = { "callback": '<http://127.0.0.1:12345/event>',
2894 "NT": "upnp:foobar",
2895 "timeout": "Second-1234" }
2896 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2897 resp = conn.getresponse()
2898 if resp.status != 400:
5c267d71 2899 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2900
2901 logger.debug("Valid subscription")
2902 headers = { "callback": '<http://127.0.0.1:12345/event>',
2903 "NT": "upnp:event",
2904 "timeout": "Second-1234" }
2905 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2906 resp = conn.getresponse()
2907 if resp.status != 200:
5c267d71 2908 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2909 sid = resp.getheader("sid")
2910 logger.debug("Subscription SID " + sid)
2911
2912 logger.debug("Invalid re-subscription")
2913 headers = { "NT": "upnp:event",
2914 "sid": "123456734567854",
2915 "timeout": "Second-1234" }
2916 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2917 resp = conn.getresponse()
2918 if resp.status != 400:
5c267d71 2919 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2920
2921 logger.debug("Invalid re-subscription")
2922 headers = { "NT": "upnp:event",
2923 "sid": "uuid:123456734567854",
2924 "timeout": "Second-1234" }
2925 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2926 resp = conn.getresponse()
2927 if resp.status != 400:
5c267d71 2928 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2929
2930 logger.debug("Invalid re-subscription")
2931 headers = { "callback": '<http://127.0.0.1:12345/event>',
2932 "NT": "upnp:event",
2933 "sid": sid,
2934 "timeout": "Second-1234" }
2935 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2936 resp = conn.getresponse()
2937 if resp.status != 400:
5c267d71 2938 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2939
2940 logger.debug("SID mismatch in re-subscription")
2941 headers = { "NT": "upnp:event",
2942 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2943 "timeout": "Second-1234" }
2944 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2945 resp = conn.getresponse()
2946 if resp.status != 412:
5c267d71 2947 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2948
2949 logger.debug("Valid re-subscription")
2950 headers = { "NT": "upnp:event",
2951 "sid": sid,
2952 "timeout": "Second-1234" }
2953 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2954 resp = conn.getresponse()
2955 if resp.status != 200:
5c267d71 2956 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2957 sid2 = resp.getheader("sid")
2958 logger.debug("Subscription SID " + sid2)
2959
2960 if sid != sid2:
2961 raise Exception("Unexpected SID change")
2962
2963 logger.debug("Valid re-subscription")
2964 headers = { "NT": "upnp:event",
2965 "sid": "uuid: \t \t" + sid.split(':')[1],
2966 "timeout": "Second-1234" }
2967 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2968 resp = conn.getresponse()
2969 if resp.status != 200:
5c267d71 2970 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2971
2972 logger.debug("Invalid unsubscription")
2973 headers = { "sid": sid }
2974 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
2975 resp = conn.getresponse()
2976 if resp.status != 412:
5c267d71 2977 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2978 headers = { "foo": "bar" }
2979 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2980 resp = conn.getresponse()
2981 if resp.status != 412:
5c267d71 2982 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2983
2984 logger.debug("Valid unsubscription")
2985 headers = { "sid": sid }
2986 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2987 resp = conn.getresponse()
2988 if resp.status != 200:
5c267d71 2989 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2990
2991 logger.debug("Unsubscription for not existing SID")
2992 headers = { "sid": sid }
2993 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2994 resp = conn.getresponse()
2995 if resp.status != 412:
5c267d71 2996 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2997
2998 logger.debug("Invalid unsubscription")
2999 headers = { "sid": " \t \tfoo" }
3000 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3001 resp = conn.getresponse()
3002 if resp.status != 400:
5c267d71 3003 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3004
3005 logger.debug("Invalid unsubscription")
3006 headers = { "sid": "uuid:\t \tfoo" }
3007 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3008 resp = conn.getresponse()
3009 if resp.status != 400:
5c267d71 3010 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3011
3012 logger.debug("Invalid unsubscription")
3013 headers = { "NT": "upnp:event",
3014 "sid": sid }
3015 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3016 resp = conn.getresponse()
3017 if resp.status != 400:
5c267d71 3018 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3019 headers = { "callback": '<http://127.0.0.1:12345/event>',
3020 "sid": sid }
3021 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3022 resp = conn.getresponse()
3023 if resp.status != 400:
5c267d71 3024 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3025
3026 logger.debug("Valid subscription with multiple callbacks")
3027 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>',
3028 "NT": "upnp:event",
3029 "timeout": "Second-1234" }
3030 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3031 resp = conn.getresponse()
3032 if resp.status != 200:
5c267d71 3033 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3034 sid = resp.getheader("sid")
3035 logger.debug("Subscription SID " + sid)
d352c407 3036
24b7f282
JM
3037 # Force subscription to be deleted due to errors
3038 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3039 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3040 with alloc_fail(hapd, 1, "event_build_message"):
3041 for i in range(10):
3042 dev[1].dump_monitor()
3043 dev[2].dump_monitor()
3044 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3045 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3046 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3047 dev[1].request("WPS_CANCEL")
3048 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3049 dev[2].request("WPS_CANCEL")
3050 if i % 4 == 1:
3051 time.sleep(1)
3052 else:
3053 time.sleep(0.1)
3054 time.sleep(0.2)
3055
3056 headers = { "sid": sid }
3057 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3058 resp = conn.getresponse()
3059 if resp.status != 200 and resp.status != 412:
3060 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3061
3062 headers = { "callback": '<http://127.0.0.1:12345/event>',
3063 "NT": "upnp:event",
3064 "timeout": "Second-1234" }
3065 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3066 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3067 resp = conn.getresponse()
3068 if resp.status != 200:
3069 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3070 sid = resp.getheader("sid")
3071 logger.debug("Subscription SID " + sid)
3072
3073 headers = { "sid": sid }
3074 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3075 resp = conn.getresponse()
3076 if resp.status != 200:
3077 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3078
3079 headers = { "callback": '<http://127.0.0.1:12345/event>',
3080 "NT": "upnp:event",
3081 "timeout": "Second-1234" }
3082 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3083 resp = conn.getresponse()
3084 if resp.status != 200:
3085 raise Exception("Unexpected HTTP response: %d" % resp.status)
3086 sid = resp.getheader("sid")
3087 logger.debug("Subscription SID " + sid)
3088
3089 with alloc_fail(hapd, 1, "=event_add"):
3090 for i in range(2):
3091 dev[1].dump_monitor()
3092 dev[2].dump_monitor()
3093 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3094 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3095 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3096 dev[1].request("WPS_CANCEL")
3097 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3098 dev[2].request("WPS_CANCEL")
3099 if i == 0:
3100 time.sleep(1)
3101 else:
3102 time.sleep(0.1)
3103
3104 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3105 resp = conn.getresponse()
3106 if resp.status != 200:
3107 raise Exception("Unexpected HTTP response: %d" % resp.status)
3108
3109 with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
3110 dev[1].dump_monitor()
3111 dev[2].dump_monitor()
3112 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3113 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3114 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3115 dev[1].request("WPS_CANCEL")
3116 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3117 dev[2].request("WPS_CANCEL")
3118 time.sleep(0.1)
3119
3120 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3121 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3122 resp = conn.getresponse()
3123 if resp.status != 500:
3124 raise Exception("Unexpected HTTP response: %d" % resp.status)
3125
3126 with alloc_fail(hapd, 1, "=subscription_start"):
3127 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3128 resp = conn.getresponse()
3129 if resp.status != 500:
3130 raise Exception("Unexpected HTTP response: %d" % resp.status)
3131
3132 headers = { "callback": '',
3133 "NT": "upnp:event",
3134 "timeout": "Second-1234" }
3135 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3136 resp = conn.getresponse()
3137 if resp.status != 500:
3138 raise Exception("Unexpected HTTP response: %d" % resp.status)
3139
3140 headers = { "callback": ' <',
3141 "NT": "upnp:event",
3142 "timeout": "Second-1234" }
3143 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3144 resp = conn.getresponse()
3145 if resp.status != 500:
3146 raise Exception("Unexpected HTTP response: %d" % resp.status)
3147
3148 headers = { "callback": '<http://127.0.0.1:12345/event>',
3149 "NT": "upnp:event",
3150 "timeout": "Second-1234" }
3151 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3152 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3153 resp = conn.getresponse()
3154 if resp.status != 500:
3155 raise Exception("Unexpected HTTP response: %d" % resp.status)
3156
3157 with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
3158 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3159 resp = conn.getresponse()
3160 if resp.status != 500:
3161 raise Exception("Unexpected HTTP response: %d" % resp.status)
3162
3163 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3164 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3165 resp = conn.getresponse()
3166 if resp.status != 500:
3167 raise Exception("Unexpected HTTP response: %d" % resp.status)
3168
3169 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3170 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3171 resp = conn.getresponse()
3172 if resp.status != 500:
3173 raise Exception("Unexpected HTTP response: %d" % resp.status)
3174
3175 for i in range(6):
3176 headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3177 "NT": "upnp:event",
3178 "timeout": "Second-1234" }
3179 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3180 resp = conn.getresponse()
3181 if resp.status != 200:
3182 raise Exception("Unexpected HTTP response: %d" % resp.status)
3183
3184 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3185 dev[1].dump_monitor()
3186 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3187 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3188 dev[1].request("WPS_CANCEL")
3189 time.sleep(0.1)
3190
3191 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3192 dev[1].dump_monitor()
3193 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3194 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3195 dev[1].request("WPS_CANCEL")
3196 time.sleep(0.1)
3197
3198 with alloc_fail(hapd, 1, "base64_encode;upnp_wps_device_send_wlan_event"):
3199 dev[1].dump_monitor()
3200 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3201 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3202 dev[1].request("WPS_CANCEL")
3203 time.sleep(0.1)
3204
3205 hapd.disable()
3206 with alloc_fail(hapd, 1, "get_netif_info"):
3207 if "FAIL" not in hapd.request("ENABLE"):
3208 raise Exception("ENABLE succeeded during OOM")
3209
d91a64c4
JM
3210def test_ap_wps_upnp_subscribe_events(dev, apdev):
3211 """WPS AP and UPnP event subscription and many events"""
3212 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3213 hapd = add_ssdp_ap(apdev[0], ap_uuid)
d91a64c4
JM
3214
3215 location = ssdp_get_location(ap_uuid)
3216 urls = upnp_get_urls(location)
3217 eventurl = urlparse.urlparse(urls['event_sub_url'])
3218
3219 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
3220 def handle(self):
3221 data = self.rfile.readline().strip()
3222 logger.debug(data)
3223 self.wfile.write(gen_wps_event())
3224
3225 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3226 server.timeout = 1
3227
3228 url = urlparse.urlparse(location)
3229 conn = httplib.HTTPConnection(url.netloc)
3230
3231 headers = { "callback": '<http://127.0.0.1:12345/event>',
3232 "NT": "upnp:event",
3233 "timeout": "Second-1234" }
3234 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3235 resp = conn.getresponse()
3236 if resp.status != 200:
3237 raise Exception("Unexpected HTTP response: %d" % resp.status)
3238 sid = resp.getheader("sid")
3239 logger.debug("Subscription SID " + sid)
3240
3241 # Fetch the first event message
3242 server.handle_request()
3243
3244 # Force subscription event queue to reach the maximum length by generating
3245 # new proxied events without the ER fetching any of the pending events.
3246 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3247 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3248 for i in range(16):
3249 dev[1].dump_monitor()
3250 dev[2].dump_monitor()
3251 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3252 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3253 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3254 dev[1].request("WPS_CANCEL")
3255 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3256 dev[2].request("WPS_CANCEL")
3257 if i % 4 == 1:
3258 time.sleep(1)
3259 else:
3260 time.sleep(0.1)
3261
3262 hapd.request("WPS_PIN any 12345670")
3263 dev[1].dump_monitor()
3264 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3265 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3266 if ev is None:
3267 raise Exception("WPS success not reported")
3268
3269 # Close the WPS ER HTTP server without fetching all the pending events.
3270 # This tests hostapd code path that clears subscription and the remaining
3271 # event queue when the interface is deinitialized.
3272 server.handle_request()
3273 server.server_close()
3274
3275 dev[1].wait_connected()
3276
b2047531
JM
3277def test_ap_wps_upnp_http_proto(dev, apdev):
3278 """WPS AP and UPnP/HTTP protocol testing"""
3279 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3280 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3281
3282 location = ssdp_get_location(ap_uuid)
3283
3284 url = urlparse.urlparse(location)
81f8e7e9 3285 conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
b2047531
JM
3286 #conn.set_debuglevel(1)
3287
3288 conn.request("HEAD", "hello")
3289 resp = conn.getresponse()
3290 if resp.status != 501:
3291 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3292 conn.close()
3293
3294 for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
3295 try:
3296 conn.request(cmd, "hello")
3297 resp = conn.getresponse()
3298 except Exception, e:
3299 pass
3300 conn.close()
3301
3302 headers = { "Content-Length": 'abc' }
3303 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3304 try:
3305 resp = conn.getresponse()
3306 except Exception, e:
3307 pass
3308 conn.close()
3309
3310 headers = { "Content-Length": '-10' }
3311 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3312 try:
3313 resp = conn.getresponse()
3314 except Exception, e:
3315 pass
3316 conn.close()
3317
3318 headers = { "Content-Length": '10000000000000' }
3319 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3320 try:
3321 resp = conn.getresponse()
3322 except Exception, e:
3323 pass
3324 conn.close()
3325
3326 headers = { "Transfer-Encoding": 'abc' }
3327 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3328 resp = conn.getresponse()
3329 if resp.status != 501:
3330 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3331 conn.close()
3332
3333 headers = { "Transfer-Encoding": 'chunked' }
3334 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3335 resp = conn.getresponse()
3336 if resp.status != 501:
3337 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3338 conn.close()
3339
3340 # Too long a header
3341 conn.request("HEAD", 5000 * 'A')
3342 try:
3343 resp = conn.getresponse()
3344 except Exception, e:
3345 pass
3346 conn.close()
3347
3348 # Long URL but within header length limits
3349 conn.request("HEAD", 3000 * 'A')
3350 resp = conn.getresponse()
3351 if resp.status != 501:
3352 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3353 conn.close()
3354
3355 headers = { "Content-Length": '20' }
3356 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3357 try:
3358 resp = conn.getresponse()
3359 except Exception, e:
3360 pass
3361 conn.close()
3362
3363 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3364 resp = conn.getresponse()
3365 if resp.status != 404:
5c267d71 3366 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3367 conn.close()
3368
3369 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3370 try:
3371 resp = conn.getresponse()
3372 except Exception, e:
3373 pass
3374 conn.close()
3375
3376def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3377 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3378 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3379 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3380
3381 location = ssdp_get_location(ap_uuid)
3382
3383 url = urlparse.urlparse(location)
3384 conn = httplib.HTTPConnection(url.netloc)
3385 #conn.set_debuglevel(1)
3386
3387 headers = { "Transfer-Encoding": 'chunked' }
3388 conn.request("POST", "hello",
3389 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3390 headers)
3391 resp = conn.getresponse()
3392 if resp.status != 404:
5c267d71 3393 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3394 conn.close()
3395
3396 conn.putrequest("POST", "hello")
3397 conn.putheader('Transfer-Encoding', 'chunked')
3398 conn.endheaders()
3399 conn.send("a\r\nabcdefghij\r\n")
3400 time.sleep(0.1)
3401 conn.send("2\r\nkl\r\n")
3402 conn.send("0\r\n\r\n")
3403 resp = conn.getresponse()
3404 if resp.status != 404:
5c267d71 3405 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3406 conn.close()
3407
3408 conn.putrequest("POST", "hello")
3409 conn.putheader('Transfer-Encoding', 'chunked')
3410 conn.endheaders()
3411 completed = False
3412 try:
3413 for i in range(20000):
3414 conn.send("1\r\nZ\r\n")
3415 conn.send("0\r\n\r\n")
3416 resp = conn.getresponse()
3417 completed = True
3418 except Exception, e:
3419 pass
3420 conn.close()
3421 if completed:
3422 raise Exception("Too long chunked request did not result in connection reset")
3423
3424 headers = { "Transfer-Encoding": 'chunked' }
3425 conn.request("POST", "hello", "80000000\r\na", headers)
3426 try:
3427 resp = conn.getresponse()
3428 except Exception, e:
3429 pass
3430 conn.close()
3431
3432 conn.request("POST", "hello", "10000000\r\na", headers)
3433 try:
3434 resp = conn.getresponse()
3435 except Exception, e:
3436 pass
3437 conn.close()
3438
9fd6804d 3439@remote_compatible
d352c407
JM
3440def test_ap_wps_disabled(dev, apdev):
3441 """WPS operations while WPS is disabled"""
3442 ssid = "test-wps-disabled"
6f334bf7 3443 hapd = hostapd.add_ap(apdev[0], { "ssid": ssid })
d352c407
JM
3444 if "FAIL" not in hapd.request("WPS_PBC"):
3445 raise Exception("WPS_PBC succeeded unexpectedly")
3446 if "FAIL" not in hapd.request("WPS_CANCEL"):
3447 raise Exception("WPS_CANCEL succeeded unexpectedly")
a0fd2ae6
JM
3448
3449def test_ap_wps_mixed_cred(dev, apdev):
3450 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3451 ssid = "test-wps-wep"
6f334bf7
JD
3452 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3453 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" }
3454 hapd = hostapd.add_ap(apdev[0], params)
a0fd2ae6 3455 hapd.request("WPS_PBC")
33d0b157
JM
3456 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3457 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
9ed53f5e 3458 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
a0fd2ae6
JM
3459 if ev is None:
3460 raise Exception("WPS-SUCCESS event timed out")
3461 nets = dev[0].list_networks()
3462 if len(nets) != 1:
3463 raise Exception("Unexpected number of network blocks")
3464 id = nets[0]['id']
3465 proto = dev[0].get_network(id, "proto")
3466 if proto != "WPA RSN":
3467 raise Exception("Unexpected merged proto field value: " + proto)
3468 pairwise = dev[0].get_network(id, "pairwise")
72a8e30b 3469 if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
a0fd2ae6 3470 raise Exception("Unexpected merged pairwise field value: " + pairwise)
e5a79e3f 3471
9fd6804d 3472@remote_compatible
e5a79e3f
JM
3473def test_ap_wps_while_connected(dev, apdev):
3474 """WPS PBC provisioning while connected to another AP"""
3475 ssid = "test-wps-conf"
6f334bf7
JD
3476 hapd = hostapd.add_ap(apdev[0],
3477 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3478 "wpa_passphrase": "12345678", "wpa": "2",
3479 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3480
8b8a1864 3481 hostapd.add_ap(apdev[1], { "ssid": "open" })
e5a79e3f
JM
3482 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3483
3484 logger.info("WPS provisioning step")
3485 hapd.request("WPS_PBC")
3486 dev[0].dump_monitor()
33d0b157 3487 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3488 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3489 status = dev[0].get_status()
3490 if status['bssid'] != apdev[0]['bssid']:
3491 raise Exception("Unexpected BSSID")
3492
9fd6804d 3493@remote_compatible
e5a79e3f
JM
3494def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3495 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3496 ssid = "test-wps-conf"
6f334bf7
JD
3497 hapd = hostapd.add_ap(apdev[0],
3498 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3499 "wpa_passphrase": "12345678", "wpa": "2",
3500 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3501
8b8a1864 3502 hostapd.add_ap(apdev[1], { "ssid": "open" })
e5a79e3f
JM
3503
3504 try:
3505 dev[0].request("STA_AUTOCONNECT 0")
3506 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3507
3508 logger.info("WPS provisioning step")
3509 hapd.request("WPS_PBC")
3510 dev[0].dump_monitor()
33d0b157 3511 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3512 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3513 status = dev[0].get_status()
3514 if status['bssid'] != apdev[0]['bssid']:
3515 raise Exception("Unexpected BSSID")
3516 finally:
3517 dev[0].request("STA_AUTOCONNECT 1")
3f08d1cd 3518
9fd6804d 3519@remote_compatible
3f08d1cd
JM
3520def test_ap_wps_from_event(dev, apdev):
3521 """WPS PBC event on AP to enable PBC"""
3522 ssid = "test-wps-conf"
8b8a1864 3523 hapd = hostapd.add_ap(apdev[0],
3f08d1cd
JM
3524 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3525 "wpa_passphrase": "12345678", "wpa": "2",
3526 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
33d0b157 3527 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3f08d1cd 3528 dev[0].dump_monitor()
33d0b157
JM
3529 hapd.dump_monitor()
3530 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3f08d1cd
JM
3531
3532 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3533 if ev is None:
3534 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3535 vals = ev.split(' ')
3536 if vals[1] != dev[0].p2p_interface_addr():
3537 raise Exception("Unexpected enrollee address: " + vals[1])
3538 if vals[5] != '4':
3539 raise Exception("Unexpected Device Password Id: " + vals[5])
3540 hapd.request("WPS_PBC")
5f35a5e2 3541 dev[0].wait_connected(timeout=30)
1531402e
JM
3542
3543def test_ap_wps_ap_scan_2(dev, apdev):
3544 """AP_SCAN 2 for WPS"""
3545 ssid = "test-wps-conf"
8b8a1864 3546 hapd = hostapd.add_ap(apdev[0],
1531402e
JM
3547 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3548 "wpa_passphrase": "12345678", "wpa": "2",
3549 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3550 hapd.request("WPS_PBC")
3551
3552 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3553 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
4b9d79b6 3554 wpas.dump_monitor()
1531402e
JM
3555
3556 if "OK" not in wpas.request("AP_SCAN 2"):
3557 raise Exception("Failed to set AP_SCAN 2")
3558
e51c8b2e 3559 wpas.flush_scan_cache()
33d0b157 3560 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
4b9d79b6 3561 wpas.dump_monitor()
33d0b157 3562 wpas.request("WPS_PBC " + apdev[0]['bssid'])
1531402e
JM
3563 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3564 if ev is None:
3565 raise Exception("WPS-SUCCESS event timed out")
5f35a5e2 3566 wpas.wait_connected(timeout=30)
4b9d79b6 3567 wpas.dump_monitor()
1531402e
JM
3568 wpas.request("DISCONNECT")
3569 wpas.request("BSS_FLUSH 0")
3570 wpas.dump_monitor()
3571 wpas.request("REASSOCIATE")
5f35a5e2 3572 wpas.wait_connected(timeout=30)
4b9d79b6 3573 wpas.dump_monitor()
a08fdb17 3574
9fd6804d 3575@remote_compatible
a08fdb17
JM
3576def test_ap_wps_eapol_workaround(dev, apdev):
3577 """EAPOL workaround code path for 802.1X header length mismatch"""
3578 ssid = "test-wps"
6f334bf7
JD
3579 hapd = hostapd.add_ap(apdev[0],
3580 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
a08fdb17
JM
3581 bssid = apdev[0]['bssid']
3582 hapd.request("SET ext_eapol_frame_io 1")
3583 dev[0].request("SET ext_eapol_frame_io 1")
3584 hapd.request("WPS_PBC")
3585 dev[0].request("WPS_PBC")
3586
3587 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3588 if ev is None:
3589 raise Exception("Timeout on EAPOL-TX from hostapd")
3590
3591 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3592 if "OK" not in res:
3593 raise Exception("EAPOL_RX to wpa_supplicant failed")
46dea617
JM
3594
3595def test_ap_wps_iteration(dev, apdev):
3596 """WPS PIN and iterate through APs without selected registrar"""
3597 ssid = "test-wps-conf"
8b8a1864 3598 hapd = hostapd.add_ap(apdev[0],
46dea617
JM
3599 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3600 "wpa_passphrase": "12345678", "wpa": "2",
3601 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3602
3603 ssid2 = "test-wps-conf2"
8b8a1864 3604 hapd2 = hostapd.add_ap(apdev[1],
46dea617
JM
3605 { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
3606 "wpa_passphrase": "12345678", "wpa": "2",
3607 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3608
3609 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3610 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3611 dev[0].dump_monitor()
3612 pin = dev[0].request("WPS_PIN any")
3613
3614 # Wait for iteration through all WPS APs to happen before enabling any
3615 # Registrar.
3616 for i in range(2):
3617 ev = dev[0].wait_event(["Associated with"], timeout=30)
3618 if ev is None:
3619 raise Exception("No association seen")
3620 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3621 if ev is None:
3622 raise Exception("No M2D from AP")
3623 dev[0].wait_disconnected()
3624
3625 # Verify that each AP requested PIN
3626 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3627 if ev is None:
3628 raise Exception("No WPS-PIN-NEEDED event from AP")
3629 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3630 if ev is None:
3631 raise Exception("No WPS-PIN-NEEDED event from AP2")
3632
3633 # Provide PIN to one of the APs and verify that connection gets formed
3634 hapd.request("WPS_PIN any " + pin)
3635 dev[0].wait_connected(timeout=30)
2272f5aa
JM
3636
3637def test_ap_wps_iteration_error(dev, apdev):
3638 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3639 ssid = "test-wps-conf-pin"
8b8a1864 3640 hapd = hostapd.add_ap(apdev[0],
2272f5aa
JM
3641 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3642 "wpa_passphrase": "12345678", "wpa": "2",
3643 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3644 "wps_independent": "1" })
3645 hapd.request("SET ext_eapol_frame_io 1")
3646 bssid = apdev[0]['bssid']
3647 pin = dev[0].wps_read_pin()
3648 dev[0].request("WPS_PIN any " + pin)
3649
3650 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3651 if ev is None:
3652 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3653 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3654
3655 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3656 if ev is None:
3657 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3658 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3659 if ev is None:
3660 raise Exception("No CTRL-EVENT-EAP-STARTED")
3661
3662 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3663 # a case with an incorrectly behaving WPS AP.
3664
3665 # Start the real target AP and activate registrar on it.
8b8a1864 3666 hapd2 = hostapd.add_ap(apdev[1],
2272f5aa
JM
3667 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3668 "wpa_passphrase": "12345678", "wpa": "2",
3669 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3670 "wps_independent": "1" })
3671 hapd2.request("WPS_PIN any " + pin)
3672
3673 dev[0].wait_disconnected(timeout=15)
3674 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3675 if ev is None:
3676 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3677 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3678 if ev is None:
3679 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3680 dev[0].wait_connected(timeout=15)
d6f6a86a 3681
9fd6804d 3682@remote_compatible
d6f6a86a
JM
3683def test_ap_wps_priority(dev, apdev):
3684 """WPS PIN provisioning with configured AP and wps_priority"""
3685 ssid = "test-wps-conf-pin"
6f334bf7
JD
3686 hapd = hostapd.add_ap(apdev[0],
3687 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3688 "wpa_passphrase": "12345678", "wpa": "2",
3689 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d6f6a86a
JM
3690 logger.info("WPS provisioning step")
3691 pin = dev[0].wps_read_pin()
3692 hapd.request("WPS_PIN any " + pin)
3693 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3694 dev[0].dump_monitor()
3695 try:
3696 dev[0].request("SET wps_priority 6")
3697 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3698 dev[0].wait_connected(timeout=30)
3699 netw = dev[0].list_networks()
3700 prio = dev[0].get_network(netw[0]['id'], 'priority')
3701 if prio != '6':
3702 raise Exception("Unexpected network priority: " + prio)
3703 finally:
3704 dev[0].request("SET wps_priority 0")
2c3a0190 3705
9fd6804d 3706@remote_compatible
df1d01cf
JM
3707def test_ap_wps_and_non_wps(dev, apdev):
3708 """WPS and non-WPS AP in single hostapd process"""
3709 params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
8b8a1864 3710 hapd = hostapd.add_ap(apdev[0], params)
df1d01cf
JM
3711
3712 params = { "ssid": "no wps" }
8b8a1864 3713 hapd2 = hostapd.add_ap(apdev[1], params)
df1d01cf
JM
3714
3715 appin = hapd.request("WPS_AP_PIN random")
3716 if "FAIL" in appin:
3717 raise Exception("Could not generate random AP PIN")
3718 if appin not in hapd.request("WPS_AP_PIN get"):
3719 raise Exception("Could not fetch current AP PIN")
3720
3721 if "FAIL" in hapd.request("WPS_PBC"):
3722 raise Exception("WPS_PBC failed")
3723 if "FAIL" in hapd.request("WPS_CANCEL"):
3724 raise Exception("WPS_CANCEL failed")
3725
2c3a0190
JM
3726def test_ap_wps_init_oom(dev, apdev):
3727 """Initial AP configuration and OOM during PSK generation"""
3728 ssid = "test-wps"
3729 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
8b8a1864 3730 hapd = hostapd.add_ap(apdev[0], params)
2c3a0190
JM
3731
3732 with alloc_fail(hapd, 1, "base64_encode;wps_build_cred"):
3733 pin = dev[0].wps_read_pin()
3734 hapd.request("WPS_PIN any " + pin)
3735 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3736 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3737 dev[0].wait_disconnected()
3738
3739 hapd.request("WPS_PIN any " + pin)
3740 dev[0].wait_connected(timeout=30)
ccf4d764 3741
9fd6804d 3742@remote_compatible
ccf4d764
JM
3743def test_ap_wps_er_oom(dev, apdev):
3744 """WPS ER OOM in XML processing"""
3745 try:
3746 _test_ap_wps_er_oom(dev, apdev)
3747 finally:
3748 dev[0].request("WPS_ER_STOP")
3749 dev[1].request("WPS_CANCEL")
3750 dev[0].request("DISCONNECT")
3751
3752def _test_ap_wps_er_oom(dev, apdev):
3753 ssid = "wps-er-ap-config"
3754 ap_pin = "12345670"
3755 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 3756 hostapd.add_ap(apdev[0],
ccf4d764
JM
3757 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3758 "wpa_passphrase": "12345678", "wpa": "2",
3759 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3760 "device_name": "Wireless AP", "manufacturer": "Company",
3761 "model_name": "WAP", "model_number": "123",
3762 "serial_number": "12345", "device_type": "6-0050F204-1",
3763 "os_version": "01020300",
3764 "config_methods": "label push_button",
3765 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3766
3767 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3768
3769 with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3770 dev[0].request("WPS_ER_START ifname=lo")
3771 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3772 if ev is not None:
3773 raise Exception("Unexpected AP discovery")
3774
3775 dev[0].request("WPS_ER_STOP")
3776 dev[0].request("WPS_ER_START ifname=lo")
3777 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3778 if ev is None:
3779 raise Exception("AP discovery timed out")
3780
3781 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3782 with alloc_fail(dev[0], 1, "base64_decode;xml_get_base64_item"):
3783 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3784 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3785 if ev is None:
3786 raise Exception("PBC scan failed")
3787 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3788 if ev is None:
3789 raise Exception("Enrollee discovery timed out")
2602a2ff 3790
9fd6804d 3791@remote_compatible
c965ae03
JM
3792def test_ap_wps_er_init_oom(dev, apdev):
3793 """WPS ER and OOM during init"""
3794 try:
3795 _test_ap_wps_er_init_oom(dev, apdev)
3796 finally:
3797 dev[0].request("WPS_ER_STOP")
3798
3799def _test_ap_wps_er_init_oom(dev, apdev):
3800 with alloc_fail(dev[0], 1, "wps_er_init"):
3801 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3802 raise Exception("WPS_ER_START succeeded during OOM")
3803 with alloc_fail(dev[0], 1, "http_server_init"):
3804 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3805 raise Exception("WPS_ER_START succeeded during OOM")
3806 with alloc_fail(dev[0], 2, "http_server_init"):
3807 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3808 raise Exception("WPS_ER_START succeeded during OOM")
9b35afd6 3809 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
c965ae03
JM
3810 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3811 raise Exception("WPS_ER_START succeeded during OOM")
3812 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3813 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3814 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3815
9fd6804d 3816@remote_compatible
07536b18
JM
3817def test_ap_wps_er_init_fail(dev, apdev):
3818 """WPS ER init failure"""
3819 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3820 dev[0].request("WPS_ER_STOP")
3821 raise Exception("WPS_ER_START with non-existing ifname succeeded")
3822
2602a2ff
JM
3823def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3824 """WPS events and wpa_cli action script"""
8936b095
JM
3825 logdir = os.path.abspath(test_params['logdir'])
3826 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3827 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3828 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
2602a2ff
JM
3829
3830 with open(actionfile, 'w') as f:
3831 f.write('#!/bin/sh\n')
3832 f.write('echo $* >> %s\n' % logfile)
3833 # Kill the process and wait some time before returning to allow all the
3834 # pending events to be processed with some of this happening after the
3835 # eloop SIGALRM signal has been scheduled.
3836 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3837
8936b095
JM
3838 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3839 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
2602a2ff
JM
3840
3841 ssid = "test-wps-conf"
6f334bf7
JD
3842 hapd = hostapd.add_ap(apdev[0],
3843 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3844 "wpa_passphrase": "12345678", "wpa": "2",
3845 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2602a2ff
JM
3846
3847 prg = os.path.join(test_params['logdir'],
3848 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3849 if not os.path.exists(prg):
3850 prg = '../../wpa_supplicant/wpa_cli'
3851 arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
3852 subprocess.call(arg)
3853
3854 arg = [ 'ps', 'ax' ]
3855 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3856 out = cmd.communicate()[0]
3857 cmd.wait()
3858 logger.debug("Processes:\n" + out)
3859 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3860 raise Exception("Did not see wpa_cli running")
3861
3862 hapd.request("WPS_PIN any 12345670")
3863 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3864 dev[0].dump_monitor()
3865 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3866 dev[0].wait_connected(timeout=30)
3867
3868 for i in range(30):
3869 if not os.path.exists(pidfile):
3870 break
3871 time.sleep(0.1)
3872
3873 if not os.path.exists(logfile):
3874 raise Exception("wpa_cli action results file not found")
3875 with open(logfile, 'r') as f:
3876 res = f.read()
3877 if "WPS-SUCCESS" not in res:
3878 raise Exception("WPS-SUCCESS event not seen in action file")
3879
3880 arg = [ 'ps', 'ax' ]
3881 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3882 out = cmd.communicate()[0]
3883 cmd.wait()
3884 logger.debug("Remaining processes:\n" + out)
3885 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3886 raise Exception("wpa_cli still running")
3887
3888 if os.path.exists(pidfile):
3889 raise Exception("PID file not removed")
c965ae03
JM
3890
3891def test_ap_wps_er_ssdp_proto(dev, apdev):
3892 """WPS ER SSDP protocol testing"""
3893 try:
3894 _test_ap_wps_er_ssdp_proto(dev, apdev)
3895 finally:
3896 dev[0].request("WPS_ER_STOP")
3897
3898def _test_ap_wps_er_ssdp_proto(dev, apdev):
3899 socket.setdefaulttimeout(1)
3900 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3901 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3902 sock.bind(("239.255.255.250", 1900))
3903 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3904 raise Exception("Invalid filter accepted")
3905 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3906 raise Exception("WPS_ER_START with filter failed")
3907 (msg,addr) = sock.recvfrom(1000)
3908 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3909 if "M-SEARCH" not in msg:
3910 raise Exception("Not an M-SEARCH")
3911 sock.sendto("FOO", addr)
3912 time.sleep(0.1)
3913 dev[0].request("WPS_ER_STOP")
3914
3915 dev[0].request("WPS_ER_START ifname=lo")
3916 (msg,addr) = sock.recvfrom(1000)
3917 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3918 if "M-SEARCH" not in msg:
3919 raise Exception("Not an M-SEARCH")
3920 sock.sendto("FOO", addr)
3921 sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3922 sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3923 sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3924 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
3925 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
3926 sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3927 sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3928 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
3929 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
3930 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
3931 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3932 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)
3933 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
3934 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3935 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)
3936 time.sleep(0.1)
3937 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
3938 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)
3939 time.sleep(0.1)
3940
3941 # Add an AP with bogus URL
3942 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)
3943 # Update timeout on AP without updating URL
3944 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)
3945 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3946 if ev is None:
3947 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3948
3949 # Add an AP with a valid URL (but no server listing to it)
3950 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)
3951 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3952 if ev is None:
3953 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3954
3955 sock.close()
3956
3957wps_event_url = None
3958
6aaa661a
JM
3959def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
3960 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4c3ae1c0 3961 payload = '''<?xml version="1.0"?>
c965ae03
JM
3962<root xmlns="urn:schemas-upnp-org:device-1-0">
3963<specVersion>
3964<major>1</major>
3965<minor>0</minor>
3966</specVersion>
3967<device>
3968<deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
3969<friendlyName>WPS Access Point</friendlyName>
3970<manufacturer>Company</manufacturer>
3971<modelName>WAP</modelName>
3972<modelNumber>123</modelNumber>
3973<serialNumber>12345</serialNumber>
6aaa661a
JM
3974'''
3975 if udn:
3976 payload += '<UDN>' + udn + '</UDN>'
3977 payload += '''<serviceList>
c965ae03
JM
3978<service>
3979<serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
3980<serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
3981<SCPDURL>wps_scpd.xml</SCPDURL>
4c3ae1c0 3982'''
6aaa661a
JM
3983 if controlURL:
3984 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4c3ae1c0 3985 if eventSubURL:
6aaa661a 3986 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4c3ae1c0 3987 payload += '''</service>
c965ae03
JM
3988</serviceList>
3989</device>
3990</root>
3991'''
4c3ae1c0
JM
3992 hdr = 'HTTP/1.1 200 OK\r\n' + \
3993 'Content-Type: text/xml; charset="utf-8"\r\n' + \
3994 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
3995 'Connection: close\r\n' + \
3996 'Content-Length: ' + str(len(payload)) + '\r\n' + \
3997 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
3998 return hdr + payload
3999
6aaa661a 4000def gen_wps_control(payload_override=None):
4c3ae1c0 4001 payload = '''<?xml version="1.0"?>
c965ae03
JM
4002<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4003<s:Body>
4004<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4005<NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
4006Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
4007+FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
40087zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
4009KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
4010AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
4011AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
4012AAYANyoAASA=
4013</NewDeviceInfo>
4014</u:GetDeviceInfoResponse>
4015</s:Body>
4016</s:Envelope>
4017'''
6aaa661a
JM
4018 if payload_override:
4019 payload = payload_override
4c3ae1c0
JM
4020 hdr = 'HTTP/1.1 200 OK\r\n' + \
4021 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4022 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4023 'Connection: close\r\n' + \
4024 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4025 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4026 return hdr + payload
4027
6aaa661a 4028def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4c3ae1c0
JM
4029 payload = ""
4030 hdr = 'HTTP/1.1 200 OK\r\n' + \
4031 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4032 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4033 'Connection: close\r\n' + \
6aaa661a
JM
4034 'Content-Length: ' + str(len(payload)) + '\r\n'
4035 if sid:
4036 hdr += 'SID: ' + sid + '\r\n'
4037 hdr += 'Timeout: Second-1801\r\n' + \
4c3ae1c0
JM
4038 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4039 return hdr + payload
4040
4041class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
4042 def handle(self):
4043 data = self.rfile.readline().strip()
4044 logger.info("HTTP server received: " + data)
4045 while True:
4046 hdr = self.rfile.readline().strip()
4047 if len(hdr) == 0:
4048 break
4049 logger.info("HTTP header: " + hdr)
4050 if "CALLBACK:" in hdr:
4051 global wps_event_url
4052 wps_event_url = hdr.split(' ')[1].strip('<>')
4053
4054 if "GET /foo.xml" in data:
6aaa661a
JM
4055 self.handle_upnp_info()
4056 elif "POST /wps_control" in data:
4057 self.handle_wps_control()
4058 elif "SUBSCRIBE /wps_event" in data:
4059 self.handle_wps_event()
24b7f282
JM
4060 else:
4061 self.handle_others(data)
6aaa661a
JM
4062
4063 def handle_upnp_info(self):
4064 self.wfile.write(gen_upnp_info())
4c3ae1c0 4065
6aaa661a
JM
4066 def handle_wps_control(self):
4067 self.wfile.write(gen_wps_control())
c965ae03 4068
6aaa661a
JM
4069 def handle_wps_event(self):
4070 self.wfile.write(gen_wps_event())
c965ae03 4071
24b7f282
JM
4072 def handle_others(self, data):
4073 logger.info("Ignore HTTP request: " + data)
4074
4c3ae1c0
JM
4075class MyTCPServer(SocketServer.TCPServer):
4076 def __init__(self, addr, handler):
4077 self.allow_reuse_address = True
4078 SocketServer.TCPServer.__init__(self, addr, handler)
c965ae03 4079
24b7f282
JM
4080def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4081 location_url=None):
c965ae03
JM
4082 socket.setdefaulttimeout(1)
4083 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4084 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4085 sock.bind(("239.255.255.250", 1900))
4c3ae1c0 4086 dev.request("WPS_ER_START ifname=lo")
24b7f282
JM
4087 for i in range(100):
4088 (msg,addr) = sock.recvfrom(1000)
4089 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4090 if "M-SEARCH" in msg:
4091 break
4092 if not wait_m_search:
4093 raise Exception("Not an M-SEARCH")
4094 if i == 99:
4095 raise Exception("No M-SEARCH seen")
c965ae03
JM
4096
4097 # Add an AP with a valid URL and server listing to it
4c3ae1c0 4098 server = MyTCPServer(("127.0.0.1", 12345), http_server)
24b7f282
JM
4099 if not location_url:
4100 location_url = 'http://127.0.0.1:12345/foo.xml'
4101 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 4102 server.timeout = 1
4c3ae1c0
JM
4103 return server,sock
4104
4105def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4106 sock.close()
4107 server.server_close()
4108
4109 if on_alloc_fail:
4110 done = False
4111 for i in range(50):
4112 res = dev.request("GET_ALLOC_FAIL")
4113 if res.startswith("0:"):
4114 done = True
4115 break
4116 time.sleep(0.1)
4117 if not done:
4118 raise Exception("No allocation failure reported")
4119 else:
4120 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4121 if ev is None:
4122 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4123 dev.request("WPS_ER_STOP")
4124
24b7f282 4125def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
6aaa661a
JM
4126 try:
4127 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
24b7f282 4128 server,sock = wps_er_start(dev, handler, location_url=location_url)
6aaa661a
JM
4129 global wps_event_url
4130 wps_event_url = None
4131 server.handle_request()
4132 server.handle_request()
4133 server.handle_request()
4134 server.server_close()
4135 if no_event_url:
4136 if wps_event_url:
4137 raise Exception("Received event URL unexpectedly")
4138 return
4139 if wps_event_url is None:
4140 raise Exception("Did not get event URL")
4141 logger.info("Event URL: " + wps_event_url)
4142 finally:
24b7f282 4143 dev.request("WPS_ER_STOP")
6aaa661a 4144
18478107 4145def send_wlanevent(url, uuid, data, no_response=False):
6aaa661a
JM
4146 conn = httplib.HTTPConnection(url.netloc)
4147 payload = '''<?xml version="1.0" encoding="utf-8"?>
4148<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4149<e:property><STAStatus>1</STAStatus></e:property>
4150<e:property><APStatus>1</APStatus></e:property>
4151<e:property><WLANEvent>'''
4152 payload += base64.b64encode(data)
4153 payload += '</WLANEvent></e:property></e:propertyset>'
4154 headers = { "Content-type": 'text/xml; charset="utf-8"',
4155 "Server": "Unspecified, UPnP/1.0, Unspecified",
4156 "HOST": url.netloc,
4157 "NT": "upnp:event",
4158 "SID": "uuid:" + uuid,
4159 "SEQ": "0",
4160 "Content-Length": str(len(payload)) }
4161 conn.request("NOTIFY", url.path, payload, headers)
18478107
JM
4162 if no_response:
4163 try:
4164 conn.getresponse()
4165 except Exception, e:
4166 pass
4167 return
6aaa661a
JM
4168 resp = conn.getresponse()
4169 if resp.status != 200:
4170 raise Exception("Unexpected HTTP response: %d" % resp.status)
4171
4c3ae1c0
JM
4172def test_ap_wps_er_http_proto(dev, apdev):
4173 """WPS ER HTTP protocol testing"""
4174 try:
4175 _test_ap_wps_er_http_proto(dev, apdev)
4176 finally:
4177 dev[0].request("WPS_ER_STOP")
4178
4179def _test_ap_wps_er_http_proto(dev, apdev):
4180 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
6aaa661a 4181 server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
c965ae03
JM
4182 global wps_event_url
4183 wps_event_url = None
4184 server.handle_request()
4185 server.handle_request()
4186 server.handle_request()
4187 server.server_close()
4188 if wps_event_url is None:
4189 raise Exception("Did not get event URL")
4190 logger.info("Event URL: " + wps_event_url)
4191
4192 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4193 if ev is None:
4194 raise Exception("No WPS-ER-AP-ADD event")
4195 if uuid not in ev:
4196 raise Exception("UUID mismatch")
4197
4198 sock.close()
4199
4200 logger.info("Valid Probe Request notification")
4201 url = urlparse.urlparse(wps_event_url)
4202 conn = httplib.HTTPConnection(url.netloc)
4203 payload = '''<?xml version="1.0" encoding="utf-8"?>
4204<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4205<e:property><STAStatus>1</STAStatus></e:property>
4206<e:property><APStatus>1</APStatus></e:property>
4207<e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4208EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4209RGV2aWNlIEEQSQAGADcqAAEg
4210</WLANEvent></e:property>
4211</e:propertyset>
4212'''
4213 headers = { "Content-type": 'text/xml; charset="utf-8"',
4214 "Server": "Unspecified, UPnP/1.0, Unspecified",
4215 "HOST": url.netloc,
4216 "NT": "upnp:event",
4217 "SID": "uuid:" + uuid,
4218 "SEQ": "0",
4219 "Content-Length": str(len(payload)) }
4220 conn.request("NOTIFY", url.path, payload, headers)
4221 resp = conn.getresponse()
4222 if resp.status != 200:
4223 raise Exception("Unexpected HTTP response: %d" % resp.status)
4224
4225 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4226 if ev is None:
4227 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4228 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4229 raise Exception("No Enrollee UUID match")
4230
4231 logger.info("Incorrect event URL AP id")
4232 conn = httplib.HTTPConnection(url.netloc)
4233 conn.request("NOTIFY", url.path + '123', payload, headers)
4234 resp = conn.getresponse()
4235 if resp.status != 404:
4236 raise Exception("Unexpected HTTP response: %d" % resp.status)
4237
4238 logger.info("Missing AP id")
4239 conn = httplib.HTTPConnection(url.netloc)
4240 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4241 payload, headers)
4242 time.sleep(0.1)
4243
4244 logger.info("Incorrect event URL event id")
4245 conn = httplib.HTTPConnection(url.netloc)
4246 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4247 time.sleep(0.1)
4248
4249 logger.info("Incorrect event URL prefix")
4250 conn = httplib.HTTPConnection(url.netloc)
4251 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4252 resp = conn.getresponse()
4253 if resp.status != 404:
4254 raise Exception("Unexpected HTTP response: %d" % resp.status)
4255
4256 logger.info("Unsupported request")
4257 conn = httplib.HTTPConnection(url.netloc)
4258 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4259 resp = conn.getresponse()
4260 if resp.status != 501:
4261 raise Exception("Unexpected HTTP response: %d" % resp.status)
4262
4263 logger.info("Unsupported request and OOM")
4264 with alloc_fail(dev[0], 1, "wps_er_http_req"):
4265 conn = httplib.HTTPConnection(url.netloc)
4266 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4267 time.sleep(0.5)
4c3ae1c0 4268
6aaa661a
JM
4269 logger.info("Too short WLANEvent")
4270 data = '\x00'
4271 send_wlanevent(url, uuid, data)
4272
4273 logger.info("Invalid WLANEventMAC")
4274 data = '\x00qwertyuiopasdfghjklzxcvbnm'
4275 send_wlanevent(url, uuid, data)
4276
4277 logger.info("Unknown WLANEventType")
4278 data = '\xff02:00:00:00:00:00'
4279 send_wlanevent(url, uuid, data)
4280
4281 logger.info("Probe Request notification without any attributes")
4282 data = '\x0102:00:00:00:00:00'
4283 send_wlanevent(url, uuid, data)
4284
4285 logger.info("Probe Request notification with invalid attribute")
4286 data = '\x0102:00:00:00:00:00\xff'
4287 send_wlanevent(url, uuid, data)
4288
4289 logger.info("EAP message without any attributes")
4290 data = '\x0202:00:00:00:00:00'
4291 send_wlanevent(url, uuid, data)
4292
4293 logger.info("EAP message with invalid attribute")
4294 data = '\x0202:00:00:00:00:00\xff'
4295 send_wlanevent(url, uuid, data)
4296
4297 logger.info("EAP message from new STA and not M1")
4298 data = '\x0202:ff:ff:ff:ff:ff' + '\x10\x22\x00\x01\x05'
4299 send_wlanevent(url, uuid, data)
4300
4301 logger.info("EAP message: M1")
4302 data = '\x0202:00:00:00:00:00'
4303 data += '\x10\x22\x00\x01\x04'
4304 data += '\x10\x47\x00\x10' + 16*'\x00'
4305 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4306 data += '\x10\x1a\x00\x10' + 16*'\x00'
4307 data += '\x10\x32\x00\xc0' + 192*'\x00'
4308 data += '\x10\x04\x00\x02\x00\x00'
4309 data += '\x10\x10\x00\x02\x00\x00'
4310 data += '\x10\x0d\x00\x01\x00'
4311 data += '\x10\x08\x00\x02\x00\x00'
4312 data += '\x10\x44\x00\x01\x00'
4313 data += '\x10\x21\x00\x00'
4314 data += '\x10\x23\x00\x00'
4315 data += '\x10\x24\x00\x00'
4316 data += '\x10\x42\x00\x00'
4317 data += '\x10\x54\x00\x08' + 8*'\x00'
4318 data += '\x10\x11\x00\x00'
4319 data += '\x10\x3c\x00\x01\x00'
4320 data += '\x10\x02\x00\x02\x00\x00'
4321 data += '\x10\x12\x00\x02\x00\x00'
4322 data += '\x10\x09\x00\x02\x00\x00'
4323 data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4324 m1 = data
4325 send_wlanevent(url, uuid, data)
4326
4327 logger.info("EAP message: WSC_ACK")
4328 data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0d'
4329 send_wlanevent(url, uuid, data)
4330
4331 logger.info("EAP message: M1")
4332 send_wlanevent(url, uuid, m1)
4333
4334 logger.info("EAP message: WSC_NACK")
4335 data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0e'
4336 send_wlanevent(url, uuid, data)
4337
4338 logger.info("EAP message: M1 - Too long attribute values")
4339 data = '\x0202:00:00:00:00:00'
4340 data += '\x10\x11\x00\x21' + 33*'\x00'
4341 data += '\x10\x45\x00\x21' + 33*'\x00'
4342 data += '\x10\x42\x00\x21' + 33*'\x00'
4343 data += '\x10\x24\x00\x21' + 33*'\x00'
4344 data += '\x10\x23\x00\x21' + 33*'\x00'
4345 data += '\x10\x21\x00\x41' + 65*'\x00'
4346 data += '\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4347 send_wlanevent(url, uuid, data)
4348
4349 logger.info("EAP message: M1 missing UUID-E")
4350 data = '\x0202:00:00:00:00:00'
4351 data += '\x10\x22\x00\x01\x04'
4352 send_wlanevent(url, uuid, data)
4353
4354 logger.info("EAP message: M1 missing MAC Address")
4355 data += '\x10\x47\x00\x10' + 16*'\x00'
4356 send_wlanevent(url, uuid, data)
4357
4358 logger.info("EAP message: M1 missing Enrollee Nonce")
4359 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4360 send_wlanevent(url, uuid, data)
4361
4362 logger.info("EAP message: M1 missing Public Key")
4363 data += '\x10\x1a\x00\x10' + 16*'\x00'
4364 send_wlanevent(url, uuid, data)
4365
4366 logger.info("EAP message: M1 missing Authentication Type flags")
4367 data += '\x10\x32\x00\xc0' + 192*'\x00'
4368 send_wlanevent(url, uuid, data)
4369
4370 logger.info("EAP message: M1 missing Encryption Type Flags")
4371 data += '\x10\x04\x00\x02\x00\x00'
4372 send_wlanevent(url, uuid, data)
4373
4374 logger.info("EAP message: M1 missing Connection Type flags")
4375 data += '\x10\x10\x00\x02\x00\x00'
4376 send_wlanevent(url, uuid, data)
4377
4378 logger.info("EAP message: M1 missing Config Methods")
4379 data += '\x10\x0d\x00\x01\x00'
4380 send_wlanevent(url, uuid, data)
4381
4382 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4383 data += '\x10\x08\x00\x02\x00\x00'
4384 send_wlanevent(url, uuid, data)
4385
4386 logger.info("EAP message: M1 missing Manufacturer")
4387 data += '\x10\x44\x00\x01\x00'
4388 send_wlanevent(url, uuid, data)
4389
4390 logger.info("EAP message: M1 missing Model Name")
4391 data += '\x10\x21\x00\x00'
4392 send_wlanevent(url, uuid, data)
4393
4394 logger.info("EAP message: M1 missing Model Number")
4395 data += '\x10\x23\x00\x00'
4396 send_wlanevent(url, uuid, data)
4397
4398 logger.info("EAP message: M1 missing Serial Number")
4399 data += '\x10\x24\x00\x00'
4400 send_wlanevent(url, uuid, data)
4401
4402 logger.info("EAP message: M1 missing Primary Device Type")
4403 data += '\x10\x42\x00\x00'
4404 send_wlanevent(url, uuid, data)
4405
4406 logger.info("EAP message: M1 missing Device Name")
4407 data += '\x10\x54\x00\x08' + 8*'\x00'
4408 send_wlanevent(url, uuid, data)
4409
4410 logger.info("EAP message: M1 missing RF Bands")
4411 data += '\x10\x11\x00\x00'
4412 send_wlanevent(url, uuid, data)
4413
4414 logger.info("EAP message: M1 missing Association State")
4415 data += '\x10\x3c\x00\x01\x00'
4416 send_wlanevent(url, uuid, data)
4417
4418 logger.info("EAP message: M1 missing Device Password ID")
4419 data += '\x10\x02\x00\x02\x00\x00'
4420 send_wlanevent(url, uuid, data)
4421
4422 logger.info("EAP message: M1 missing Configuration Error")
4423 data += '\x10\x12\x00\x02\x00\x00'
4424 send_wlanevent(url, uuid, data)
4425
4426 logger.info("EAP message: M1 missing OS Version")
4427 data += '\x10\x09\x00\x02\x00\x00'
4428 send_wlanevent(url, uuid, data)
4c3ae1c0 4429
24b7f282
JM
4430 logger.info("Check max concurrent requests")
4431 addr = (url.hostname, url.port)
4432 socks = {}
4433 for i in range(20):
4434 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4435 socket.IPPROTO_TCP)
e5d3e13a
JM
4436 socks[i].settimeout(10)
4437 socks[i].connect(addr)
24b7f282
JM
4438 for i in range(20):
4439 socks[i].send("GET / HTTP/1.1\r\n\r\n")
4440 count = 0
4441 for i in range(20):
4442 try:
4443 res = socks[i].recv(100)
4444 if "HTTP/1" in res:
4445 count += 1
4446 except:
4447 pass
4448 socks[i].close()
4449 logger.info("%d concurrent HTTP GET operations returned response" % count)
4450 if count < 10:
4451 raise Exception("Too few concurrent HTTP connections accepted")
4452
4453 logger.info("OOM in HTTP server")
4454 for func in [ "http_request_init", "httpread_create",
4455 "eloop_register_timeout;httpread_create",
9b35afd6 4456 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
24b7f282
JM
4457 "httpread_hdr_analyze" ]:
4458 with alloc_fail(dev[0], 1, func):
4459 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4460 socket.IPPROTO_TCP)
4461 sock.connect(addr)
4462 sock.send("GET / HTTP/1.1\r\n\r\n")
4463 try:
4464 sock.recv(100)
4465 except:
4466 pass
4467 sock.close()
4468
4469 logger.info("Invalid HTTP header")
4470 for req in [ " GET / HTTP/1.1\r\n\r\n",
4471 "HTTP/1.1 200 OK\r\n\r\n",
4472 "HTTP/\r\n\r\n",
4473 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4474 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4475 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4476 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4477 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4478 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4479 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4480 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
4481 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4482 socket.IPPROTO_TCP)
4483 sock.settimeout(0.1)
4484 sock.connect(addr)
4485 sock.send(req)
4486 try:
4487 sock.recv(100)
4488 except:
4489 pass
4490 sock.close()
4491
4492 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4493 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4494 socket.IPPROTO_TCP)
4495 sock.connect(addr)
4496 sock.send("NOTIFY / HTTP/1.1\r\n\r\n" + 4500*'a')
4497 try:
4498 sock.recv(100)
4499 except:
4500 pass
4501 sock.close()
4502
4503 conn = httplib.HTTPConnection(url.netloc)
4504 payload = '<foo'
4505 headers = { "Content-type": 'text/xml; charset="utf-8"',
4506 "Server": "Unspecified, UPnP/1.0, Unspecified",
4507 "HOST": url.netloc,
4508 "NT": "upnp:event",
4509 "SID": "uuid:" + uuid,
4510 "SEQ": "0",
4511 "Content-Length": str(len(payload)) }
4512 conn.request("NOTIFY", url.path, payload, headers)
4513 resp = conn.getresponse()
4514 if resp.status != 200:
4515 raise Exception("Unexpected HTTP response: %d" % resp.status)
4516
4517 conn = httplib.HTTPConnection(url.netloc)
4518 payload = '<WLANEvent foo></WLANEvent>'
4519 headers = { "Content-type": 'text/xml; charset="utf-8"',
4520 "Server": "Unspecified, UPnP/1.0, Unspecified",
4521 "HOST": url.netloc,
4522 "NT": "upnp:event",
4523 "SID": "uuid:" + uuid,
4524 "SEQ": "0",
4525 "Content-Length": str(len(payload)) }
4526 conn.request("NOTIFY", url.path, payload, headers)
4527 resp = conn.getresponse()
4528 if resp.status != 200:
4529 raise Exception("Unexpected HTTP response: %d" % resp.status)
4530
4531 with alloc_fail(dev[0], 1, "xml_get_first_item"):
4532 send_wlanevent(url, uuid, '')
4533
4534 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4535 send_wlanevent(url, uuid, 'foo')
4536
4537 for func in [ "wps_init",
4538 "wps_process_manufacturer",
4539 "wps_process_model_name",
4540 "wps_process_model_number",
4541 "wps_process_serial_number",
4542 "wps_process_dev_name" ]:
4543 with alloc_fail(dev[0], 1, func):
4544 send_wlanevent(url, uuid, m1)
4545
18478107
JM
4546 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4547 send_wlanevent(url, uuid, m1, no_response=True)
4548
4549 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4550 url2 = urlparse.urlparse(wps_event_url.replace('/event/', '/notfound/'))
4551 send_wlanevent(url2, uuid, m1, no_response=True)
4552
3d105cdf
JM
4553 logger.info("EAP message: M1")
4554 data = '\x0202:11:22:00:00:00'
4555 data += '\x10\x22\x00\x01\x04'
4556 data += '\x10\x47\x00\x10' + 16*'\x00'
4557 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4558 data += '\x10\x1a\x00\x10' + 16*'\x00'
4559 data += '\x10\x32\x00\xc0' + 192*'\x00'
4560 data += '\x10\x04\x00\x02\x00\x00'
4561 data += '\x10\x10\x00\x02\x00\x00'
4562 data += '\x10\x0d\x00\x01\x00'
4563 data += '\x10\x08\x00\x02\x00\x00'
4564 data += '\x10\x44\x00\x01\x00'
4565 data += '\x10\x21\x00\x00'
4566 data += '\x10\x23\x00\x00'
4567 data += '\x10\x24\x00\x00'
4568 data += '\x10\x42\x00\x00'
4569 data += '\x10\x54\x00\x08' + 8*'\x00'
4570 data += '\x10\x11\x00\x00'
4571 data += '\x10\x3c\x00\x01\x00'
4572 data += '\x10\x02\x00\x02\x00\x00'
4573 data += '\x10\x12\x00\x02\x00\x00'
4574 data += '\x10\x09\x00\x02\x00\x00'
4575 data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4576 dev[0].dump_monitor()
4577 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4578 send_wlanevent(url, uuid, data)
4579 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4580 if ev is not None:
4581 raise Exception("Unexpected enrollee add event")
4582 send_wlanevent(url, uuid, data)
4583 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4584 if ev is None:
4585 raise Exception("Enrollee add event not seen")
4586
fe67b945
JM
4587 with alloc_fail(dev[0], 1, "base64_encode;wps_er_soap_hdr"):
4588 send_wlanevent(url, uuid, data)
4589
4590 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4591 send_wlanevent(url, uuid, data)
4592
4593 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4594 send_wlanevent(url, uuid, data)
4595
4596 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4597 send_wlanevent(url, uuid, data)
4598
4c3ae1c0
JM
4599def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4600 """WPS ER HTTP protocol testing - no eventSubURL"""
6aaa661a
JM
4601 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4602 def handle_upnp_info(self):
4603 self.wfile.write(gen_upnp_info(eventSubURL=None))
4604 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4605 no_event_url=True)
4c3ae1c0
JM
4606
4607def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4608 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
6aaa661a
JM
4609 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4610 def handle_upnp_info(self):
4611 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4612 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4613 no_event_url=True)
4c3ae1c0
JM
4614
4615def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4616 """WPS ER HTTP protocol testing - subscribe OOM"""
4617 try:
4618 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4619 finally:
4620 dev[0].request("WPS_ER_STOP")
4621
4622def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4623 tests = [ (1, "http_client_url_parse"),
4624 (1, "wpabuf_alloc;wps_er_subscribe"),
4625 (1, "http_client_addr"),
9b35afd6 4626 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4c3ae1c0
JM
4627 (1, "eloop_register_timeout;http_client_addr") ]
4628 for count,func in tests:
4629 with alloc_fail(dev[0], count, func):
4630 server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
4631 server.handle_request()
4632 server.handle_request()
4633 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
6aaa661a
JM
4634
4635def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4636 """WPS ER HTTP protocol testing - no SID"""
4637 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4638 def handle_wps_event(self):
4639 self.wfile.write(gen_wps_event(sid=None))
4640 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4641
4642def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4643 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4644 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4645 def handle_wps_event(self):
4646 self.wfile.write(gen_wps_event(sid='FOO'))
4647 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4648
4649def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4650 """WPS ER HTTP protocol testing - invalid SID UUID"""
4651 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4652 def handle_wps_event(self):
4653 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4654 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4655
4656def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4657 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4658 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4659 def handle_wps_event(self):
4660 payload = ""
4661 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4662 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4663 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4664 'Connection: close\r\n' + \
4665 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4666 'Timeout: Second-1801\r\n' + \
4667 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4668 self.wfile.write(hdr + payload)
4669 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4670
4671def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4672 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4673 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4674 def handle_wps_event(self):
4675 payload = ""
4676 hdr = 'HTTP/1.1 FOO\r\n' + \
4677 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4678 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4679 'Connection: close\r\n' + \
4680 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4681 'Timeout: Second-1801\r\n' + \
4682 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4683 self.wfile.write(hdr + payload)
4684 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4685
4686def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4687 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4688 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4689 def handle_wps_control(self):
4690 payload = '''<?xml version="1.0"?>
4691<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4692<s:Body>
4693<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4694<NewDeviceInfo>Rk9P</NewDeviceInfo>
4695</u:GetDeviceInfoResponse>
4696</s:Body>
4697</s:Envelope>
4698'''
4699 self.wfile.write(gen_wps_control(payload_override=payload))
4700 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4701
4702def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4703 """WPS ER HTTP protocol testing - No device in UPnP info"""
4704 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4705 def handle_upnp_info(self):
4706 payload = '''<?xml version="1.0"?>
4707<root xmlns="urn:schemas-upnp-org:device-1-0">
4708<specVersion>
4709<major>1</major>
4710<minor>0</minor>
4711</specVersion>
4712</root>
4713'''
4714 hdr = 'HTTP/1.1 200 OK\r\n' + \
4715 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4716 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4717 'Connection: close\r\n' + \
4718 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4719 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4720 self.wfile.write(hdr + payload)
4721 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4722
4723def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4724 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4725 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4726 def handle_upnp_info(self):
4727 payload = '''<?xml version="1.0"?>
4728<root xmlns="urn:schemas-upnp-org:device-1-0">
4729<specVersion>
4730<major>1</major>
4731<minor>0</minor>
4732</specVersion>
4733<device>
4734</device>
4735</root>
4736'''
4737 hdr = 'HTTP/1.1 200 OK\r\n' + \
4738 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4739 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4740 'Connection: close\r\n' + \
4741 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4742 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4743 self.wfile.write(hdr + payload)
4744 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4745
4746def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4747 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4748 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4749 def handle_upnp_info(self):
4750 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4751 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4752
4753def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4754 """WPS ER HTTP protocol testing - no controlURL"""
4755 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4756 def handle_upnp_info(self):
4757 self.wfile.write(gen_upnp_info(controlURL=None))
4758 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4759 no_event_url=True)
4760
4761def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4762 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4763 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4764 def handle_upnp_info(self):
4765 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4766 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4767 no_event_url=True)
24b7f282
JM
4768
4769def test_ap_wps_http_timeout(dev, apdev):
4770 """WPS AP/ER and HTTP timeout"""
4771 try:
4772 _test_ap_wps_http_timeout(dev, apdev)
4773 finally:
4774 dev[0].request("WPS_ER_STOP")
4775
4776def _test_ap_wps_http_timeout(dev, apdev):
4777 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 4778 add_ssdp_ap(apdev[0], ap_uuid)
24b7f282
JM
4779
4780 location = ssdp_get_location(ap_uuid)
4781 url = urlparse.urlparse(location)
4782 addr = (url.hostname, url.port)
4783 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4784 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4785 socket.IPPROTO_TCP)
4786 sock.connect(addr)
4787 sock.send("G")
4788
4789 class DummyServer(SocketServer.StreamRequestHandler):
4790 def handle(self):
4791 logger.debug("DummyServer - start 31 sec wait")
4792 time.sleep(31)
4793 logger.debug("DummyServer - wait done")
4794
4795 logger.debug("Start WPS ER")
4796 server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4797 wait_m_search=True)
4798
4799 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4800 # This will wait for 31 seconds..
4801 server.handle_request()
4802
4803 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4804 try:
4805 sock.send("ET / HTTP/1.1\r\n\r\n")
4806 res = sock.recv(100)
4807 sock.close()
4808 except:
4809 pass
4810
4811def test_ap_wps_er_url_parse(dev, apdev):
4812 """WPS ER and URL parsing special cases"""
4813 try:
4814 _test_ap_wps_er_url_parse(dev, apdev)
4815 finally:
4816 dev[0].request("WPS_ER_STOP")
4817
4818def _test_ap_wps_er_url_parse(dev, apdev):
4819 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4820 sock.settimeout(1)
4821 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4822 sock.bind(("239.255.255.250", 1900))
4823 dev[0].request("WPS_ER_START ifname=lo")
4824 (msg,addr) = sock.recvfrom(1000)
4825 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4826 if "M-SEARCH" not in msg:
4827 raise Exception("Not an M-SEARCH")
4828 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)
4829 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4830 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)
4831 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4832 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)
4833 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4834
4835 sock.close()
4836
4837def test_ap_wps_er_link_update(dev, apdev):
4838 """WPS ER and link update special cases"""
4839 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4840 def handle_upnp_info(self):
4841 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4842 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4843
4844 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4845 def handle_others(self, data):
4846 if "GET / " in data:
4847 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4848 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4849 location_url='http://127.0.0.1:12345')
4850
4851def test_ap_wps_er_http_client(dev, apdev):
4852 """WPS ER and HTTP client special cases"""
4853 with alloc_fail(dev[0], 1, "http_link_update"):
4854 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4855
4856 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4857 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4858
4859 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4860 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4861
4862 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4863 def handle_upnp_info(self):
4864 self.wfile.write("GET / HTTP/1.1\r\n\r\n")
4865 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4866 no_event_url=True)
4867
4868def test_ap_wps_init_oom(dev, apdev):
4869 """wps_init OOM cases"""
4870 ssid = "test-wps"
4871 appin = "12345670"
4872 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4873 "ap_pin": appin }
8b8a1864 4874 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4875 pin = dev[0].wps_read_pin()
4876
4877 with alloc_fail(hapd, 1, "wps_init"):
4878 hapd.request("WPS_PIN any " + pin)
4879 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4880 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4881 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4882 if ev is None:
4883 raise Exception("No EAP failure reported")
4884 dev[0].request("WPS_CANCEL")
4885
4886 with alloc_fail(dev[0], 2, "wps_init"):
4887 hapd.request("WPS_PIN any " + pin)
4888 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4889 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4890 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4891 if ev is None:
4892 raise Exception("No EAP failure reported")
4893 dev[0].request("WPS_CANCEL")
4894
4895 with alloc_fail(dev[0], 2, "wps_init"):
4896 hapd.request("WPS_PBC")
4897 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4898 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4899 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4900 if ev is None:
4901 raise Exception("No EAP failure reported")
4902 dev[0].request("WPS_CANCEL")
4903
4904 dev[0].dump_monitor()
4905 new_ssid = "wps-new-ssid"
4906 new_passphrase = "1234567890"
4907 with alloc_fail(dev[0], 3, "wps_init"):
4908 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4909 new_passphrase, no_wait=True)
4910 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4911 if ev is None:
4912 raise Exception("No EAP failure reported")
4913
4914 dev[0].flush_scan_cache()
4915
9fd6804d 4916@remote_compatible
24b7f282
JM
4917def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4918 """WPS and invalid IE in Association Request frame"""
4919 ssid = "test-wps"
4920 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4921 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4922 pin = "12345670"
4923 hapd.request("WPS_PIN any " + pin)
4924 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4925 try:
4926 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4927 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4928 for i in range(5):
4929 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4930 if ev and "vendor=14122" in ev:
4931 break
4932 if ev is None or "vendor=14122" not in ev:
4933 raise Exception("EAP-WSC not started")
4934 dev[0].request("WPS_CANCEL")
4935 finally:
4936 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
4937
4938def test_ap_wps_pbc_pin_mismatch(dev, apdev):
4939 """WPS PBC/PIN mismatch"""
4940 ssid = "test-wps"
4941 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4942 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4943 hapd.request("SET wps_version_number 0x10")
4944 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4945 hapd.request("WPS_PBC")
4946 pin = dev[0].wps_read_pin()
4947 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4948 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4949 if ev is None:
4950 raise Exception("Scan did not complete")
4951 dev[0].request("WPS_CANCEL")
4952
4953 hapd.request("WPS_CANCEL")
4954 dev[0].flush_scan_cache()
4955
9fd6804d 4956@remote_compatible
24b7f282
JM
4957def test_ap_wps_ie_invalid(dev, apdev):
4958 """WPS PIN attempt with AP that has invalid WSC IE"""
4959 ssid = "test-wps"
4960 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4961 "vendor_elements": "dd050050f20410" }
8b8a1864 4962 hapd = hostapd.add_ap(apdev[0], params)
24b7f282 4963 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
8b8a1864 4964 hostapd.add_ap(apdev[1], params)
24b7f282
JM
4965 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4966 pin = dev[0].wps_read_pin()
4967 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4968 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4969 if ev is None:
4970 raise Exception("Scan did not complete")
4971 dev[0].request("WPS_CANCEL")
4972
9fd6804d 4973@remote_compatible
24b7f282
JM
4974def test_ap_wps_scan_prio_order(dev, apdev):
4975 """WPS scan priority ordering"""
4976 ssid = "test-wps"
4977 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4978 hapd = hostapd.add_ap(apdev[0], params)
24b7f282 4979 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
8b8a1864 4980 hostapd.add_ap(apdev[1], params)
24b7f282
JM
4981 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4982 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
4983 pin = dev[0].wps_read_pin()
4984 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4985 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4986 if ev is None:
4987 raise Exception("Scan did not complete")
4988 dev[0].request("WPS_CANCEL")
4989
4990def test_ap_wps_probe_req_ie_oom(dev, apdev):
4991 """WPS ProbeReq IE OOM"""
4992 ssid = "test-wps"
4993 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4994 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4995 pin = dev[0].wps_read_pin()
4996 hapd.request("WPS_PIN any " + pin)
4997 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4998 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
4999 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5000 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5001 if ev is None:
5002 raise Exception("Association not seen")
5003 dev[0].request("WPS_CANCEL")
161c8515 5004 dev[0].wait_disconnected()
24b7f282
JM
5005
5006 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
5007 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5008 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5009 if ev is None:
5010 raise Exception("Association not seen")
5011 dev[0].request("WPS_CANCEL")
161c8515
JM
5012 hapd.disable()
5013 dev[0].request("REMOVE_NETWORK all")
5014 dev[0].wait_disconnected()
5015 time.sleep(0.2)
5016 dev[0].flush_scan_cache()
24b7f282
JM
5017
5018def test_ap_wps_assoc_req_ie_oom(dev, apdev):
5019 """WPS AssocReq IE OOM"""
5020 ssid = "test-wps"
5021 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 5022 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5023 pin = dev[0].wps_read_pin()
5024 hapd.request("WPS_PIN any " + pin)
5025 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5026 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
5027 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5028 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5029 if ev is None:
5030 raise Exception("Association not seen")
5031 dev[0].request("WPS_CANCEL")
5032
5033def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
5034 """WPS AssocResp IE OOM"""
5035 ssid = "test-wps"
5036 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 5037 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5038 pin = dev[0].wps_read_pin()
5039 hapd.request("WPS_PIN any " + pin)
5040 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5041 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
5042 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5043 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5044 if ev is None:
5045 raise Exception("Association not seen")
5046 dev[0].request("WPS_CANCEL")
5047
9fd6804d 5048@remote_compatible
24b7f282
JM
5049def test_ap_wps_bss_info_errors(dev, apdev):
5050 """WPS BSS info errors"""
5051 params = { "ssid": "1",
5052 "vendor_elements": "dd0e0050f20410440001ff101100010a" }
8b8a1864 5053 hostapd.add_ap(apdev[0], params)
24b7f282 5054 params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
8b8a1864 5055 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5056 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5057 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5058 bss = dev[0].get_bss(apdev[0]['bssid'])
5059 logger.info("BSS: " + str(bss))
5060 if "wps_state" in bss:
5061 raise Exception("Unexpected wps_state in BSS info")
5062 if 'wps_device_name' not in bss:
5063 raise Exception("No wps_device_name in BSS info")
5064 if bss['wps_device_name'] != '_':
5065 raise Exception("Unexpected wps_device_name value")
5066 bss = dev[0].get_bss(apdev[1]['bssid'])
5067 logger.info("BSS: " + str(bss))
5068
5069 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5070 bss = dev[0].get_bss(apdev[0]['bssid'])
5071 logger.info("BSS(OOM): " + str(bss))
5072
5073def wps_run_pbc_fail_ap(apdev, dev, hapd):
5074 hapd.request("WPS_PBC")
5075 dev.scan_for_bss(apdev['bssid'], freq="2412")
5076 dev.request("WPS_PBC " + apdev['bssid'])
5077 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5078 if ev is None:
5079 raise Exception("No EAP failure reported")
5080 dev.request("WPS_CANCEL")
5081 dev.wait_disconnected()
5082 for i in range(5):
5083 try:
5084 dev.flush_scan_cache()
5085 break
5086 except Exception, e:
5087 if str(e).startswith("Failed to trigger scan"):
5088 # Try again
5089 time.sleep(1)
5090 else:
5091 raise
5092
5093def wps_run_pbc_fail(apdev, dev):
5094 hapd = wps_start_ap(apdev)
5095 wps_run_pbc_fail_ap(apdev, dev, hapd)
5096
9fd6804d 5097@remote_compatible
24b7f282
JM
5098def test_ap_wps_pk_oom(dev, apdev):
5099 """WPS and public key OOM"""
5100 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5101 wps_run_pbc_fail(apdev[0], dev[0])
5102
9fd6804d 5103@remote_compatible
24b7f282
JM
5104def test_ap_wps_pk_oom_ap(dev, apdev):
5105 """WPS and public key OOM on AP"""
5106 hapd = wps_start_ap(apdev[0])
5107 with alloc_fail(hapd, 1, "wps_build_public_key"):
5108 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5109
9fd6804d 5110@remote_compatible
24b7f282
JM
5111def test_ap_wps_encr_oom_ap(dev, apdev):
5112 """WPS and encrypted settings decryption OOM on AP"""
5113 hapd = wps_start_ap(apdev[0])
5114 pin = dev[0].wps_read_pin()
5115 hapd.request("WPS_PIN any " + pin)
5116 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5117 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5118 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5119 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5120 if ev is None:
5121 raise Exception("No WPS-FAIL reported")
5122 dev[0].request("WPS_CANCEL")
5123 dev[0].wait_disconnected()
5124
9fd6804d 5125@remote_compatible
24b7f282
JM
5126def test_ap_wps_encr_no_random_ap(dev, apdev):
5127 """WPS and no random data available for encryption on AP"""
5128 hapd = wps_start_ap(apdev[0])
5129 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5130 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5131
9fd6804d 5132@remote_compatible
24b7f282
JM
5133def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5134 """WPS and no random data available for e-hash on STA"""
5135 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5136 wps_run_pbc_fail(apdev[0], dev[0])
5137
9fd6804d 5138@remote_compatible
24b7f282
JM
5139def test_ap_wps_m1_no_random(dev, apdev):
5140 """WPS and no random for M1 on STA"""
5141 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5142 wps_run_pbc_fail(apdev[0], dev[0])
5143
9fd6804d 5144@remote_compatible
24b7f282
JM
5145def test_ap_wps_m1_oom(dev, apdev):
5146 """WPS and OOM for M1 on STA"""
5147 with alloc_fail(dev[0], 1, "wps_build_m1"):
5148 wps_run_pbc_fail(apdev[0], dev[0])
5149
9fd6804d 5150@remote_compatible
24b7f282
JM
5151def test_ap_wps_m3_oom(dev, apdev):
5152 """WPS and OOM for M3 on STA"""
5153 with alloc_fail(dev[0], 1, "wps_build_m3"):
5154 wps_run_pbc_fail(apdev[0], dev[0])
5155
9fd6804d 5156@remote_compatible
24b7f282
JM
5157def test_ap_wps_m5_oom(dev, apdev):
5158 """WPS and OOM for M5 on STA"""
5159 hapd = wps_start_ap(apdev[0])
5160 hapd.request("WPS_PBC")
5161 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5162 for i in range(1, 3):
5163 with alloc_fail(dev[0], i, "wps_build_m5"):
5164 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5165 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5166 if ev is None:
5167 raise Exception("No EAP failure reported")
5168 dev[0].request("WPS_CANCEL")
5169 dev[0].wait_disconnected()
5170 dev[0].flush_scan_cache()
5171
9fd6804d 5172@remote_compatible
24b7f282
JM
5173def test_ap_wps_m5_no_random(dev, apdev):
5174 """WPS and no random for M5 on STA"""
5175 with fail_test(dev[0], 1,
5176 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5177 wps_run_pbc_fail(apdev[0], dev[0])
5178
9fd6804d 5179@remote_compatible
24b7f282
JM
5180def test_ap_wps_m7_oom(dev, apdev):
5181 """WPS and OOM for M7 on STA"""
5182 hapd = wps_start_ap(apdev[0])
5183 hapd.request("WPS_PBC")
5184 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5185 for i in range(1, 3):
5186 with alloc_fail(dev[0], i, "wps_build_m7"):
5187 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5188 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5189 if ev is None:
5190 raise Exception("No EAP failure reported")
5191 dev[0].request("WPS_CANCEL")
5192 dev[0].wait_disconnected()
5193 dev[0].flush_scan_cache()
5194
9fd6804d 5195@remote_compatible
24b7f282
JM
5196def test_ap_wps_m7_no_random(dev, apdev):
5197 """WPS and no random for M7 on STA"""
5198 with fail_test(dev[0], 1,
5199 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5200 wps_run_pbc_fail(apdev[0], dev[0])
5201
9fd6804d 5202@remote_compatible
24b7f282
JM
5203def test_ap_wps_wsc_done_oom(dev, apdev):
5204 """WPS and OOM for WSC_Done on STA"""
5205 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5206 wps_run_pbc_fail(apdev[0], dev[0])
5207
5208def test_ap_wps_random_psk_fail(dev, apdev):
5209 """WPS and no random for PSK on AP"""
5210 ssid = "test-wps"
5211 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5212 appin = "12345670"
5213 try:
5214 os.remove(pskfile)
5215 except:
5216 pass
5217
5218 try:
5219 with open(pskfile, "w") as f:
5220 f.write("# WPA PSKs\n")
5221
5222 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5223 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5224 "rsn_pairwise": "CCMP", "ap_pin": appin,
5225 "wpa_psk_file": pskfile }
8b8a1864 5226 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5227
5228 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5229 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5230 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5231 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5232 if ev is None:
5233 raise Exception("No EAP failure reported")
5234 dev[0].request("WPS_CANCEL")
5235 dev[0].wait_disconnected()
5236
5237 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5238 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5239
5240 with alloc_fail(hapd, 1, "wps_build_cred"):
5241 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5242
5243 with alloc_fail(hapd, 2, "wps_build_cred"):
5244 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5245 finally:
5246 os.remove(pskfile)
5247
5248def wps_ext_eap_identity_req(dev, hapd, bssid):
5249 logger.debug("EAP-Identity/Request")
5250 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5251 if ev is None:
5252 raise Exception("Timeout on EAPOL-TX from hostapd")
5253 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5254 if "OK" not in res:
5255 raise Exception("EAPOL_RX to wpa_supplicant failed")
5256
5257def wps_ext_eap_identity_resp(hapd, dev, addr):
5258 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5259 if ev is None:
5260 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5261 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5262 if "OK" not in res:
5263 raise Exception("EAPOL_RX to hostapd failed")
5264
5265def wps_ext_eap_wsc(dst, src, src_addr, msg):
5266 logger.debug(msg)
5267 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5268 if ev is None:
5269 raise Exception("Timeout on EAPOL-TX")
5270 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5271 if "OK" not in res:
5272 raise Exception("EAPOL_RX failed")
5273
7511ead0 5274def wps_start_ext(apdev, dev, pbc=False, pin=None):
24b7f282
JM
5275 addr = dev.own_addr()
5276 bssid = apdev['bssid']
5277 ssid = "test-wps-conf"
5278 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5279 "wpa_passphrase": "12345678", "wpa": "2",
5280 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
afc26df2 5281 hapd = hostapd.add_ap(apdev, params)
24b7f282 5282
d1883671
JM
5283 if pbc:
5284 hapd.request("WPS_PBC")
5285 else:
7511ead0
JM
5286 if pin is None:
5287 pin = dev.wps_read_pin()
d1883671 5288 hapd.request("WPS_PIN any " + pin)
24b7f282
JM
5289 dev.scan_for_bss(bssid, freq="2412")
5290 hapd.request("SET ext_eapol_frame_io 1")
5291 dev.request("SET ext_eapol_frame_io 1")
5292
d1883671
JM
5293 if pbc:
5294 dev.request("WPS_PBC " + bssid)
5295 else:
5296 dev.request("WPS_PIN " + bssid + " " + pin)
24b7f282
JM
5297 return addr,bssid,hapd
5298
5299def wps_auth_corrupt(dst, src, addr):
5300 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5301 if ev is None:
5302 raise Exception("Timeout on EAPOL-TX")
5303 src.request("SET ext_eapol_frame_io 0")
5304 dst.request("SET ext_eapol_frame_io 0")
5305 msg = ev.split(' ')[2]
5306 if msg[-24:-16] != '10050008':
5307 raise Exception("Could not find Authenticator attribute")
5308 # Corrupt Authenticator value
5309 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5310 res = dst.request("EAPOL_RX " + addr + " " + msg)
5311 if "OK" not in res:
5312 raise Exception("EAPOL_RX failed")
5313
5314def wps_fail_finish(hapd, dev, fail_str):
5315 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5316 if ev is None:
5317 raise Exception("WPS-FAIL not indicated")
5318 if fail_str not in ev:
5319 raise Exception("Unexpected WPS-FAIL value: " + ev)
5320 dev.request("WPS_CANCEL")
5321 dev.wait_disconnected()
5322
5323def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5324 wps_auth_corrupt(dev, hapd, bssid)
5325 wps_fail_finish(hapd, dev, fail_str)
5326
5327def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5328 wps_auth_corrupt(hapd, dev, addr)
5329 wps_fail_finish(hapd, dev, fail_str)
5330
5331def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5332 """WPS and Authenticator attribute mismatch in M2"""
5333 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5334 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5335 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5336 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5337 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5338 logger.debug("M2")
5339 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5340
5341def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5342 """WPS and Authenticator attribute mismatch in M3"""
5343 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5344 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5345 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5346 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5347 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5348 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5349 logger.debug("M3")
5350 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5351
5352def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5353 """WPS and Authenticator attribute mismatch in M4"""
5354 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5355 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5356 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5357 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5358 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5359 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5360 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5361 logger.debug("M4")
5362 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5363
5364def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5365 """WPS and Authenticator attribute mismatch in M5"""
5366 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5367 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5368 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5369 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5370 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5371 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5372 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5373 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5374 logger.debug("M5")
5375 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5376
5377def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5378 """WPS and Authenticator attribute mismatch in M6"""
5379 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5380 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5381 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5382 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5383 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5384 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5385 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5386 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5387 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5388 logger.debug("M6")
5389 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5390
5391def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5392 """WPS and Authenticator attribute mismatch in M7"""
5393 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5394 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5395 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5396 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5397 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5398 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5399 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5400 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5401 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5402 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5403 logger.debug("M7")
5404 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5405
5406def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5407 """WPS and Authenticator attribute mismatch in M8"""
5408 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5409 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5410 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5411 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5412 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5413 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5414 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5415 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5416 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5417 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5418 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5419 logger.debug("M8")
5420 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5421
5422def test_ap_wps_authenticator_missing_m2(dev, apdev):
5423 """WPS and Authenticator attribute missing from M2"""
5424 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5425 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5426 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5427 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5428 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5429 logger.debug("M2")
5430 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5431 if ev is None:
5432 raise Exception("Timeout on EAPOL-TX")
5433 hapd.request("SET ext_eapol_frame_io 0")
5434 dev[0].request("SET ext_eapol_frame_io 0")
5435 msg = ev.split(' ')[2]
5436 if msg[-24:-16] != '10050008':
5437 raise Exception("Could not find Authenticator attribute")
5438 # Remove Authenticator value
5439 msg = msg[:-24]
5440 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5441 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5442 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5443 if "OK" not in res:
5444 raise Exception("EAPOL_RX failed")
5445 wps_fail_finish(hapd, dev[0], "msg=5")
5446
d1883671
JM
5447def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5448 """WPS and M2 with different Device Password ID (P2P)"""
5449 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5450 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5451 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5452 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5453 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5454 logger.debug("M2")
5455 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5456 if ev is None:
5457 raise Exception("Timeout on EAPOL-TX")
5458 hapd.request("SET ext_eapol_frame_io 0")
5459 dev[0].request("SET ext_eapol_frame_io 0")
5460 msg = ev.split(' ')[2]
5461 if msg[722:730] != '10120002':
5462 raise Exception("Could not find Device Password ID attribute")
5463 # Replace Device Password ID value. This will fail Authenticator check, but
5464 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5465 # log.
5466 msg = msg[0:730] + "0005" + msg[734:]
5467 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5468 if "OK" not in res:
5469 raise Exception("EAPOL_RX failed")
5470 wps_fail_finish(hapd, dev[0], "msg=5")
5471
5472def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5473 """WPS and M2 with different Device Password ID (PIN to PBC)"""
5474 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5475 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5476 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5477 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5478 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5479 logger.debug("M2")
5480 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5481 if ev is None:
5482 raise Exception("Timeout on EAPOL-TX")
5483 hapd.request("SET ext_eapol_frame_io 0")
5484 dev[0].request("SET ext_eapol_frame_io 0")
5485 msg = ev.split(' ')[2]
5486 if msg[722:730] != '10120002':
5487 raise Exception("Could not find Device Password ID attribute")
5488 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5489 msg = msg[0:730] + "0004" + msg[734:]
5490 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5491 if "OK" not in res:
5492 raise Exception("EAPOL_RX failed")
5493 wps_fail_finish(hapd, dev[0], "msg=5")
5494
5495def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5496 """WPS and M2 with different Device Password ID (PBC to PIN)"""
5497 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5498 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5499 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5500 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5501 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5502 logger.debug("M2")
5503 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5504 if ev is None:
5505 raise Exception("Timeout on EAPOL-TX")
5506 hapd.request("SET ext_eapol_frame_io 0")
5507 dev[0].request("SET ext_eapol_frame_io 0")
5508 msg = ev.split(' ')[2]
5509 if msg[722:730] != '10120002':
5510 raise Exception("Could not find Device Password ID attribute")
5511 # Replace Device Password ID value. This will fail Authenticator check, but
5512 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5513 # log.
5514 msg = msg[0:730] + "0000" + msg[734:]
5515 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5516 if "OK" not in res:
5517 raise Exception("EAPOL_RX failed")
5518 wps_fail_finish(hapd, dev[0], "msg=5")
5519 dev[0].flush_scan_cache()
5520
5521def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5522 """WPS and M2 without Device Password ID"""
5523 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5524 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5525 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5526 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5527 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5528 logger.debug("M2")
5529 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5530 if ev is None:
5531 raise Exception("Timeout on EAPOL-TX")
5532 hapd.request("SET ext_eapol_frame_io 0")
5533 dev[0].request("SET ext_eapol_frame_io 0")
5534 msg = ev.split(' ')[2]
5535 if msg[722:730] != '10120002':
5536 raise Exception("Could not find Device Password ID attribute")
5537 # Remove Device Password ID value. This will fail Authenticator check, but
5538 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5539 # log.
5540 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5541 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5542 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5543 if "OK" not in res:
5544 raise Exception("EAPOL_RX failed")
5545 wps_fail_finish(hapd, dev[0], "msg=5")
5546
5547def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5548 """WPS and M2 without Registrar Nonce"""
5549 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5550 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5551 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5552 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5553 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5554 logger.debug("M2")
5555 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5556 if ev is None:
5557 raise Exception("Timeout on EAPOL-TX")
5558 hapd.request("SET ext_eapol_frame_io 0")
5559 dev[0].request("SET ext_eapol_frame_io 0")
5560 msg = ev.split(' ')[2]
5561 if msg[96:104] != '10390010':
5562 raise Exception("Could not find Registrar Nonce attribute")
5563 # Remove Registrar Nonce. This will fail Authenticator check, but
5564 # allows the code path in wps_process_registrar_nonce() to be checked from
5565 # the debug log.
5566 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5567 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5568 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5569 if "OK" not in res:
5570 raise Exception("EAPOL_RX failed")
5571 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5572 if ev is None:
5573 raise Exception("Disconnect event not seen")
5574 dev[0].request("WPS_CANCEL")
5575 dev[0].flush_scan_cache()
5576
5577def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5578 """WPS and M2 without Enrollee Nonce"""
5579 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5580 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5581 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5582 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5583 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5584 logger.debug("M2")
5585 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5586 if ev is None:
5587 raise Exception("Timeout on EAPOL-TX")
5588 hapd.request("SET ext_eapol_frame_io 0")
5589 dev[0].request("SET ext_eapol_frame_io 0")
5590 msg = ev.split(' ')[2]
5591 if msg[56:64] != '101a0010':
5592 raise Exception("Could not find enrollee Nonce attribute")
5593 # Remove Enrollee Nonce. This will fail Authenticator check, but
5594 # allows the code path in wps_process_enrollee_nonce() to be checked from
5595 # the debug log.
5596 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5597 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5598 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5599 if "OK" not in res:
5600 raise Exception("EAPOL_RX failed")
5601 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5602 if ev is None:
5603 raise Exception("Disconnect event not seen")
5604 dev[0].request("WPS_CANCEL")
5605 dev[0].flush_scan_cache()
5606
5607def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5608 """WPS and M2 without UUID-R"""
5609 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5610 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5611 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5612 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5613 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5614 logger.debug("M2")
5615 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5616 if ev is None:
5617 raise Exception("Timeout on EAPOL-TX")
5618 hapd.request("SET ext_eapol_frame_io 0")
5619 dev[0].request("SET ext_eapol_frame_io 0")
5620 msg = ev.split(' ')[2]
5621 if msg[136:144] != '10480010':
5622 raise Exception("Could not find enrollee Nonce attribute")
5623 # Remove UUID-R. This will fail Authenticator check, but allows the code
5624 # path in wps_process_uuid_r() to be checked from the debug log.
5625 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5626 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5627 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5628 if "OK" not in res:
5629 raise Exception("EAPOL_RX failed")
5630 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5631 if ev is None:
5632 raise Exception("Disconnect event not seen")
5633 dev[0].request("WPS_CANCEL")
5634 dev[0].flush_scan_cache()
5635
5636def test_ap_wps_m2_invalid(dev, apdev):
5637 """WPS and M2 parsing failure"""
5638 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5639 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5640 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5641 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5642 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5643 logger.debug("M2")
5644 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5645 if ev is None:
5646 raise Exception("Timeout on EAPOL-TX")
5647 hapd.request("SET ext_eapol_frame_io 0")
5648 dev[0].request("SET ext_eapol_frame_io 0")
5649 msg = ev.split(' ')[2]
5650 if msg[136:144] != '10480010':
5651 raise Exception("Could not find enrollee Nonce attribute")
5652 # Remove UUID-R. This will fail Authenticator check, but allows the code
5653 # path in wps_process_uuid_r() to be checked from the debug log.
5654 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5655 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5656 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5657 if "OK" not in res:
5658 raise Exception("EAPOL_RX failed")
5659 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5660 if ev is None:
5661 raise Exception("Disconnect event not seen")
5662 dev[0].request("WPS_CANCEL")
5663 dev[0].flush_scan_cache()
5664
5665def test_ap_wps_m2_missing_msg_type(dev, apdev):
5666 """WPS and M2 without Message Type"""
5667 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5668 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5669 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5670 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5671 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5672 logger.debug("M2")
5673 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5674 if ev is None:
5675 raise Exception("Timeout on EAPOL-TX")
5676 hapd.request("SET ext_eapol_frame_io 0")
5677 dev[0].request("SET ext_eapol_frame_io 0")
5678 msg = ev.split(' ')[2]
5679 if msg[46:54] != '10220001':
5680 raise Exception("Could not find Message Type attribute")
5681 # Remove Message Type. This will fail Authenticator check, but allows the
5682 # code path in wps_process_wsc_msg() to be checked from the debug log.
5683 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5684 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5685 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5686 if "OK" not in res:
5687 raise Exception("EAPOL_RX failed")
5688 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5689 if ev is None:
5690 raise Exception("Disconnect event not seen")
5691 dev[0].request("WPS_CANCEL")
5692 dev[0].flush_scan_cache()
5693
5694def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5695 """WPS and M2 but unknown Message Type"""
5696 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5697 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5698 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5699 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5700 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5701 logger.debug("M2")
5702 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5703 if ev is None:
5704 raise Exception("Timeout on EAPOL-TX")
5705 hapd.request("SET ext_eapol_frame_io 0")
5706 dev[0].request("SET ext_eapol_frame_io 0")
5707 msg = ev.split(' ')[2]
5708 if msg[46:54] != '10220001':
5709 raise Exception("Could not find Message Type attribute")
5710 # Replace Message Type value. This will be rejected.
5711 msg = msg[0:54] + "00" + msg[56:]
5712 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5713 if "OK" not in res:
5714 raise Exception("EAPOL_RX failed")
5715 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5716 if ev is None:
5717 raise Exception("Disconnect event not seen")
5718 dev[0].request("WPS_CANCEL")
5719 dev[0].flush_scan_cache()
5720
5721def test_ap_wps_m2_unknown_opcode(dev, apdev):
5722 """WPS and M2 but unknown opcode"""
5723 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5724 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5725 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5726 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5727 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5728 logger.debug("M2")
5729 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5730 if ev is None:
5731 raise Exception("Timeout on EAPOL-TX")
5732 hapd.request("SET ext_eapol_frame_io 0")
5733 dev[0].request("SET ext_eapol_frame_io 0")
5734 msg = ev.split(' ')[2]
5735 # Replace opcode. This will be discarded in EAP-WSC processing.
5736 msg = msg[0:32] + "00" + msg[34:]
5737 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5738 if "OK" not in res:
5739 raise Exception("EAPOL_RX failed")
5740 dev[0].request("WPS_CANCEL")
5741 dev[0].wait_disconnected()
5742 dev[0].flush_scan_cache()
5743
5744def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5745 """WPS and M2 but unknown opcode (WSC_Start)"""
5746 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5747 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5748 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5749 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5750 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5751 logger.debug("M2")
5752 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5753 if ev is None:
5754 raise Exception("Timeout on EAPOL-TX")
5755 hapd.request("SET ext_eapol_frame_io 0")
5756 dev[0].request("SET ext_eapol_frame_io 0")
5757 msg = ev.split(' ')[2]
5758 # Replace opcode. This will be discarded in EAP-WSC processing.
5759 msg = msg[0:32] + "01" + msg[34:]
5760 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5761 if "OK" not in res:
5762 raise Exception("EAPOL_RX failed")
5763 dev[0].request("WPS_CANCEL")
5764 dev[0].wait_disconnected()
5765 dev[0].flush_scan_cache()
5766
5767def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5768 """WPS and M2 but unknown opcode (WSC_Done)"""
5769 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5770 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5771 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5772 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5773 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5774 logger.debug("M2")
5775 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5776 if ev is None:
5777 raise Exception("Timeout on EAPOL-TX")
5778 hapd.request("SET ext_eapol_frame_io 0")
5779 dev[0].request("SET ext_eapol_frame_io 0")
5780 msg = ev.split(' ')[2]
5781 # Replace opcode. This will be discarded in WPS Enrollee processing.
5782 msg = msg[0:32] + "05" + msg[34:]
5783 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5784 if "OK" not in res:
5785 raise Exception("EAPOL_RX failed")
5786 dev[0].request("WPS_CANCEL")
5787 dev[0].wait_disconnected()
5788 dev[0].flush_scan_cache()
5789
5790def wps_m2_but_other(dev, apdev, title, msgtype):
5791 addr,bssid,hapd = wps_start_ext(apdev, dev)
5792 wps_ext_eap_identity_req(dev, hapd, bssid)
5793 wps_ext_eap_identity_resp(hapd, dev, addr)
5794 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5795 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5796 logger.debug(title)
5797 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5798 if ev is None:
5799 raise Exception("Timeout on EAPOL-TX")
5800 hapd.request("SET ext_eapol_frame_io 0")
5801 dev.request("SET ext_eapol_frame_io 0")
5802 msg = ev.split(' ')[2]
5803 if msg[46:54] != '10220001':
5804 raise Exception("Could not find Message Type attribute")
5805 # Replace Message Type value. This will be rejected.
5806 msg = msg[0:54] + msgtype + msg[56:]
5807 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5808 if "OK" not in res:
5809 raise Exception("EAPOL_RX failed")
5810 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5811 if ev is None:
5812 raise Exception("WPS-FAIL event not seen")
5813 dev.request("WPS_CANCEL")
5814 dev.wait_disconnected()
5815
5816def wps_m4_but_other(dev, apdev, title, msgtype):
5817 addr,bssid,hapd = wps_start_ext(apdev, dev)
5818 wps_ext_eap_identity_req(dev, hapd, bssid)
5819 wps_ext_eap_identity_resp(hapd, dev, addr)
5820 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5821 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5822 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5823 wps_ext_eap_wsc(hapd, dev, addr, "M3")
5824 logger.debug(title)
5825 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5826 if ev is None:
5827 raise Exception("Timeout on EAPOL-TX")
5828 hapd.request("SET ext_eapol_frame_io 0")
5829 dev.request("SET ext_eapol_frame_io 0")
5830 msg = ev.split(' ')[2]
5831 if msg[46:54] != '10220001':
5832 raise Exception("Could not find Message Type attribute")
5833 # Replace Message Type value. This will be rejected.
5834 msg = msg[0:54] + msgtype + msg[56:]
5835 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5836 if "OK" not in res:
5837 raise Exception("EAPOL_RX failed")
5838 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5839 if ev is None:
5840 raise Exception("WPS-FAIL event not seen")
5841 dev.request("WPS_CANCEL")
5842 dev.wait_disconnected()
5843
5844def test_ap_wps_m2_msg_type_m4(dev, apdev):
5845 """WPS and M2 but Message Type M4"""
5846 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5847
5848def test_ap_wps_m2_msg_type_m6(dev, apdev):
5849 """WPS and M2 but Message Type M6"""
5850 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5851
5852def test_ap_wps_m2_msg_type_m8(dev, apdev):
5853 """WPS and M2 but Message Type M8"""
5854 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5855
5856def test_ap_wps_m4_msg_type_m2(dev, apdev):
5857 """WPS and M4 but Message Type M2"""
5858 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5859
5860def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5861 """WPS and M4 but Message Type M2D"""
5862 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5863
9fd6804d 5864@remote_compatible
24b7f282
JM
5865def test_ap_wps_config_methods(dev, apdev):
5866 """WPS configuration method parsing"""
5867 ssid = "test-wps-conf"
5868 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5869 "wpa_passphrase": "12345678", "wpa": "2",
5870 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5871 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
8b8a1864 5872 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5873 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5874 "wpa_passphrase": "12345678", "wpa": "2",
5875 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5876 "config_methods": "display push_button" }
8b8a1864 5877 hapd2 = hostapd.add_ap(apdev[1], params)
476daa05
JM
5878
5879def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5880 """WPS UPnP SetSelectedRegistrar protocol testing"""
5881 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 5882 hapd = add_ssdp_ap(apdev[0], ap_uuid)
476daa05
JM
5883
5884 location = ssdp_get_location(ap_uuid)
5885 urls = upnp_get_urls(location)
5886 eventurl = urlparse.urlparse(urls['event_sub_url'])
5887 ctrlurl = urlparse.urlparse(urls['control_url'])
5888 url = urlparse.urlparse(location)
5889 conn = httplib.HTTPConnection(url.netloc)
5890
5891 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
5892 def handle(self):
5893 data = self.rfile.readline().strip()
5894 logger.debug(data)
5895 self.wfile.write(gen_wps_event())
5896
5897 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5898 server.timeout = 1
5899
5900 headers = { "callback": '<http://127.0.0.1:12345/event>',
5901 "NT": "upnp:event",
5902 "timeout": "Second-1234" }
5903 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5904 resp = conn.getresponse()
5905 if resp.status != 200:
5906 raise Exception("Unexpected HTTP response: %d" % resp.status)
5907 sid = resp.getheader("sid")
5908 logger.debug("Subscription SID " + sid)
5909 server.handle_request()
5910
5911 tests = [ (500, "10"),
5912 (200, "104a000110" + "1041000101" + "101200020000" +
5913 "105300023148" +
5914 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5915 "10480010362db47ba53a519188fb5458b986b2e4"),
5916 (200, "104a000110" + "1041000100" + "101200020000" +
5917 "105300020000"),
5918 (200, "104a000110" + "1041000100"),
5919 (200, "104a000110") ]
5920 for status,test in tests:
5921 tlvs = binascii.unhexlify(test)
5922 newmsg = base64.b64encode(tlvs)
5923 msg = '<?xml version="1.0"?>\n'
5924 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5925 msg += '<s:Body>'
5926 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5927 msg += '<NewMessage>'
5928 msg += newmsg
5929 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
5930 headers = { "Content-type": 'text/xml; charset="utf-8"' }
5931 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
5932 conn.request("POST", ctrlurl.path, msg, headers)
5933 resp = conn.getresponse()
5934 if resp.status != status:
5935 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
96038a5f
JM
5936
5937def test_ap_wps_adv_oom(dev, apdev):
5938 """WPS AP and advertisement OOM"""
5939 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 5940 hapd = add_ssdp_ap(apdev[0], ap_uuid)
96038a5f
JM
5941
5942 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
5943 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5944 no_recv=True)
5945 time.sleep(0.2)
5946
5947 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
5948 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5949 no_recv=True)
5950 time.sleep(0.2)
5951
5952 with alloc_fail(hapd, 1,
5953 "next_advertisement;advertisement_state_machine_stop"):
5954 hapd.disable()
5955
5956 with alloc_fail(hapd, 1, "ssdp_listener_start"):
5957 if "FAIL" not in hapd.request("ENABLE"):
5958 raise Exception("ENABLE succeeded during OOM")
926404a6
JM
5959
5960def test_wps_config_methods(dev):
5961 """WPS config method update"""
5962 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
5963 wpas.interface_add("wlan5")
5964 if "OK" not in wpas.request("SET config_methods display label"):
5965 raise Exception("Failed to set config_methods")
5966 if wpas.request("GET config_methods").strip() != "display label":
5967 raise Exception("config_methods were not updated")
5968 if "OK" not in wpas.request("SET config_methods "):
5969 raise Exception("Failed to clear config_methods")
5970 if wpas.request("GET config_methods").strip() != "":
5971 raise Exception("config_methods were not cleared")
7511ead0
JM
5972
5973WPS_VENDOR_ID_WFA = 14122
5974WPS_VENDOR_TYPE = 1
5975
5976# EAP-WSC Op-Code values
5977WSC_Start = 0x01
5978WSC_ACK = 0x02
5979WSC_NACK = 0x03
5980WSC_MSG = 0x04
5981WSC_Done = 0x05
5982WSC_FRAG_ACK = 0x06
5983
5984ATTR_AP_CHANNEL = 0x1001
5985ATTR_ASSOC_STATE = 0x1002
5986ATTR_AUTH_TYPE = 0x1003
5987ATTR_AUTH_TYPE_FLAGS = 0x1004
5988ATTR_AUTHENTICATOR = 0x1005
5989ATTR_CONFIG_METHODS = 0x1008
5990ATTR_CONFIG_ERROR = 0x1009
5991ATTR_CONFIRM_URL4 = 0x100a
5992ATTR_CONFIRM_URL6 = 0x100b
5993ATTR_CONN_TYPE = 0x100c
5994ATTR_CONN_TYPE_FLAGS = 0x100d
5995ATTR_CRED = 0x100e
5996ATTR_ENCR_TYPE = 0x100f
5997ATTR_ENCR_TYPE_FLAGS = 0x1010
5998ATTR_DEV_NAME = 0x1011
5999ATTR_DEV_PASSWORD_ID = 0x1012
6000ATTR_E_HASH1 = 0x1014
6001ATTR_E_HASH2 = 0x1015
6002ATTR_E_SNONCE1 = 0x1016
6003ATTR_E_SNONCE2 = 0x1017
6004ATTR_ENCR_SETTINGS = 0x1018
6005ATTR_ENROLLEE_NONCE = 0x101a
6006ATTR_FEATURE_ID = 0x101b
6007ATTR_IDENTITY = 0x101c
6008ATTR_IDENTITY_PROOF = 0x101d
6009ATTR_KEY_WRAP_AUTH = 0x101e
6010ATTR_KEY_ID = 0x101f
6011ATTR_MAC_ADDR = 0x1020
6012ATTR_MANUFACTURER = 0x1021
6013ATTR_MSG_TYPE = 0x1022
6014ATTR_MODEL_NAME = 0x1023
6015ATTR_MODEL_NUMBER = 0x1024
6016ATTR_NETWORK_INDEX = 0x1026
6017ATTR_NETWORK_KEY = 0x1027
6018ATTR_NETWORK_KEY_INDEX = 0x1028
6019ATTR_NEW_DEVICE_NAME = 0x1029
6020ATTR_NEW_PASSWORD = 0x102a
6021ATTR_OOB_DEVICE_PASSWORD = 0x102c
6022ATTR_OS_VERSION = 0x102d
6023ATTR_POWER_LEVEL = 0x102f
6024ATTR_PSK_CURRENT = 0x1030
6025ATTR_PSK_MAX = 0x1031
6026ATTR_PUBLIC_KEY = 0x1032
6027ATTR_RADIO_ENABLE = 0x1033
6028ATTR_REBOOT = 0x1034
6029ATTR_REGISTRAR_CURRENT = 0x1035
6030ATTR_REGISTRAR_ESTABLISHED = 0x1036
6031ATTR_REGISTRAR_LIST = 0x1037
6032ATTR_REGISTRAR_MAX = 0x1038
6033ATTR_REGISTRAR_NONCE = 0x1039
6034ATTR_REQUEST_TYPE = 0x103a
6035ATTR_RESPONSE_TYPE = 0x103b
6036ATTR_RF_BANDS = 0x103c
6037ATTR_R_HASH1 = 0x103d
6038ATTR_R_HASH2 = 0x103e
6039ATTR_R_SNONCE1 = 0x103f
6040ATTR_R_SNONCE2 = 0x1040
6041ATTR_SELECTED_REGISTRAR = 0x1041
6042ATTR_SERIAL_NUMBER = 0x1042
6043ATTR_WPS_STATE = 0x1044
6044ATTR_SSID = 0x1045
6045ATTR_TOTAL_NETWORKS = 0x1046
6046ATTR_UUID_E = 0x1047
6047ATTR_UUID_R = 0x1048
6048ATTR_VENDOR_EXT = 0x1049
6049ATTR_VERSION = 0x104a
6050ATTR_X509_CERT_REQ = 0x104b
6051ATTR_X509_CERT = 0x104c
6052ATTR_EAP_IDENTITY = 0x104d
6053ATTR_MSG_COUNTER = 0x104e
6054ATTR_PUBKEY_HASH = 0x104f
6055ATTR_REKEY_KEY = 0x1050
6056ATTR_KEY_LIFETIME = 0x1051
6057ATTR_PERMITTED_CFG_METHODS = 0x1052
6058ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
6059ATTR_PRIMARY_DEV_TYPE = 0x1054
6060ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
6061ATTR_PORTABLE_DEV = 0x1056
6062ATTR_AP_SETUP_LOCKED = 0x1057
6063ATTR_APPLICATION_EXT = 0x1058
6064ATTR_EAP_TYPE = 0x1059
6065ATTR_IV = 0x1060
6066ATTR_KEY_PROVIDED_AUTO = 0x1061
6067ATTR_802_1X_ENABLED = 0x1062
6068ATTR_APPSESSIONKEY = 0x1063
6069ATTR_WEPTRANSMITKEY = 0x1064
6070ATTR_REQUESTED_DEV_TYPE = 0x106a
6071
6072# Message Type
6073WPS_Beacon = 0x01
6074WPS_ProbeRequest = 0x02
6075WPS_ProbeResponse = 0x03
6076WPS_M1 = 0x04
6077WPS_M2 = 0x05
6078WPS_M2D = 0x06
6079WPS_M3 = 0x07
6080WPS_M4 = 0x08
6081WPS_M5 = 0x09
6082WPS_M6 = 0x0a
6083WPS_M7 = 0x0b
6084WPS_M8 = 0x0c
6085WPS_WSC_ACK = 0x0d
6086WPS_WSC_NACK = 0x0e
6087WPS_WSC_DONE = 0x0f
6088
6089def get_wsc_msg(dev):
6090 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6091 if ev is None:
6092 raise Exception("Timeout on EAPOL-TX")
6093 data = binascii.unhexlify(ev.split(' ')[2])
6094 msg = {}
6095
6096 # Parse EAPOL header
6097 if len(data) < 4:
6098 raise Exception("No room for EAPOL header")
6099 version,type,length = struct.unpack('>BBH', data[0:4])
6100 msg['eapol_version'] = version
6101 msg['eapol_type'] = type
6102 msg['eapol_length'] = length
6103 data = data[4:]
6104 if length != len(data):
6105 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6106 if type != 0:
6107 raise Exception("Unexpected EAPOL header type: %d" % type)
6108
6109 # Parse EAP header
6110 if len(data) < 4:
6111 raise Exception("No room for EAP header")
6112 code,identifier,length = struct.unpack('>BBH', data[0:4])
6113 msg['eap_code'] = code
6114 msg['eap_identifier'] = identifier
6115 msg['eap_length'] = length
6116 data = data[4:]
6117 if msg['eapol_length'] != msg['eap_length']:
6118 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6119
6120 # Parse EAP expanded header
6121 if len(data) < 1:
6122 raise Exception("No EAP type included")
6123 msg['eap_type'], = struct.unpack('B', data[0])
6124 data = data[1:]
6125
6126 if msg['eap_type'] == 254:
6127 if len(data) < 3 + 4:
6128 raise Exception("Truncated EAP expanded header")
6129 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', '\0' + data[0:7])
6130 data = data[7:]
6131 else:
6132 raise Exception("Unexpected EAP type")
6133
6134 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6135 raise Exception("Unexpected Vendor-Id")
6136 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6137 raise Exception("Unexpected Vendor-Type")
6138
6139 # Parse EAP-WSC header
6140 if len(data) < 2:
6141 raise Exception("Truncated EAP-WSC header")
6142 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6143 data = data[2:]
6144
6145 # Parse WSC attributes
6146 msg['raw_attrs'] = data
6147 attrs = {}
6148 while len(data) > 0:
6149 if len(data) < 4:
6150 raise Exception("Truncated attribute header")
6151 attr,length = struct.unpack('>HH', data[0:4])
6152 data = data[4:]
6153 if length > len(data):
6154 raise Exception("Truncated attribute 0x%04x" % attr)
6155 attrs[attr] = data[0:length]
6156 data = data[length:]
6157 msg['wsc_attrs'] = attrs
6158
6159 if ATTR_MSG_TYPE in attrs:
6160 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6161
6162 return msg
6163
6164def recv_wsc_msg(dev, opcode, msg_type):
6165 msg = get_wsc_msg(dev)
6166 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6167 raise Exception("Unexpected Op-Code/MsgType")
6168 return msg, msg['wsc_attrs'], msg['raw_attrs']
6169
6170def build_wsc_attr(attr, payload):
6171 return struct.pack('>HH', attr, len(payload)) + payload
6172
6173def build_attr_msg_type(msg_type):
6174 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6175
6176def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6177 length = 4 + 8 + 2 + len(payload)
6178 # EAPOL header
6179 msg = struct.pack('>BBH', 2, 0, length)
6180 # EAP header
6181 msg += struct.pack('>BBH', eap_code, eap_id, length)
6182 # EAP expanded header for EAP-WSC
6183 msg += struct.pack('B', 254)
6184 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6185 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6186 # EAP-WSC header
6187 msg += struct.pack('BB', opcode, 0)
6188 # WSC attributes
6189 msg += payload
6190 return msg
6191
6192def build_eap_success(eap_id):
6193 length = 4
6194 # EAPOL header
6195 msg = struct.pack('>BBH', 2, 0, length)
6196 # EAP header
6197 msg += struct.pack('>BBH', 3, eap_id, length)
6198 return msg
6199
6200def build_eap_failure(eap_id):
6201 length = 4
6202 # EAPOL header
6203 msg = struct.pack('>BBH', 2, 0, length)
6204 # EAP header
6205 msg += struct.pack('>BBH', 4, eap_id, length)
6206 return msg
6207
6208def send_wsc_msg(dev, src, msg):
6209 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg))
6210 if "OK" not in res:
6211 raise Exception("EAPOL_RX failed")
6212
6213group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6214group_5_generator = 2
6215
6216def wsc_kdf(key, label, bits):
6217 result = ''
6218 i = 1
6219 while len(result) * 8 < bits:
6220 data = struct.pack('>L', i) + label + struct.pack('>L', bits)
6221 m = hmac.new(key, data, hashlib.sha256)
6222 result += m.digest()
6223 i += 1
6224 return result[0:bits / 8]
6225
6226def wsc_keys(kdk):
6227 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6228 authkey = keys[0:32]
6229 keywrapkey = keys[32:48]
6230 emsk = keys[48:80]
6231 return authkey,keywrapkey,emsk
6232
6233def wsc_dev_pw_half_psk(authkey, dev_pw):
6234 m = hmac.new(authkey, dev_pw, hashlib.sha256)
6235 return m.digest()[0:16]
6236
6237def wsc_dev_pw_psk(authkey, dev_pw):
6238 dev_pw_1 = dev_pw[0:len(dev_pw) / 2]
6239 dev_pw_2 = dev_pw[len(dev_pw) / 2:]
6240 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6241 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6242 return psk1,psk2
6243
6244def build_attr_authenticator(authkey, prev_msg, curr_msg):
6245 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6246 auth = m.digest()[0:8]
6247 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6248
6249def build_attr_encr_settings(authkey, keywrapkey, data):
6250 m = hmac.new(authkey, data, hashlib.sha256)
6251 kwa = m.digest()[0:8]
6252 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6253 iv = 16*'\x99'
6254 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6255 pad_len = 16 - len(data) % 16
6256 ps = pad_len * struct.pack('B', pad_len)
6257 data += ps
6258 wrapped = aes.encrypt(data)
6259 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6260
6261def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6262 if len(data) < 32 or len(data) % 16 != 0:
6263 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6264 iv = data[0:16]
6265 encr = data[16:]
6266 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6267 decrypted = aes.decrypt(encr)
6268 pad_len, = struct.unpack('B', decrypted[-1])
6269 if pad_len > len(decrypted):
6270 raise Exception("Invalid padding in Encrypted Settings")
6271 for i in range(-pad_len, -1):
6272 if decrypted[i] != decrypted[-1]:
6273 raise Exception("Invalid PS value in Encrypted Settings")
db98b587 6274
7511ead0
JM
6275 decrypted = decrypted[0:len(decrypted) - pad_len]
6276 if len(decrypted) < 12:
6277 raise Exception("Truncated Encrypted Settings plaintext")
6278 kwa = decrypted[-12:]
6279 attr,length = struct.unpack(">HH", kwa[0:4])
6280 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6281 raise Exception("Invalid KWA header")
6282 kwa = kwa[4:]
6283 decrypted = decrypted[0:len(decrypted) - 12]
6284
6285 m = hmac.new(authkey, decrypted, hashlib.sha256)
6286 calc_kwa = m.digest()[0:8]
6287 if kwa != calc_kwa:
6288 raise Exception("KWA mismatch")
6289
6290 return decrypted
6291
6292def zeropad_str(val, pad_len):
6293 while len(val) < pad_len * 2:
6294 val = '0' + val
6295 return val
6296
6297def wsc_dh_init():
6298 # For now, use a hardcoded private key. In theory, this is supposed to be
6299 # randomly selected.
6300 own_private = 0x123456789
6301 own_public = pow(group_5_generator, own_private, group_5_prime)
6302 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6303 return own_private, pk
6304
6305def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6306 peer_public = long(binascii.hexlify(peer_pk), 16)
6307 if peer_public < 2 or peer_public >= group_5_prime:
6308 raise Exception("Invalid peer public key")
6309 if pow(peer_public, (group_5_prime - 1) / 2, group_5_prime) != 1:
6310 raise Exception("Unexpected Legendre symbol for peer public key")
6311
6312 shared_secret = pow(peer_public, own_private, group_5_prime)
6313 ss = zeropad_str(format(shared_secret, "02x"), 192)
6314 logger.debug("DH shared secret: " + ss)
6315
6316 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6317 logger.debug("DHKey: " + binascii.hexlify(dhkey))
6318
6319 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6320 kdk = m.digest()
6321 logger.debug("KDK: " + binascii.hexlify(kdk))
6322 authkey,keywrapkey,emsk = wsc_keys(kdk)
6323 logger.debug("AuthKey: " + binascii.hexlify(authkey))
6324 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey))
6325 logger.debug("EMSK: " + binascii.hexlify(emsk))
6326 return authkey,keywrapkey
6327
6328def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6329 psk1,psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6330 logger.debug("PSK1: " + binascii.hexlify(psk1))
6331 logger.debug("PSK2: " + binascii.hexlify(psk2))
6332
6333 # Note: Secret values are supposed to be random, but hardcoded values are
6334 # fine for testing.
6335 s1 = 16*'\x77'
6336 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6337 hash1 = m.digest()
6338 logger.debug("Hash1: " + binascii.hexlify(hash1))
6339
6340 s2 = 16*'\x88'
6341 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6342 hash2 = m.digest()
6343 logger.debug("Hash2: " + binascii.hexlify(hash2))
6344 return s1,s2,hash1,hash2
6345
6346def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6347 manufacturer='', model_name='', config_methods='\x00\x00'):
6348 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6349 attrs += build_attr_msg_type(WPS_M1)
6350 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6351 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6352 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6353 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6354 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6355 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6356 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6357 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6358 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6359 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6360 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6361 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6362 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6363 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6364 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6365 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6366 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6367 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6368 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6369 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6370 m1 = build_eap_wsc(2, eap_id, attrs)
6371 return m1, attrs
6372
6373def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6374 dev_pw_id='\x00\x00', eap_code=1):
6375 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6376 attrs += build_attr_msg_type(WPS_M2)
6377 if e_nonce:
6378 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6379 if r_nonce:
6380 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6381 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6382 if r_pk:
6383 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6384 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6385 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6386 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6387 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6388 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6389 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6390 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6391 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6392 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6393 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6394 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6395 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6396 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6397 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6398 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6399 attrs += build_attr_authenticator(authkey, m1, attrs)
6400 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6401 return m2, attrs
6402
6403def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6404 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6405 attrs += build_attr_msg_type(WPS_M2D)
6406 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6407 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6408 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6409 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6410 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6411 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6412 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6413 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6414 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6415 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6416 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6417 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6418 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6419 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6420 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6421 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6422 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6423 if dev_pw_id:
6424 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6425 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6426 return m2d, attrs
6427
6428def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6429 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6430 if msg_type is not None:
6431 attrs += build_attr_msg_type(msg_type)
6432 if e_nonce:
6433 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6434 if r_nonce:
6435 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6436 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6437 return msg, attrs
6438
6439def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6440 msg_type=WPS_WSC_NACK, eap_code=1):
6441 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6442 if msg_type is not None:
6443 attrs += build_attr_msg_type(msg_type)
6444 if e_nonce:
6445 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6446 if r_nonce:
6447 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6448 if config_error:
6449 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6450 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6451 return msg, attrs
6452
6453def test_wps_ext(dev, apdev):
6454 """WPS against external implementation"""
6455 pin = "12345670"
6456 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6457 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6458 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6459
6460 logger.debug("Receive WSC/Start from AP")
6461 msg = get_wsc_msg(hapd)
6462 if msg['wsc_opcode'] != WSC_Start:
6463 raise Exception("Unexpected Op-Code for WSC/Start")
6464 wsc_start_id = msg['eap_identifier']
6465
6466 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6467 uuid_e = 16*'\x11'
6468 e_nonce = 16*'\x22'
6469 own_private, e_pk = wsc_dh_init()
6470
6471 logger.debug("Send M1 to AP")
6472 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6473 e_nonce, e_pk)
6474 send_wsc_msg(hapd, addr, m1)
6475
6476 logger.debug("Receive M2 from AP")
6477 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6478
6479 authkey,keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6480 mac_addr, e_nonce,
6481 m2_attrs[ATTR_REGISTRAR_NONCE])
6482 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6483 m2_attrs[ATTR_PUBLIC_KEY])
6484
6485 logger.debug("Send M3 to AP")
6486 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6487 attrs += build_attr_msg_type(WPS_M3)
6488 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6489 m2_attrs[ATTR_REGISTRAR_NONCE])
6490 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6491 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6492 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6493 raw_m3_attrs = attrs
6494 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6495 send_wsc_msg(hapd, addr, m3)
6496
6497 logger.debug("Receive M4 from AP")
6498 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6499
6500 logger.debug("Send M5 to AP")
6501 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6502 attrs += build_attr_msg_type(WPS_M5)
6503 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6504 m2_attrs[ATTR_REGISTRAR_NONCE])
6505 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6506 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6507 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6508 raw_m5_attrs = attrs
6509 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6510 send_wsc_msg(hapd, addr, m5)
6511
6512 logger.debug("Receive M6 from AP")
6513 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6514
6515 logger.debug("Send M7 to AP")
6516 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6517 attrs += build_attr_msg_type(WPS_M7)
6518 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6519 m2_attrs[ATTR_REGISTRAR_NONCE])
6520 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6521 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6522 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6523 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6524 raw_m7_attrs = attrs
6525 send_wsc_msg(hapd, addr, m7)
6526
6527 logger.debug("Receive M8 from AP")
6528 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6529 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6530 m8_attrs[ATTR_ENCR_SETTINGS])
6531 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred))
6532
6533 logger.debug("Prepare WSC_Done")
6534 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6535 attrs += build_attr_msg_type(WPS_WSC_DONE)
6536 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6537 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6538 m2_attrs[ATTR_REGISTRAR_NONCE])
6539 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6540 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6541 # AP disconnects.
6542
6543 uuid_r = 16*'\x33'
6544 r_nonce = 16*'\x44'
6545
6546 eap_id = wsc_start_id
6547 logger.debug("Send WSC/Start to STA")
6548 wsc_start = build_eap_wsc(1, eap_id, "", opcode=WSC_Start)
6549 send_wsc_msg(dev[0], bssid, wsc_start)
6550 eap_id = (eap_id + 1) % 256
6551
6552 logger.debug("Receive M1 from STA")
6553 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6554
6555 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6556 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6557 r_nonce)
6558 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6559 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6560
6561 logger.debug("Send M2 to STA")
6562 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6563 m1_attrs[ATTR_ENROLLEE_NONCE],
6564 r_nonce, uuid_r, e_pk)
6565 send_wsc_msg(dev[0], bssid, m2)
6566 eap_id = (eap_id + 1) % 256
6567
6568 logger.debug("Receive M3 from STA")
6569 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6570
6571 logger.debug("Send M4 to STA")
6572 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6573 attrs += build_attr_msg_type(WPS_M4)
6574 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6575 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6576 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6577 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6578 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6579 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6580 raw_m4_attrs = attrs
6581 m4 = build_eap_wsc(1, eap_id, attrs)
6582 send_wsc_msg(dev[0], bssid, m4)
6583 eap_id = (eap_id + 1) % 256
6584
6585 logger.debug("Receive M5 from STA")
6586 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6587
6588 logger.debug("Send M6 to STA")
6589 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6590 attrs += build_attr_msg_type(WPS_M6)
6591 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6592 m1_attrs[ATTR_ENROLLEE_NONCE])
6593 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6594 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6595 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6596 raw_m6_attrs = attrs
6597 m6 = build_eap_wsc(1, eap_id, attrs)
6598 send_wsc_msg(dev[0], bssid, m6)
6599 eap_id = (eap_id + 1) % 256
6600
6601 logger.debug("Receive M7 from STA")
6602 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6603
6604 logger.debug("Send M8 to STA")
6605 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6606 attrs += build_attr_msg_type(WPS_M8)
6607 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6608 m1_attrs[ATTR_ENROLLEE_NONCE])
6609 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6610 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6611 raw_m8_attrs = attrs
6612 m8 = build_eap_wsc(1, eap_id, attrs)
6613 send_wsc_msg(dev[0], bssid, m8)
6614 eap_id = (eap_id + 1) % 256
6615
6616 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6617 if ev is None:
6618 raise Exception("wpa_supplicant did not report credential")
6619
6620 logger.debug("Receive WSC_Done from STA")
6621 msg = get_wsc_msg(dev[0])
6622 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6623 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6624
6625 logger.debug("Send WSC_Done to AP")
6626 hapd.request("SET ext_eapol_frame_io 0")
6627 dev[0].request("SET ext_eapol_frame_io 0")
6628 send_wsc_msg(hapd, addr, wsc_done)
6629
6630 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6631 if ev is None:
6632 raise Exception("hostapd did not report WPS success")
6633
6634 dev[0].wait_connected()
6635
6636def wps_start_kwa(dev, apdev):
6637 pin = "12345670"
6638 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6639 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6640 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6641 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6642
6643 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6644 uuid_r = 16*'\x33'
6645 r_nonce = 16*'\x44'
6646 own_private, e_pk = wsc_dh_init()
6647
6648 logger.debug("Receive M1 from STA")
6649 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6650 eap_id = (msg['eap_identifier'] + 1) % 256
6651
6652 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6653 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6654 r_nonce)
6655 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6656 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6657
6658 logger.debug("Send M2 to STA")
6659 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6660 m1_attrs[ATTR_ENROLLEE_NONCE],
6661 r_nonce, uuid_r, e_pk)
6662 send_wsc_msg(dev[0], bssid, m2)
6663 eap_id = (eap_id + 1) % 256
6664
6665 logger.debug("Receive M3 from STA")
6666 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6667
6668 logger.debug("Send M4 to STA")
6669 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6670 attrs += build_attr_msg_type(WPS_M4)
6671 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6672 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6673 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6674
6675 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6676
6677def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6678 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6679 m4 = build_eap_wsc(1, eap_id, attrs)
6680 send_wsc_msg(dev[0], bssid, m4)
6681 eap_id = (eap_id + 1) % 256
6682
6683 logger.debug("Receive M5 from STA")
6684 msg = get_wsc_msg(dev[0])
6685 if msg['wsc_opcode'] != WSC_NACK:
6686 raise Exception("Unexpected message - expected WSC_Nack")
6687
6688 dev[0].request("WPS_CANCEL")
6689 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6690 dev[0].wait_disconnected()
6691
6692def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6693 """WPS and KWA error: No KWA attribute"""
6694 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6695 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6696 # Encrypted Settings without KWA
6697 iv = 16*'\x99'
6698 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6699 pad_len = 16 - len(data) % 16
6700 ps = pad_len * struct.pack('B', pad_len)
6701 data += ps
6702 wrapped = aes.encrypt(data)
6703 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6704 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6705
6706def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6707 """WPS and KWA error: Data after KWA"""
6708 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6709 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6710 # Encrypted Settings and data after KWA
6711 m = hmac.new(authkey, data, hashlib.sha256)
6712 kwa = m.digest()[0:8]
6713 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6714 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6715 iv = 16*'\x99'
6716 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6717 pad_len = 16 - len(data) % 16
6718 ps = pad_len * struct.pack('B', pad_len)
6719 data += ps
6720 wrapped = aes.encrypt(data)
6721 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6722 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6723
6724def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6725 """WPS and KWA error: KWA mismatch"""
6726 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6727 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6728 # Encrypted Settings and KWA with incorrect value
6729 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6730 iv = 16*'\x99'
6731 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6732 pad_len = 16 - len(data) % 16
6733 ps = pad_len * struct.pack('B', pad_len)
6734 data += ps
6735 wrapped = aes.encrypt(data)
6736 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6737 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6738
6739def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6740 pin = "12345670"
6741 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6742 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6743 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6744 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6745
6746 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6747 uuid_r = 16*'\x33'
6748 r_nonce = 16*'\x44'
6749 own_private, e_pk = wsc_dh_init()
6750
6751 logger.debug("Receive M1 from STA")
6752 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6753 eap_id = (msg['eap_identifier'] + 1) % 256
6754
6755 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6756 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6757 r_nonce)
6758 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6759 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6760
6761 logger.debug("Send M2 to STA")
6762 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6763 m1_attrs[ATTR_ENROLLEE_NONCE],
6764 r_nonce, uuid_r, e_pk)
6765 send_wsc_msg(dev[0], bssid, m2)
6766 eap_id = (eap_id + 1) % 256
6767
6768 logger.debug("Receive M3 from STA")
6769 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6770
6771 logger.debug("Send M4 to STA")
6772 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6773 attrs += build_attr_msg_type(WPS_M4)
6774 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6775 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6776 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6777 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6778 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6779 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6780 raw_m4_attrs = attrs
6781 m4 = build_eap_wsc(1, eap_id, attrs)
6782 send_wsc_msg(dev[0], bssid, m4)
6783 eap_id = (eap_id + 1) % 256
6784
6785 logger.debug("Receive M5 from STA")
6786 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6787
6788 logger.debug("Send M6 to STA")
6789 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6790 attrs += build_attr_msg_type(WPS_M6)
6791 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6792 m1_attrs[ATTR_ENROLLEE_NONCE])
6793 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6794 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6795 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6796 raw_m6_attrs = attrs
6797 m6 = build_eap_wsc(1, eap_id, attrs)
6798 send_wsc_msg(dev[0], bssid, m6)
6799 eap_id = (eap_id + 1) % 256
6800
6801 logger.debug("Receive M7 from STA")
6802 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6803
6804 logger.debug("Send M8 to STA")
6805 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6806 attrs += build_attr_msg_type(WPS_M8)
6807 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6808 m1_attrs[ATTR_ENROLLEE_NONCE])
6809 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6810 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6811 raw_m8_attrs = attrs
6812 m8 = build_eap_wsc(1, eap_id, attrs)
6813 send_wsc_msg(dev[0], bssid, m8)
6814 eap_id = (eap_id + 1) % 256
6815
6816 if no_connect:
6817 logger.debug("Receive WSC_Done from STA")
6818 msg = get_wsc_msg(dev[0])
6819 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6820 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6821
6822 hapd.request("SET ext_eapol_frame_io 0")
6823 dev[0].request("SET ext_eapol_frame_io 0")
6824
6825 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6826
6827 dev[0].wait_disconnected()
6828 dev[0].request("REMOVE_NETWORK all")
6829 elif connect:
6830 logger.debug("Receive WSC_Done from STA")
6831 msg = get_wsc_msg(dev[0])
6832 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6833 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6834
6835 hapd.request("SET ext_eapol_frame_io 0")
6836 dev[0].request("SET ext_eapol_frame_io 0")
6837
6838 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6839
6840 dev[0].wait_connected()
6841 else:
6842 # Verify STA NACK's the credential
6843 msg = get_wsc_msg(dev[0])
6844 if msg['wsc_opcode'] != WSC_NACK:
6845 raise Exception("Unexpected message - expected WSC_Nack")
6846 dev[0].request("WPS_CANCEL")
6847 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6848 dev[0].wait_disconnected()
6849
6850def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6851 encr_type='\x00\x08', nw_key="12345678",
6852 mac_addr='\x00\x00\x00\x00\x00\x00'):
6853 attrs = ''
6854 if nw_idx is not None:
6855 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6856 if ssid is not None:
6857 attrs += build_wsc_attr(ATTR_SSID, ssid)
6858 if auth_type is not None:
6859 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6860 if encr_type is not None:
6861 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6862 if nw_key is not None:
6863 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6864 if mac_addr is not None:
6865 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6866 return build_wsc_attr(ATTR_CRED, attrs)
6867
6868def test_wps_ext_cred_proto_success(dev, apdev):
6869 """WPS and Credential: success"""
6870 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6871 m8_cred = build_cred(mac_addr=mac_addr)
6872 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6873
6874def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6875 """WPS and Credential: MAC Address mismatch"""
6876 m8_cred = build_cred()
6877 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6878
6879def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6880 """WPS and Credential: zeropadded attributes"""
6881 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6882 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6883 nw_key="12345678\x00")
6884 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6885
6886def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6887 """WPS and Credential: SSID missing"""
6888 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6889 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6890 wps_run_cred_proto(dev, apdev, m8_cred)
6891
6892def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6893 """WPS and Credential: Zero-length SSID"""
6894 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6895 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6896 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6897
6898def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6899 """WPS and Credential: Auth Type missing"""
6900 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6901 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6902 wps_run_cred_proto(dev, apdev, m8_cred)
6903
6904def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6905 """WPS and Credential: Encr Type missing"""
6906 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6907 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6908 wps_run_cred_proto(dev, apdev, m8_cred)
6909
6910def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6911 """WPS and Credential: Network Key missing"""
6912 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6913 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6914 wps_run_cred_proto(dev, apdev, m8_cred)
6915
6916def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6917 """WPS and Credential: Network Key missing (open)"""
6918 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6919 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6920 encr_type='\x00\x01', nw_key=None, ssid="foo")
6921 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6922
6923def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6924 """WPS and Credential: MAC Address missing"""
6925 m8_cred = build_cred(mac_addr=None)
6926 wps_run_cred_proto(dev, apdev, m8_cred)
6927
6928def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
6929 """WPS and Credential: Invalid Encr Type"""
6930 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6931 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
6932 wps_run_cred_proto(dev, apdev, m8_cred)
6933
6934def test_wps_ext_cred_proto_missing_cred(dev, apdev):
6935 """WPS and Credential: Missing Credential"""
6936 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6937 m8_cred = ''
6938 wps_run_cred_proto(dev, apdev, m8_cred)
6939
6940def test_wps_ext_proto_m2_no_public_key(dev, apdev):
6941 """WPS and no Public Key in M2"""
6942 pin = "12345670"
6943 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6944 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6945 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6946 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6947
6948 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6949 uuid_r = 16*'\x33'
6950 r_nonce = 16*'\x44'
6951 own_private, e_pk = wsc_dh_init()
6952
6953 logger.debug("Receive M1 from STA")
6954 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6955 eap_id = (msg['eap_identifier'] + 1) % 256
6956
6957 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6958 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6959 r_nonce)
6960 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6961 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6962
6963 logger.debug("Send M2 to STA")
6964 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6965 m1_attrs[ATTR_ENROLLEE_NONCE],
6966 r_nonce, uuid_r, None)
6967 send_wsc_msg(dev[0], bssid, m2)
6968 eap_id = (eap_id + 1) % 256
6969
6970 # Verify STA NACK's the credential
6971 msg = get_wsc_msg(dev[0])
6972 if msg['wsc_opcode'] != WSC_NACK:
6973 raise Exception("Unexpected message - expected WSC_Nack")
6974 dev[0].request("WPS_CANCEL")
6975 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6976 dev[0].wait_disconnected()
6977
6978def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
6979 """WPS and invalid Public Key in M2"""
6980 pin = "12345670"
6981 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6982 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6983 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6984 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6985
6986 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6987 uuid_r = 16*'\x33'
6988 r_nonce = 16*'\x44'
6989 own_private, e_pk = wsc_dh_init()
6990
6991 logger.debug("Receive M1 from STA")
6992 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6993 eap_id = (msg['eap_identifier'] + 1) % 256
6994
6995 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6996 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6997 r_nonce)
6998 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6999 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7000
7001 logger.debug("Send M2 to STA")
7002 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7003 m1_attrs[ATTR_ENROLLEE_NONCE],
7004 r_nonce, uuid_r, 192*'\xff')
7005 send_wsc_msg(dev[0], bssid, m2)
7006 eap_id = (eap_id + 1) % 256
7007
7008 # Verify STA NACK's the credential
7009 msg = get_wsc_msg(dev[0])
7010 if msg['wsc_opcode'] != WSC_NACK:
7011 raise Exception("Unexpected message - expected WSC_Nack")
7012 dev[0].request("WPS_CANCEL")
7013 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7014 dev[0].wait_disconnected()
7015
7016def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7017 """WPS and Public Key OOM in M2"""
7018 pin = "12345670"
7019 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7020 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7021 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7022 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7023
7024 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7025 uuid_r = 16*'\x33'
7026 r_nonce = 16*'\x44'
7027 own_private, e_pk = wsc_dh_init()
7028
7029 logger.debug("Receive M1 from STA")
7030 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7031 eap_id = (msg['eap_identifier'] + 1) % 256
7032
7033 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7034 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7035 r_nonce)
7036 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7037 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7038
7039 logger.debug("Send M2 to STA")
7040 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7041 m1_attrs[ATTR_ENROLLEE_NONCE],
7042 r_nonce, uuid_r, e_pk)
7043 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7044 send_wsc_msg(dev[0], bssid, m2)
7045 eap_id = (eap_id + 1) % 256
7046
7047 # Verify STA NACK's the credential
7048 msg = get_wsc_msg(dev[0])
7049 if msg['wsc_opcode'] != WSC_NACK:
7050 raise Exception("Unexpected message - expected WSC_Nack")
7051 dev[0].request("WPS_CANCEL")
7052 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7053 dev[0].wait_disconnected()
7054
7055def test_wps_ext_proto_nack_m3(dev, apdev):
7056 """WPS and NACK M3"""
7057 pin = "12345670"
7058 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7059 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7060 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7061 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7062
7063 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7064 uuid_r = 16*'\x33'
7065 r_nonce = 16*'\x44'
7066 own_private, e_pk = wsc_dh_init()
7067
7068 logger.debug("Receive M1 from STA")
7069 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7070 eap_id = (msg['eap_identifier'] + 1) % 256
7071
7072 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7073 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7074 r_nonce)
7075 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7076 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7077
7078 logger.debug("Send M2 to STA")
7079 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7080 m1_attrs[ATTR_ENROLLEE_NONCE],
7081 r_nonce, uuid_r, e_pk)
7082 send_wsc_msg(dev[0], bssid, m2)
7083 eap_id = (eap_id + 1) % 256
7084
7085 logger.debug("Receive M3 from STA")
7086 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7087
7088 logger.debug("Send NACK to STA")
7089 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7090 r_nonce, config_error='\x01\x23')
7091 send_wsc_msg(dev[0], bssid, msg)
7092 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7093 if ev is None:
7094 raise Exception("Failure not reported")
7095 if "msg=7 config_error=291" not in ev:
7096 raise Exception("Unexpected failure reason: " + ev)
7097
7098def test_wps_ext_proto_nack_m5(dev, apdev):
7099 """WPS and NACK M5"""
7100 pin = "12345670"
7101 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7102 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7103 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7104 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7105
7106 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7107 uuid_r = 16*'\x33'
7108 r_nonce = 16*'\x44'
7109 own_private, e_pk = wsc_dh_init()
7110
7111 logger.debug("Receive M1 from STA")
7112 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7113 eap_id = (msg['eap_identifier'] + 1) % 256
7114
7115 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7116 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7117 r_nonce)
7118 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7119 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7120
7121 logger.debug("Send M2 to STA")
7122 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7123 m1_attrs[ATTR_ENROLLEE_NONCE],
7124 r_nonce, uuid_r, e_pk)
7125 send_wsc_msg(dev[0], bssid, m2)
7126 eap_id = (eap_id + 1) % 256
7127
7128 logger.debug("Receive M3 from STA")
7129 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7130
7131 logger.debug("Send M4 to STA")
7132 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7133 attrs += build_attr_msg_type(WPS_M4)
7134 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7135 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7136 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7137 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7138 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7139 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7140 raw_m4_attrs = attrs
7141 m4 = build_eap_wsc(1, eap_id, attrs)
7142 send_wsc_msg(dev[0], bssid, m4)
7143 eap_id = (eap_id + 1) % 256
7144
7145 logger.debug("Receive M5 from STA")
7146 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7147
7148 logger.debug("Send NACK to STA")
7149 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7150 r_nonce, config_error='\x01\x24')
7151 send_wsc_msg(dev[0], bssid, msg)
7152 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7153 if ev is None:
7154 raise Exception("Failure not reported")
7155 if "msg=9 config_error=292" not in ev:
7156 raise Exception("Unexpected failure reason: " + ev)
7157
7158def wps_nack_m3(dev, apdev):
7159 pin = "00000000"
7160 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7161 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7162 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7163 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7164
7165 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7166 uuid_r = 16*'\x33'
7167 r_nonce = 16*'\x44'
7168 own_private, e_pk = wsc_dh_init()
7169
7170 logger.debug("Receive M1 from STA")
7171 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7172 eap_id = (msg['eap_identifier'] + 1) % 256
7173
7174 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7175 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7176 r_nonce)
7177 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7178 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7179
7180 logger.debug("Send M2 to STA")
7181 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7182 m1_attrs[ATTR_ENROLLEE_NONCE],
7183 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7184 send_wsc_msg(dev[0], bssid, m2)
7185 eap_id = (eap_id + 1) % 256
7186
7187 logger.debug("Receive M3 from STA")
7188 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7189 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7190
7191def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7192 """WPS and NACK M3 missing Config Error"""
7193 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7194 logger.debug("Send NACK to STA")
7195 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7196 send_wsc_msg(dev[0], bssid, msg)
7197 dev[0].request("WPS_CANCEL")
7198 dev[0].wait_disconnected()
7199 dev[0].flush_scan_cache()
7200
7201def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7202 """WPS and NACK M3 missing E-Nonce"""
7203 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7204 logger.debug("Send NACK to STA")
7205 msg, attrs = build_nack(eap_id, None, r_nonce)
7206 send_wsc_msg(dev[0], bssid, msg)
7207 dev[0].request("WPS_CANCEL")
7208 dev[0].wait_disconnected()
7209 dev[0].flush_scan_cache()
7210
7211def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7212 """WPS and NACK M3 E-Nonce mismatch"""
7213 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7214 logger.debug("Send NACK to STA")
7215 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7216 send_wsc_msg(dev[0], bssid, msg)
7217 dev[0].request("WPS_CANCEL")
7218 dev[0].wait_disconnected()
7219 dev[0].flush_scan_cache()
7220
7221def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7222 """WPS and NACK M3 missing R-Nonce"""
7223 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7224 logger.debug("Send NACK to STA")
7225 msg, attrs = build_nack(eap_id, e_nonce, None)
7226 send_wsc_msg(dev[0], bssid, msg)
7227 dev[0].request("WPS_CANCEL")
7228 dev[0].wait_disconnected()
7229 dev[0].flush_scan_cache()
7230
7231def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7232 """WPS and NACK M3 R-Nonce mismatch"""
7233 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7234 logger.debug("Send NACK to STA")
7235 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7236 send_wsc_msg(dev[0], bssid, msg)
7237 dev[0].request("WPS_CANCEL")
7238 dev[0].wait_disconnected()
7239 dev[0].flush_scan_cache()
7240
7241def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7242 """WPS and NACK M3 no Message Type"""
7243 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7244 logger.debug("Send NACK to STA")
7245 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7246 send_wsc_msg(dev[0], bssid, msg)
7247 dev[0].request("WPS_CANCEL")
7248 dev[0].wait_disconnected()
7249 dev[0].flush_scan_cache()
7250
7251def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7252 """WPS and NACK M3 invalid Message Type"""
7253 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7254 logger.debug("Send NACK to STA")
7255 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7256 send_wsc_msg(dev[0], bssid, msg)
7257 dev[0].request("WPS_CANCEL")
7258 dev[0].wait_disconnected()
7259 dev[0].flush_scan_cache()
7260
7261def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7262 """WPS and NACK M3 invalid attribute"""
7263 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7264 logger.debug("Send NACK to STA")
7265 attrs = '\x10\x10\x00'
7266 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7267 send_wsc_msg(dev[0], bssid, msg)
7268 dev[0].request("WPS_CANCEL")
7269 dev[0].wait_disconnected()
7270 dev[0].flush_scan_cache()
7271
7272def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7273 """WPS and ACK M3 missing E-Nonce"""
7274 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7275 logger.debug("Send NACK to STA")
7276 msg, attrs = build_ack(eap_id, None, r_nonce)
7277 send_wsc_msg(dev[0], bssid, msg)
7278 dev[0].request("WPS_CANCEL")
7279 dev[0].wait_disconnected()
7280 dev[0].flush_scan_cache()
7281
7282def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7283 """WPS and ACK M3 E-Nonce mismatch"""
7284 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7285 logger.debug("Send NACK to STA")
7286 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7287 send_wsc_msg(dev[0], bssid, msg)
7288 dev[0].request("WPS_CANCEL")
7289 dev[0].wait_disconnected()
7290 dev[0].flush_scan_cache()
7291
7292def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7293 """WPS and ACK M3 missing R-Nonce"""
7294 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7295 logger.debug("Send NACK to STA")
7296 msg, attrs = build_ack(eap_id, e_nonce, None)
7297 send_wsc_msg(dev[0], bssid, msg)
7298 dev[0].request("WPS_CANCEL")
7299 dev[0].wait_disconnected()
7300 dev[0].flush_scan_cache()
7301
7302def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7303 """WPS and ACK M3 R-Nonce mismatch"""
7304 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7305 logger.debug("Send NACK to STA")
7306 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7307 send_wsc_msg(dev[0], bssid, msg)
7308 dev[0].request("WPS_CANCEL")
7309 dev[0].wait_disconnected()
7310 dev[0].flush_scan_cache()
7311
7312def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7313 """WPS and ACK M3 no Message Type"""
7314 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7315 logger.debug("Send NACK to STA")
7316 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7317 send_wsc_msg(dev[0], bssid, msg)
7318 dev[0].request("WPS_CANCEL")
7319 dev[0].wait_disconnected()
7320 dev[0].flush_scan_cache()
7321
7322def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7323 """WPS and ACK M3 invalid Message Type"""
7324 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7325 logger.debug("Send NACK to STA")
7326 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7327 send_wsc_msg(dev[0], bssid, msg)
7328 dev[0].request("WPS_CANCEL")
7329 dev[0].wait_disconnected()
7330 dev[0].flush_scan_cache()
7331
7332def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7333 """WPS and ACK M3 invalid attribute"""
7334 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7335 logger.debug("Send ACK to STA")
7336 attrs = '\x10\x10\x00'
7337 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7338 send_wsc_msg(dev[0], bssid, msg)
7339 dev[0].request("WPS_CANCEL")
7340 dev[0].wait_disconnected()
7341 dev[0].flush_scan_cache()
7342
7343def test_wps_ext_proto_ack_m3(dev, apdev):
7344 """WPS and ACK M3"""
7345 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7346 logger.debug("Send ACK to STA")
7347 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7348 send_wsc_msg(dev[0], bssid, msg)
7349 dev[0].request("WPS_CANCEL")
7350 dev[0].wait_disconnected()
7351 dev[0].flush_scan_cache()
7352
7353def wps_to_m3_helper(dev, apdev):
7354 pin = "12345670"
7355 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7356 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7357 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7358 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7359
7360 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7361 uuid_r = 16*'\x33'
7362 r_nonce = 16*'\x44'
7363 own_private, e_pk = wsc_dh_init()
7364
7365 logger.debug("Receive M1 from STA")
7366 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7367 eap_id = (msg['eap_identifier'] + 1) % 256
7368
7369 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7370 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7371 r_nonce)
7372 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7373 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7374
7375 logger.debug("Send M2 to STA")
7376 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7377 m1_attrs[ATTR_ENROLLEE_NONCE],
7378 r_nonce, uuid_r, e_pk)
7379 send_wsc_msg(dev[0], bssid, m2)
7380 eap_id = (eap_id + 1) % 256
7381
7382 logger.debug("Receive M3 from STA")
7383 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7384 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7385
7386def wps_to_m3(dev, apdev):
7387 eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey = wps_to_m3_helper(dev, apdev)
7388 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7389
7390def wps_to_m5(dev, apdev):
7391 eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey = wps_to_m3_helper(dev, apdev)
7392
7393 logger.debug("Send M4 to STA")
7394 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7395 attrs += build_attr_msg_type(WPS_M4)
7396 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7397 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7398 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7399 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7400 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7401 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7402 raw_m4_attrs = attrs
7403 m4 = build_eap_wsc(1, eap_id, attrs)
7404 send_wsc_msg(dev[0], bssid, m4)
7405 eap_id = (eap_id + 1) % 256
7406
7407 logger.debug("Receive M5 from STA")
7408 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7409
7410 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7411
7412def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7413 """WPS and no R-Hash1 in M4"""
7414 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7415
7416 logger.debug("Send M4 to STA")
7417 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7418 attrs += build_attr_msg_type(WPS_M4)
7419 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7420 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7421 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7422 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7423 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7424 attrs += build_attr_authenticator(authkey, m3, attrs)
7425 m4 = build_eap_wsc(1, eap_id, attrs)
7426 send_wsc_msg(dev[0], bssid, m4)
7427 eap_id = (eap_id + 1) % 256
7428
7429 logger.debug("Receive M5 (NACK) from STA")
7430 msg = get_wsc_msg(dev[0])
7431 if msg['wsc_opcode'] != WSC_NACK:
7432 raise Exception("Unexpected message - expected WSC_Nack")
7433
7434 dev[0].request("WPS_CANCEL")
7435 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7436 dev[0].wait_disconnected()
7437
7438def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7439 """WPS and no R-Hash2 in M4"""
7440 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7441
7442 logger.debug("Send M4 to STA")
7443 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7444 attrs += build_attr_msg_type(WPS_M4)
7445 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7446 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7447 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7448 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7449 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7450 attrs += build_attr_authenticator(authkey, m3, attrs)
7451 m4 = build_eap_wsc(1, eap_id, attrs)
7452 send_wsc_msg(dev[0], bssid, m4)
7453 eap_id = (eap_id + 1) % 256
7454
7455 logger.debug("Receive M5 (NACK) from STA")
7456 msg = get_wsc_msg(dev[0])
7457 if msg['wsc_opcode'] != WSC_NACK:
7458 raise Exception("Unexpected message - expected WSC_Nack")
7459
7460 dev[0].request("WPS_CANCEL")
7461 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7462 dev[0].wait_disconnected()
7463
7464def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7465 """WPS and no R-SNonce1 in M4"""
7466 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7467
7468 logger.debug("Send M4 to STA")
7469 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7470 attrs += build_attr_msg_type(WPS_M4)
7471 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7472 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7473 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7474 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7475 data = ''
7476 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7477 attrs += build_attr_authenticator(authkey, m3, attrs)
7478 m4 = build_eap_wsc(1, eap_id, attrs)
7479 send_wsc_msg(dev[0], bssid, m4)
7480 eap_id = (eap_id + 1) % 256
7481
7482 logger.debug("Receive M5 (NACK) from STA")
7483 msg = get_wsc_msg(dev[0])
7484 if msg['wsc_opcode'] != WSC_NACK:
7485 raise Exception("Unexpected message - expected WSC_Nack")
7486
7487 dev[0].request("WPS_CANCEL")
7488 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7489 dev[0].wait_disconnected()
7490
7491def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7492 """WPS and invalid pad string in M4"""
7493 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7494
7495 logger.debug("Send M4 to STA")
7496 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7497 attrs += build_attr_msg_type(WPS_M4)
7498 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7499 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7500 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7501 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7502
7503 m = hmac.new(authkey, data, hashlib.sha256)
7504 kwa = m.digest()[0:8]
7505 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7506 iv = 16*'\x99'
7507 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7508 pad_len = 16 - len(data) % 16
7509 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7510 data += ps
7511 wrapped = aes.encrypt(data)
7512 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7513
7514 attrs += build_attr_authenticator(authkey, m3, attrs)
7515 m4 = build_eap_wsc(1, eap_id, attrs)
7516 send_wsc_msg(dev[0], bssid, m4)
7517 eap_id = (eap_id + 1) % 256
7518
7519 logger.debug("Receive M5 (NACK) from STA")
7520 msg = get_wsc_msg(dev[0])
7521 if msg['wsc_opcode'] != WSC_NACK:
7522 raise Exception("Unexpected message - expected WSC_Nack")
7523
7524 dev[0].request("WPS_CANCEL")
7525 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7526 dev[0].wait_disconnected()
7527
7528def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7529 """WPS and invalid pad value in M4"""
7530 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7531
7532 logger.debug("Send M4 to STA")
7533 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7534 attrs += build_attr_msg_type(WPS_M4)
7535 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7536 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7537 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7538 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7539
7540 m = hmac.new(authkey, data, hashlib.sha256)
7541 kwa = m.digest()[0:8]
7542 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7543 iv = 16*'\x99'
7544 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7545 pad_len = 16 - len(data) % 16
7546 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7547 data += ps
7548 wrapped = aes.encrypt(data)
7549 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7550
7551 attrs += build_attr_authenticator(authkey, m3, attrs)
7552 m4 = build_eap_wsc(1, eap_id, attrs)
7553 send_wsc_msg(dev[0], bssid, m4)
7554 eap_id = (eap_id + 1) % 256
7555
7556 logger.debug("Receive M5 (NACK) from STA")
7557 msg = get_wsc_msg(dev[0])
7558 if msg['wsc_opcode'] != WSC_NACK:
7559 raise Exception("Unexpected message - expected WSC_Nack")
7560
7561 dev[0].request("WPS_CANCEL")
7562 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7563 dev[0].wait_disconnected()
7564
7565def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7566 """WPS and no Encr Settings in M4"""
7567 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7568
7569 logger.debug("Send M4 to STA")
7570 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7571 attrs += build_attr_msg_type(WPS_M4)
7572 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7573 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7574 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7575 attrs += build_attr_authenticator(authkey, m3, attrs)
7576 m4 = build_eap_wsc(1, eap_id, attrs)
7577 send_wsc_msg(dev[0], bssid, m4)
7578 eap_id = (eap_id + 1) % 256
7579
7580 logger.debug("Receive M5 (NACK) from STA")
7581 msg = get_wsc_msg(dev[0])
7582 if msg['wsc_opcode'] != WSC_NACK:
7583 raise Exception("Unexpected message - expected WSC_Nack")
7584
7585 dev[0].request("WPS_CANCEL")
7586 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7587 dev[0].wait_disconnected()
7588
7589def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7590 """WPS and no R-SNonce2 in M6"""
7591 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7592
7593 logger.debug("Send M6 to STA")
7594 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7595 attrs += build_attr_msg_type(WPS_M6)
7596 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7597 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7598 data = ''
7599 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7600 attrs += build_attr_authenticator(authkey, m5, attrs)
7601 m6 = build_eap_wsc(1, eap_id, attrs)
7602 send_wsc_msg(dev[0], bssid, m6)
7603 eap_id = (eap_id + 1) % 256
7604
7605 logger.debug("Receive M7 (NACK) from STA")
7606 msg = get_wsc_msg(dev[0])
7607 if msg['wsc_opcode'] != WSC_NACK:
7608 raise Exception("Unexpected message - expected WSC_Nack")
7609
7610 dev[0].request("WPS_CANCEL")
7611 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7612 dev[0].wait_disconnected()
7613
7614def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7615 """WPS and no Encr Settings in M6"""
7616 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7617
7618 logger.debug("Send M6 to STA")
7619 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7620 attrs += build_attr_msg_type(WPS_M6)
7621 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7622 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7623 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7624 attrs += build_attr_authenticator(authkey, m5, attrs)
7625 m6 = build_eap_wsc(1, eap_id, attrs)
7626 send_wsc_msg(dev[0], bssid, m6)
7627 eap_id = (eap_id + 1) % 256
7628
7629 logger.debug("Receive M7 (NACK) from STA")
7630 msg = get_wsc_msg(dev[0])
7631 if msg['wsc_opcode'] != WSC_NACK:
7632 raise Exception("Unexpected message - expected WSC_Nack")
7633
7634 dev[0].request("WPS_CANCEL")
7635 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7636 dev[0].wait_disconnected()
7637
7638def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7639 """WPS and no Encr Settings in M6"""
7640 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7641
7642 logger.debug("Send M6 to STA")
7643 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7644 attrs += build_attr_msg_type(WPS_M6)
7645 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7646 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7647 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7648 attrs += build_attr_authenticator(authkey, m5, attrs)
7649 raw_m6_attrs = attrs
7650 m6 = build_eap_wsc(1, eap_id, attrs)
7651 send_wsc_msg(dev[0], bssid, m6)
7652 eap_id = (eap_id + 1) % 256
7653
7654 logger.debug("Receive M7 from STA")
7655 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7656
7657 logger.debug("Send M8 to STA")
7658 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7659 attrs += build_attr_msg_type(WPS_M8)
7660 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7661 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7662 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7663 raw_m8_attrs = attrs
7664 m8 = build_eap_wsc(1, eap_id, attrs)
7665 send_wsc_msg(dev[0], bssid, m8)
7666
7667 logger.debug("Receive WSC_Done (NACK) from STA")
7668 msg = get_wsc_msg(dev[0])
7669 if msg['wsc_opcode'] != WSC_NACK:
7670 raise Exception("Unexpected message - expected WSC_Nack")
7671
7672 dev[0].request("WPS_CANCEL")
7673 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7674 dev[0].wait_disconnected()
7675
7676def wps_start_ext_reg(apdev, dev):
7677 addr = dev.own_addr()
7678 bssid = apdev['bssid']
7679 ssid = "test-wps-conf"
7680 appin = "12345670"
7681 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
7682 "wpa_passphrase": "12345678", "wpa": "2",
7683 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7684 "ap_pin": appin }
afc26df2 7685 hapd = hostapd.add_ap(apdev, params)
7511ead0
JM
7686
7687 dev.scan_for_bss(bssid, freq="2412")
7688 hapd.request("SET ext_eapol_frame_io 1")
7689 dev.request("SET ext_eapol_frame_io 1")
7690
7691 dev.request("WPS_REG " + bssid + " " + appin)
7692
7693 return addr,bssid,hapd
7694
7695def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7696 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7697 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7698 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7699
7700 logger.debug("Receive M1 from AP")
7701 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7702 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7703 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7704 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7705
7706 appin = '12345670'
7707 uuid_r = 16*'\x33'
7708 r_nonce = 16*'\x44'
7709 own_private, r_pk = wsc_dh_init()
7710 authkey,keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7711 r_nonce)
7712 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7713
7714 logger.debug("Send M2 to AP")
7715 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7716 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7717 send_wsc_msg(hapd, addr, m2)
7718
7719 logger.debug("Receive M3 from AP")
7720 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7721
7722 logger.debug("Send M4 to AP")
7723 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7724 attrs += build_attr_msg_type(WPS_M4)
7725 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7726 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7727 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7728 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7729 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7730 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7731 raw_m4_attrs = attrs
7732 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7733 send_wsc_msg(hapd, addr, m4)
7734
7735 logger.debug("Receive M5 from AP")
7736 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7737
7738 logger.debug("Send M6 to STA")
7739 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7740 attrs += build_attr_msg_type(WPS_M6)
7741 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7742 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7743 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7744 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7745 raw_m6_attrs = attrs
7746 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7747 send_wsc_msg(hapd, addr, m6)
7748
7749 logger.debug("Receive M7 from AP")
7750 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7751
7752 logger.debug("Send M8 to STA")
7753 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7754 attrs += build_attr_msg_type(WPS_M8)
7755 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7756 if ap_settings:
7757 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7758 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7759 raw_m8_attrs = attrs
7760 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7761 send_wsc_msg(hapd, addr, m8)
7762
7763 if success:
7764 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7765 if ev is None:
7766 raise Exception("New AP settings not reported")
7767 logger.debug("Receive WSC_Done from AP")
7768 msg = get_wsc_msg(hapd)
7769 if msg['wsc_opcode'] != WSC_Done:
7770 raise Exception("Unexpected message - expected WSC_Done")
7771
7772 logger.debug("Send WSC_ACK to AP")
7773 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7774 eap_code=2)
7775 send_wsc_msg(hapd, addr, ack)
7776 dev[0].wait_disconnected()
7777 else:
7778 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7779 if ev is None:
7780 raise Exception("WPS failure not reported")
7781 logger.debug("Receive WSC_NACK from AP")
7782 msg = get_wsc_msg(hapd)
7783 if msg['wsc_opcode'] != WSC_NACK:
7784 raise Exception("Unexpected message - expected WSC_NACK")
7785
7786 logger.debug("Send WSC_NACK to AP")
7787 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7788 eap_code=2)
7789 send_wsc_msg(hapd, addr, nack)
7790 dev[0].wait_disconnected()
7791
7792def test_wps_ext_ap_settings_success(dev, apdev):
7793 """WPS and AP Settings: success"""
7794 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7795 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7796 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7797 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7798 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7799 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7800 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7801
9fd6804d 7802@remote_compatible
7511ead0
JM
7803def test_wps_ext_ap_settings_missing(dev, apdev):
7804 """WPS and AP Settings: missing"""
7805 wps_run_ap_settings_proto(dev, apdev, None, False)
7806
9fd6804d 7807@remote_compatible
7511ead0
JM
7808def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7809 """WPS and AP Settings: MAC Address mismatch"""
7810 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7811 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7812 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7813 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7814 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7815 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7816 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7817
9fd6804d 7818@remote_compatible
7511ead0
JM
7819def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7820 """WPS and AP Settings: missing MAC Address"""
7821 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7822 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7823 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7824 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7825 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7826 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7827
9fd6804d 7828@remote_compatible
7511ead0
JM
7829def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7830 """WPS and AP Settings: reject Encr Type"""
7831 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7832 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7833 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7834 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7835 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7836 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7837 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7838
9fd6804d 7839@remote_compatible
7511ead0
JM
7840def test_wps_ext_ap_settings_m2d(dev, apdev):
7841 """WPS and AP Settings: M2D"""
7842 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7843 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7844 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7845
7846 logger.debug("Receive M1 from AP")
7847 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7848 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7849
7850 r_nonce = 16*'\x44'
7851 uuid_r = 16*'\x33'
7852
7853 logger.debug("Send M2D to AP")
7854 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7855 e_nonce, r_nonce, uuid_r,
7856 dev_pw_id='\x00\x00', eap_code=2)
7857 send_wsc_msg(hapd, addr, m2d)
7858
7859 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7860 if ev is None:
7861 raise Exception("M2D not reported")
7862
7863 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7864
7865def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7866 logger.debug("Receive WSC_NACK from AP")
7867 msg = get_wsc_msg(hapd)
7868 if msg['wsc_opcode'] != WSC_NACK:
7869 raise Exception("Unexpected message - expected WSC_NACK")
7870
7871 logger.debug("Send WSC_NACK to AP")
7872 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7873 eap_code=2)
7874 send_wsc_msg(hapd, dev.own_addr(), nack)
7875 dev.wait_disconnected()
7876
9fd6804d 7877@remote_compatible
7511ead0
JM
7878def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7879 """WPS proto: M3 missing E-Hash1"""
7880 pin = "12345670"
7881 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7882 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7883 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7884
7885 logger.debug("Receive WSC/Start from AP")
7886 msg = get_wsc_msg(hapd)
7887 if msg['wsc_opcode'] != WSC_Start:
7888 raise Exception("Unexpected Op-Code for WSC/Start")
7889
7890 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7891 uuid_e = 16*'\x11'
7892 e_nonce = 16*'\x22'
7893 own_private, e_pk = wsc_dh_init()
7894
7895 logger.debug("Send M1 to AP")
7896 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7897 e_nonce, e_pk)
7898 send_wsc_msg(hapd, addr, m1)
7899
7900 logger.debug("Receive M2 from AP")
7901 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7902 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7903 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7904
7905 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7906 r_nonce)
7907 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7908
7909 logger.debug("Send M3 to AP")
7910 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7911 attrs += build_attr_msg_type(WPS_M3)
7912 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7913 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7914 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7915 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7916 raw_m3_attrs = attrs
7917 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7918 send_wsc_msg(hapd, addr, m3)
7919
7920 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7921
9fd6804d 7922@remote_compatible
7511ead0
JM
7923def test_wps_ext_m3_missing_e_hash2(dev, apdev):
7924 """WPS proto: M3 missing E-Hash2"""
7925 pin = "12345670"
7926 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7927 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7928 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7929
7930 logger.debug("Receive WSC/Start from AP")
7931 msg = get_wsc_msg(hapd)
7932 if msg['wsc_opcode'] != WSC_Start:
7933 raise Exception("Unexpected Op-Code for WSC/Start")
7934
7935 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7936 uuid_e = 16*'\x11'
7937 e_nonce = 16*'\x22'
7938 own_private, e_pk = wsc_dh_init()
7939
7940 logger.debug("Send M1 to AP")
7941 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7942 e_nonce, e_pk)
7943 send_wsc_msg(hapd, addr, m1)
7944
7945 logger.debug("Receive M2 from AP")
7946 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7947 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7948 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7949
7950 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7951 r_nonce)
7952 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7953
7954 logger.debug("Send M3 to AP")
7955 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7956 attrs += build_attr_msg_type(WPS_M3)
7957 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7958 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7959 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7960 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7961 raw_m3_attrs = attrs
7962 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7963 send_wsc_msg(hapd, addr, m3)
7964
7965 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7966
9fd6804d 7967@remote_compatible
7511ead0
JM
7968def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
7969 """WPS proto: M5 missing E-SNonce1"""
7970 pin = "12345670"
7971 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7972 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7973 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7974
7975 logger.debug("Receive WSC/Start from AP")
7976 msg = get_wsc_msg(hapd)
7977 if msg['wsc_opcode'] != WSC_Start:
7978 raise Exception("Unexpected Op-Code for WSC/Start")
7979
7980 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7981 uuid_e = 16*'\x11'
7982 e_nonce = 16*'\x22'
7983 own_private, e_pk = wsc_dh_init()
7984
7985 logger.debug("Send M1 to AP")
7986 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7987 e_nonce, e_pk)
7988 send_wsc_msg(hapd, addr, m1)
7989
7990 logger.debug("Receive M2 from AP")
7991 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7992 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7993 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7994
7995 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7996 r_nonce)
7997 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7998
7999 logger.debug("Send M3 to AP")
8000 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8001 attrs += build_attr_msg_type(WPS_M3)
8002 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8003 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8004 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8005 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8006 raw_m3_attrs = attrs
8007 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8008 send_wsc_msg(hapd, addr, m3)
8009
8010 logger.debug("Receive M4 from AP")
8011 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8012
8013 logger.debug("Send M5 to AP")
8014 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8015 attrs += build_attr_msg_type(WPS_M5)
8016 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8017 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8018 data = ''
8019 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8020 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8021 raw_m5_attrs = attrs
8022 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8023 send_wsc_msg(hapd, addr, m5)
8024
8025 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8026
9fd6804d 8027@remote_compatible
7511ead0
JM
8028def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8029 """WPS proto: M5 E-SNonce1 mismatch"""
8030 pin = "12345670"
8031 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8032 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8033 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8034
8035 logger.debug("Receive WSC/Start from AP")
8036 msg = get_wsc_msg(hapd)
8037 if msg['wsc_opcode'] != WSC_Start:
8038 raise Exception("Unexpected Op-Code for WSC/Start")
8039
8040 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8041 uuid_e = 16*'\x11'
8042 e_nonce = 16*'\x22'
8043 own_private, e_pk = wsc_dh_init()
8044
8045 logger.debug("Send M1 to AP")
8046 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8047 e_nonce, e_pk)
8048 send_wsc_msg(hapd, addr, m1)
8049
8050 logger.debug("Receive M2 from AP")
8051 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8052 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8053 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8054
8055 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8056 r_nonce)
8057 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8058
8059 logger.debug("Send M3 to AP")
8060 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8061 attrs += build_attr_msg_type(WPS_M3)
8062 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8063 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8064 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8065 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8066 raw_m3_attrs = attrs
8067 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8068 send_wsc_msg(hapd, addr, m3)
8069
8070 logger.debug("Receive M4 from AP")
8071 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8072
8073 logger.debug("Send M5 to AP")
8074 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8075 attrs += build_attr_msg_type(WPS_M5)
8076 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8077 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8078 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8079 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8080 raw_m5_attrs = attrs
8081 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8082 send_wsc_msg(hapd, addr, m5)
8083
8084 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8085
8086def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8087 """WPS proto: M7 missing E-SNonce2"""
8088 pin = "12345670"
8089 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8090 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8091 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8092
8093 logger.debug("Receive WSC/Start from AP")
8094 msg = get_wsc_msg(hapd)
8095 if msg['wsc_opcode'] != WSC_Start:
8096 raise Exception("Unexpected Op-Code for WSC/Start")
8097
8098 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8099 uuid_e = 16*'\x11'
8100 e_nonce = 16*'\x22'
8101 own_private, e_pk = wsc_dh_init()
8102
8103 logger.debug("Send M1 to AP")
8104 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8105 e_nonce, e_pk)
8106 send_wsc_msg(hapd, addr, m1)
8107
8108 logger.debug("Receive M2 from AP")
8109 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8110 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8111 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8112
8113 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8114 r_nonce)
8115 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8116
8117 logger.debug("Send M3 to AP")
8118 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8119 attrs += build_attr_msg_type(WPS_M3)
8120 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8121 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8122 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8123 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8124 raw_m3_attrs = attrs
8125 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8126 send_wsc_msg(hapd, addr, m3)
8127
8128 logger.debug("Receive M4 from AP")
8129 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8130
8131 logger.debug("Send M5 to AP")
8132 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8133 attrs += build_attr_msg_type(WPS_M5)
8134 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8135 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8136 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8137 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8138 raw_m5_attrs = attrs
8139 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8140 send_wsc_msg(hapd, addr, m5)
8141
8142 logger.debug("Receive M6 from AP")
8143 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8144
8145 logger.debug("Send M7 to AP")
8146 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8147 attrs += build_attr_msg_type(WPS_M7)
8148 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8149 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8150 data = ''
8151 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8152 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8153 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8154 raw_m7_attrs = attrs
8155 send_wsc_msg(hapd, addr, m7)
8156
8157 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8158
9fd6804d 8159@remote_compatible
7511ead0
JM
8160def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8161 """WPS proto: M7 E-SNonce2 mismatch"""
8162 pin = "12345670"
8163 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8164 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8165 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8166
8167 logger.debug("Receive WSC/Start from AP")
8168 msg = get_wsc_msg(hapd)
8169 if msg['wsc_opcode'] != WSC_Start:
8170 raise Exception("Unexpected Op-Code for WSC/Start")
8171
8172 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8173 uuid_e = 16*'\x11'
8174 e_nonce = 16*'\x22'
8175 own_private, e_pk = wsc_dh_init()
8176
8177 logger.debug("Send M1 to AP")
8178 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8179 e_nonce, e_pk)
8180 send_wsc_msg(hapd, addr, m1)
8181
8182 logger.debug("Receive M2 from AP")
8183 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8184 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8185 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8186
8187 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8188 r_nonce)
8189 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8190
8191 logger.debug("Send M3 to AP")
8192 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8193 attrs += build_attr_msg_type(WPS_M3)
8194 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8195 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8196 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8197 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8198 raw_m3_attrs = attrs
8199 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8200 send_wsc_msg(hapd, addr, m3)
8201
8202 logger.debug("Receive M4 from AP")
8203 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8204
8205 logger.debug("Send M5 to AP")
8206 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8207 attrs += build_attr_msg_type(WPS_M5)
8208 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8209 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8210 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8211 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8212 raw_m5_attrs = attrs
8213 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8214 send_wsc_msg(hapd, addr, m5)
8215
8216 logger.debug("Receive M6 from AP")
8217 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8218
8219 logger.debug("Send M7 to AP")
8220 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8221 attrs += build_attr_msg_type(WPS_M7)
8222 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8223 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8224 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8225 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8226 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8227 raw_m7_attrs = attrs
8228 send_wsc_msg(hapd, addr, m7)
8229
8230 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8231
9fd6804d 8232@remote_compatible
7511ead0
JM
8233def test_wps_ext_m1_pubkey_oom(dev, apdev):
8234 """WPS proto: M1 PubKey OOM"""
8235 pin = "12345670"
8236 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8237 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8238 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8239
8240 logger.debug("Receive WSC/Start from AP")
8241 msg = get_wsc_msg(hapd)
8242 if msg['wsc_opcode'] != WSC_Start:
8243 raise Exception("Unexpected Op-Code for WSC/Start")
8244
8245 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8246 uuid_e = 16*'\x11'
8247 e_nonce = 16*'\x22'
8248 own_private, e_pk = wsc_dh_init()
8249
8250 logger.debug("Send M1 to AP")
8251 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8252 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8253 e_nonce, e_pk)
8254 send_wsc_msg(hapd, addr, m1)
8255 wps_wait_eap_failure(hapd, dev[0])
8256
8257def wps_wait_eap_failure(hapd, dev):
8258 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8259 if ev is None:
8260 raise Exception("EAP-Failure not reported")
8261 dev.wait_disconnected()
8262
9fd6804d 8263@remote_compatible
7511ead0
JM
8264def test_wps_ext_m3_m1(dev, apdev):
8265 """WPS proto: M3 replaced with M1"""
8266 pin = "12345670"
8267 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8268 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8269 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8270
8271 logger.debug("Receive WSC/Start from AP")
8272 msg = get_wsc_msg(hapd)
8273 if msg['wsc_opcode'] != WSC_Start:
8274 raise Exception("Unexpected Op-Code for WSC/Start")
8275
8276 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8277 uuid_e = 16*'\x11'
8278 e_nonce = 16*'\x22'
8279 own_private, e_pk = wsc_dh_init()
8280
8281 logger.debug("Send M1 to AP")
8282 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8283 e_nonce, e_pk)
8284 send_wsc_msg(hapd, addr, m1)
8285
8286 logger.debug("Receive M2 from AP")
8287 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8288 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8289 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8290
8291 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8292 r_nonce)
8293 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8294
8295 logger.debug("Send M3(M1) to AP")
8296 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8297 attrs += build_attr_msg_type(WPS_M1)
8298 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8299 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8300 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8301 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8302 raw_m3_attrs = attrs
8303 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8304 send_wsc_msg(hapd, addr, m3)
8305
8306 wps_wait_eap_failure(hapd, dev[0])
8307
9fd6804d 8308@remote_compatible
7511ead0
JM
8309def test_wps_ext_m5_m3(dev, apdev):
8310 """WPS proto: M5 replaced with M3"""
8311 pin = "12345670"
8312 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8313 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8314 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8315
8316 logger.debug("Receive WSC/Start from AP")
8317 msg = get_wsc_msg(hapd)
8318 if msg['wsc_opcode'] != WSC_Start:
8319 raise Exception("Unexpected Op-Code for WSC/Start")
8320
8321 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8322 uuid_e = 16*'\x11'
8323 e_nonce = 16*'\x22'
8324 own_private, e_pk = wsc_dh_init()
8325
8326 logger.debug("Send M1 to AP")
8327 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8328 e_nonce, e_pk)
8329 send_wsc_msg(hapd, addr, m1)
8330
8331 logger.debug("Receive M2 from AP")
8332 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8333 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8334 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8335
8336 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8337 r_nonce)
8338 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8339
8340 logger.debug("Send M3 to AP")
8341 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8342 attrs += build_attr_msg_type(WPS_M3)
8343 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8344 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8345 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8346 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8347 raw_m3_attrs = attrs
8348 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8349 send_wsc_msg(hapd, addr, m3)
8350
8351 logger.debug("Receive M4 from AP")
8352 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8353
8354 logger.debug("Send M5(M3) to AP")
8355 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8356 attrs += build_attr_msg_type(WPS_M3)
8357 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8358 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8359 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8360 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8361 raw_m5_attrs = attrs
8362 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8363 send_wsc_msg(hapd, addr, m5)
8364
8365 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8366
9fd6804d 8367@remote_compatible
7511ead0
JM
8368def test_wps_ext_m3_m2(dev, apdev):
8369 """WPS proto: M3 replaced with M2"""
8370 pin = "12345670"
8371 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8372 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8373 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8374
8375 logger.debug("Receive WSC/Start from AP")
8376 msg = get_wsc_msg(hapd)
8377 if msg['wsc_opcode'] != WSC_Start:
8378 raise Exception("Unexpected Op-Code for WSC/Start")
8379
8380 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8381 uuid_e = 16*'\x11'
8382 e_nonce = 16*'\x22'
8383 own_private, e_pk = wsc_dh_init()
8384
8385 logger.debug("Send M1 to AP")
8386 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8387 e_nonce, e_pk)
8388 send_wsc_msg(hapd, addr, m1)
8389
8390 logger.debug("Receive M2 from AP")
8391 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8392 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8393 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8394
8395 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8396 r_nonce)
8397 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8398
8399 logger.debug("Send M3(M2) to AP")
8400 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8401 attrs += build_attr_msg_type(WPS_M2)
8402 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8403 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8404 raw_m3_attrs = attrs
8405 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8406 send_wsc_msg(hapd, addr, m3)
8407
8408 wps_wait_eap_failure(hapd, dev[0])
8409
9fd6804d 8410@remote_compatible
7511ead0
JM
8411def test_wps_ext_m3_m5(dev, apdev):
8412 """WPS proto: M3 replaced with M5"""
8413 pin = "12345670"
8414 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8415 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8416 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8417
8418 logger.debug("Receive WSC/Start from AP")
8419 msg = get_wsc_msg(hapd)
8420 if msg['wsc_opcode'] != WSC_Start:
8421 raise Exception("Unexpected Op-Code for WSC/Start")
8422
8423 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8424 uuid_e = 16*'\x11'
8425 e_nonce = 16*'\x22'
8426 own_private, e_pk = wsc_dh_init()
8427
8428 logger.debug("Send M1 to AP")
8429 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8430 e_nonce, e_pk)
8431 send_wsc_msg(hapd, addr, m1)
8432
8433 logger.debug("Receive M2 from AP")
8434 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8435 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8436 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8437
8438 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8439 r_nonce)
8440 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8441
8442 logger.debug("Send M3(M5) to AP")
8443 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8444 attrs += build_attr_msg_type(WPS_M5)
8445 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8446 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8447 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8448 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8449 raw_m3_attrs = attrs
8450 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8451 send_wsc_msg(hapd, addr, m3)
8452
8453 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8454
9fd6804d 8455@remote_compatible
7511ead0
JM
8456def test_wps_ext_m3_m7(dev, apdev):
8457 """WPS proto: M3 replaced with M7"""
8458 pin = "12345670"
8459 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8460 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8461 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8462
8463 logger.debug("Receive WSC/Start from AP")
8464 msg = get_wsc_msg(hapd)
8465 if msg['wsc_opcode'] != WSC_Start:
8466 raise Exception("Unexpected Op-Code for WSC/Start")
8467
8468 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8469 uuid_e = 16*'\x11'
8470 e_nonce = 16*'\x22'
8471 own_private, e_pk = wsc_dh_init()
8472
8473 logger.debug("Send M1 to AP")
8474 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8475 e_nonce, e_pk)
8476 send_wsc_msg(hapd, addr, m1)
8477
8478 logger.debug("Receive M2 from AP")
8479 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8480 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8481 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8482
8483 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8484 r_nonce)
8485 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8486
8487 logger.debug("Send M3(M7) to AP")
8488 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8489 attrs += build_attr_msg_type(WPS_M7)
8490 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8491 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8492 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8493 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8494 raw_m3_attrs = attrs
8495 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8496 send_wsc_msg(hapd, addr, m3)
8497
8498 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8499
9fd6804d 8500@remote_compatible
7511ead0
JM
8501def test_wps_ext_m3_done(dev, apdev):
8502 """WPS proto: M3 replaced with WSC_Done"""
8503 pin = "12345670"
8504 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8505 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8506 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8507
8508 logger.debug("Receive WSC/Start from AP")
8509 msg = get_wsc_msg(hapd)
8510 if msg['wsc_opcode'] != WSC_Start:
8511 raise Exception("Unexpected Op-Code for WSC/Start")
8512
8513 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8514 uuid_e = 16*'\x11'
8515 e_nonce = 16*'\x22'
8516 own_private, e_pk = wsc_dh_init()
8517
8518 logger.debug("Send M1 to AP")
8519 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8520 e_nonce, e_pk)
8521 send_wsc_msg(hapd, addr, m1)
8522
8523 logger.debug("Receive M2 from AP")
8524 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8525 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8526 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8527
8528 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8529 r_nonce)
8530 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8531
8532 logger.debug("Send M3(WSC_Done) to AP")
8533 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8534 attrs += build_attr_msg_type(WPS_WSC_DONE)
8535 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8536 raw_m3_attrs = attrs
8537 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8538 send_wsc_msg(hapd, addr, m3)
8539
8540 wps_wait_eap_failure(hapd, dev[0])
8541
9fd6804d 8542@remote_compatible
7511ead0
JM
8543def test_wps_ext_m2_nack_invalid(dev, apdev):
8544 """WPS proto: M2 followed by invalid NACK"""
8545 pin = "12345670"
8546 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8547 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8548 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8549
8550 logger.debug("Receive WSC/Start from AP")
8551 msg = get_wsc_msg(hapd)
8552 if msg['wsc_opcode'] != WSC_Start:
8553 raise Exception("Unexpected Op-Code for WSC/Start")
8554
8555 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8556 uuid_e = 16*'\x11'
8557 e_nonce = 16*'\x22'
8558 own_private, e_pk = wsc_dh_init()
8559
8560 logger.debug("Send M1 to AP")
8561 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8562 e_nonce, e_pk)
8563 send_wsc_msg(hapd, addr, m1)
8564
8565 logger.debug("Receive M2 from AP")
8566 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8567 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8568 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8569
8570 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8571 r_nonce)
8572 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8573
8574 logger.debug("Send WSC_NACK to AP")
8575 attrs = '\x10\x00\x00'
8576 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8577 send_wsc_msg(hapd, addr, nack)
8578
8579 wps_wait_eap_failure(hapd, dev[0])
8580
9fd6804d 8581@remote_compatible
7511ead0
JM
8582def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8583 """WPS proto: M2 followed by NACK without Msg Type"""
8584 pin = "12345670"
8585 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8586 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8587 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8588
8589 logger.debug("Receive WSC/Start from AP")
8590 msg = get_wsc_msg(hapd)
8591 if msg['wsc_opcode'] != WSC_Start:
8592 raise Exception("Unexpected Op-Code for WSC/Start")
8593
8594 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8595 uuid_e = 16*'\x11'
8596 e_nonce = 16*'\x22'
8597 own_private, e_pk = wsc_dh_init()
8598
8599 logger.debug("Send M1 to AP")
8600 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8601 e_nonce, e_pk)
8602 send_wsc_msg(hapd, addr, m1)
8603
8604 logger.debug("Receive M2 from AP")
8605 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8606 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8607 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8608
8609 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8610 r_nonce)
8611 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8612
8613 logger.debug("Send WSC_NACK to AP")
8614 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8615 msg_type=None, eap_code=2)
8616 send_wsc_msg(hapd, addr, nack)
8617
8618 wps_wait_eap_failure(hapd, dev[0])
8619
9fd6804d 8620@remote_compatible
7511ead0
JM
8621def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8622 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8623 pin = "12345670"
8624 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8625 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8626 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8627
8628 logger.debug("Receive WSC/Start from AP")
8629 msg = get_wsc_msg(hapd)
8630 if msg['wsc_opcode'] != WSC_Start:
8631 raise Exception("Unexpected Op-Code for WSC/Start")
8632
8633 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8634 uuid_e = 16*'\x11'
8635 e_nonce = 16*'\x22'
8636 own_private, e_pk = wsc_dh_init()
8637
8638 logger.debug("Send M1 to AP")
8639 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8640 e_nonce, e_pk)
8641 send_wsc_msg(hapd, addr, m1)
8642
8643 logger.debug("Receive M2 from AP")
8644 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8645 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8646 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8647
8648 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8649 r_nonce)
8650 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8651
8652 logger.debug("Send WSC_NACK to AP")
8653 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8654 msg_type=WPS_WSC_ACK, eap_code=2)
8655 send_wsc_msg(hapd, addr, nack)
8656
8657 wps_wait_eap_failure(hapd, dev[0])
8658
9fd6804d 8659@remote_compatible
7511ead0
JM
8660def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8661 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8662 pin = "12345670"
8663 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8664 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8665 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8666
8667 logger.debug("Receive WSC/Start from AP")
8668 msg = get_wsc_msg(hapd)
8669 if msg['wsc_opcode'] != WSC_Start:
8670 raise Exception("Unexpected Op-Code for WSC/Start")
8671
8672 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8673 uuid_e = 16*'\x11'
8674 e_nonce = 16*'\x22'
8675 own_private, e_pk = wsc_dh_init()
8676
8677 logger.debug("Send M1 to AP")
8678 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8679 e_nonce, e_pk)
8680 send_wsc_msg(hapd, addr, m1)
8681
8682 logger.debug("Receive M2 from AP")
8683 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8684 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8685 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8686
8687 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8688 r_nonce)
8689 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8690
8691 logger.debug("Send WSC_NACK to AP")
8692 nack,attrs = build_nack(msg['eap_identifier'], 16*'\x00', r_nonce,
8693 eap_code=2)
8694 send_wsc_msg(hapd, addr, nack)
8695
8696 wps_wait_eap_failure(hapd, dev[0])
8697
9fd6804d 8698@remote_compatible
7511ead0
JM
8699def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8700 """WPS proto: M2 followed by NACK without Config Error"""
8701 pin = "12345670"
8702 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8703 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8704 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8705
8706 logger.debug("Receive WSC/Start from AP")
8707 msg = get_wsc_msg(hapd)
8708 if msg['wsc_opcode'] != WSC_Start:
8709 raise Exception("Unexpected Op-Code for WSC/Start")
8710
8711 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8712 uuid_e = 16*'\x11'
8713 e_nonce = 16*'\x22'
8714 own_private, e_pk = wsc_dh_init()
8715
8716 logger.debug("Send M1 to AP")
8717 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8718 e_nonce, e_pk)
8719 send_wsc_msg(hapd, addr, m1)
8720
8721 logger.debug("Receive M2 from AP")
8722 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8723 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8724 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8725
8726 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8727 r_nonce)
8728 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8729
8730 logger.debug("Send WSC_NACK to AP")
8731 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8732 config_error=None, eap_code=2)
8733 send_wsc_msg(hapd, addr, nack)
8734
8735 wps_wait_eap_failure(hapd, dev[0])
8736
9fd6804d 8737@remote_compatible
7511ead0
JM
8738def test_wps_ext_m2_ack_invalid(dev, apdev):
8739 """WPS proto: M2 followed by invalid ACK"""
8740 pin = "12345670"
8741 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8742 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8743 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8744
8745 logger.debug("Receive WSC/Start from AP")
8746 msg = get_wsc_msg(hapd)
8747 if msg['wsc_opcode'] != WSC_Start:
8748 raise Exception("Unexpected Op-Code for WSC/Start")
8749
8750 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8751 uuid_e = 16*'\x11'
8752 e_nonce = 16*'\x22'
8753 own_private, e_pk = wsc_dh_init()
8754
8755 logger.debug("Send M1 to AP")
8756 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8757 e_nonce, e_pk)
8758 send_wsc_msg(hapd, addr, m1)
8759
8760 logger.debug("Receive M2 from AP")
8761 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8762 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8763 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8764
8765 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8766 r_nonce)
8767 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8768
8769 logger.debug("Send WSC_ACK to AP")
8770 attrs = '\x10\x00\x00'
8771 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8772 send_wsc_msg(hapd, addr, ack)
8773
8774 wps_wait_eap_failure(hapd, dev[0])
8775
9fd6804d 8776@remote_compatible
7511ead0
JM
8777def test_wps_ext_m2_ack(dev, apdev):
8778 """WPS proto: M2 followed by ACK"""
8779 pin = "12345670"
8780 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8781 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8782 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8783
8784 logger.debug("Receive WSC/Start from AP")
8785 msg = get_wsc_msg(hapd)
8786 if msg['wsc_opcode'] != WSC_Start:
8787 raise Exception("Unexpected Op-Code for WSC/Start")
8788
8789 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8790 uuid_e = 16*'\x11'
8791 e_nonce = 16*'\x22'
8792 own_private, e_pk = wsc_dh_init()
8793
8794 logger.debug("Send M1 to AP")
8795 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8796 e_nonce, e_pk)
8797 send_wsc_msg(hapd, addr, m1)
8798
8799 logger.debug("Receive M2 from AP")
8800 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8801 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8802 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8803
8804 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8805 r_nonce)
8806 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8807
8808 logger.debug("Send WSC_ACK to AP")
8809 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8810 send_wsc_msg(hapd, addr, ack)
8811
8812 wps_wait_eap_failure(hapd, dev[0])
8813
9fd6804d 8814@remote_compatible
7511ead0
JM
8815def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8816 """WPS proto: M2 followed by ACK missing Msg Type"""
8817 pin = "12345670"
8818 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8819 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8820 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8821
8822 logger.debug("Receive WSC/Start from AP")
8823 msg = get_wsc_msg(hapd)
8824 if msg['wsc_opcode'] != WSC_Start:
8825 raise Exception("Unexpected Op-Code for WSC/Start")
8826
8827 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8828 uuid_e = 16*'\x11'
8829 e_nonce = 16*'\x22'
8830 own_private, e_pk = wsc_dh_init()
8831
8832 logger.debug("Send M1 to AP")
8833 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8834 e_nonce, e_pk)
8835 send_wsc_msg(hapd, addr, m1)
8836
8837 logger.debug("Receive M2 from AP")
8838 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8839 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8840 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8841
8842 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8843 r_nonce)
8844 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8845
8846 logger.debug("Send WSC_ACK to AP")
8847 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8848 msg_type=None, eap_code=2)
8849 send_wsc_msg(hapd, addr, ack)
8850
8851 wps_wait_eap_failure(hapd, dev[0])
8852
9fd6804d 8853@remote_compatible
7511ead0
JM
8854def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8855 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8856 pin = "12345670"
8857 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8858 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8859 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8860
8861 logger.debug("Receive WSC/Start from AP")
8862 msg = get_wsc_msg(hapd)
8863 if msg['wsc_opcode'] != WSC_Start:
8864 raise Exception("Unexpected Op-Code for WSC/Start")
8865
8866 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8867 uuid_e = 16*'\x11'
8868 e_nonce = 16*'\x22'
8869 own_private, e_pk = wsc_dh_init()
8870
8871 logger.debug("Send M1 to AP")
8872 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8873 e_nonce, e_pk)
8874 send_wsc_msg(hapd, addr, m1)
8875
8876 logger.debug("Receive M2 from AP")
8877 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8878 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8879 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8880
8881 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8882 r_nonce)
8883 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8884
8885 logger.debug("Send WSC_ACK to AP")
8886 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8887 msg_type=WPS_WSC_NACK, eap_code=2)
8888 send_wsc_msg(hapd, addr, ack)
8889
8890 wps_wait_eap_failure(hapd, dev[0])
8891
9fd6804d 8892@remote_compatible
7511ead0
JM
8893def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8894 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8895 pin = "12345670"
8896 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8897 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8898 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8899
8900 logger.debug("Receive WSC/Start from AP")
8901 msg = get_wsc_msg(hapd)
8902 if msg['wsc_opcode'] != WSC_Start:
8903 raise Exception("Unexpected Op-Code for WSC/Start")
8904
8905 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8906 uuid_e = 16*'\x11'
8907 e_nonce = 16*'\x22'
8908 own_private, e_pk = wsc_dh_init()
8909
8910 logger.debug("Send M1 to AP")
8911 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8912 e_nonce, e_pk)
8913 send_wsc_msg(hapd, addr, m1)
8914
8915 logger.debug("Receive M2 from AP")
8916 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8917 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8918 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8919
8920 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8921 r_nonce)
8922 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8923
8924 logger.debug("Send WSC_ACK to AP")
8925 ack,attrs = build_ack(msg['eap_identifier'], 16*'\x00', r_nonce,
8926 eap_code=2)
8927 send_wsc_msg(hapd, addr, ack)
8928
8929 wps_wait_eap_failure(hapd, dev[0])
8930
9fd6804d 8931@remote_compatible
7511ead0
JM
8932def test_wps_ext_m1_invalid(dev, apdev):
8933 """WPS proto: M1 failing parsing"""
8934 pin = "12345670"
8935 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8936 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8937 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8938
8939 logger.debug("Receive WSC/Start from AP")
8940 msg = get_wsc_msg(hapd)
8941 if msg['wsc_opcode'] != WSC_Start:
8942 raise Exception("Unexpected Op-Code for WSC/Start")
8943
8944 logger.debug("Send M1 to AP")
8945 attrs = '\x10\x00\x00'
8946 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8947 send_wsc_msg(hapd, addr, m1)
8948
8949 wps_wait_eap_failure(hapd, dev[0])
8950
8951def test_wps_ext_m1_missing_msg_type(dev, apdev):
8952 """WPS proto: M1 missing Msg Type"""
8953 pin = "12345670"
8954 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8955 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8956 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8957
8958 logger.debug("Receive WSC/Start from AP")
8959 msg = get_wsc_msg(hapd)
8960 if msg['wsc_opcode'] != WSC_Start:
8961 raise Exception("Unexpected Op-Code for WSC/Start")
8962
8963 logger.debug("Send M1 to AP")
8964 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8965 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8966 send_wsc_msg(hapd, addr, m1)
8967
8968 wps_wait_ap_nack(hapd, dev[0], 16*'\x00', 16*'\x00')
8969
8970def wps_ext_wsc_done(dev, apdev):
8971 pin = "12345670"
8972 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8973 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8974 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8975
8976 logger.debug("Receive WSC/Start from AP")
8977 msg = get_wsc_msg(hapd)
8978 if msg['wsc_opcode'] != WSC_Start:
8979 raise Exception("Unexpected Op-Code for WSC/Start")
8980
8981 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8982 uuid_e = 16*'\x11'
8983 e_nonce = 16*'\x22'
8984 own_private, e_pk = wsc_dh_init()
8985
8986 logger.debug("Send M1 to AP")
8987 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8988 e_nonce, e_pk)
8989 send_wsc_msg(hapd, addr, m1)
8990
8991 logger.debug("Receive M2 from AP")
8992 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8993 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8994 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8995
8996 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8997 r_nonce)
8998 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8999
9000 logger.debug("Send M3 to AP")
9001 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9002 attrs += build_attr_msg_type(WPS_M3)
9003 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9004 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9005 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9006 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9007 raw_m3_attrs = attrs
9008 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9009 send_wsc_msg(hapd, addr, m3)
9010
9011 logger.debug("Receive M4 from AP")
9012 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9013
9014 logger.debug("Send M5 to AP")
9015 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9016 attrs += build_attr_msg_type(WPS_M5)
9017 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9018 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9019 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9020 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9021 raw_m5_attrs = attrs
9022 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9023 send_wsc_msg(hapd, addr, m5)
9024
9025 logger.debug("Receive M6 from AP")
9026 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9027
9028 logger.debug("Send M7 to AP")
9029 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9030 attrs += build_attr_msg_type(WPS_M7)
9031 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9032 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9033 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9034 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9035 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9036 raw_m7_attrs = attrs
9037 send_wsc_msg(hapd, addr, m7)
9038
9039 logger.debug("Receive M8 from AP")
9040 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9041 return hapd, msg, e_nonce, r_nonce
9042
9fd6804d 9043@remote_compatible
7511ead0
JM
9044def test_wps_ext_wsc_done_invalid(dev, apdev):
9045 """WPS proto: invalid WSC_Done"""
9046 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9047
9048 logger.debug("Send WSC_Done to AP")
9049 attrs = '\x10\x00\x00'
9050 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9051 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9052
9053 wps_wait_eap_failure(hapd, dev[0])
9054
9fd6804d 9055@remote_compatible
7511ead0
JM
9056def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9057 """WPS proto: invalid WSC_Done"""
9058 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9059
9060 logger.debug("Send WSC_Done to AP")
9061 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9062 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9063 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9064 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9065 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9066 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9067
9068 wps_wait_eap_failure(hapd, dev[0])
9069
9fd6804d 9070@remote_compatible
7511ead0
JM
9071def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9072 """WPS proto: WSC_Done with wrong Msg Type"""
9073 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9074
9075 logger.debug("Send WSC_Done to AP")
9076 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9077 attrs += build_attr_msg_type(WPS_WSC_ACK)
9078 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9079 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9080 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9081 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9082
9083 wps_wait_eap_failure(hapd, dev[0])
9084
9fd6804d 9085@remote_compatible
7511ead0
JM
9086def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9087 """WPS proto: WSC_Done without e_nonce"""
9088 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9089
9090 logger.debug("Send WSC_Done to AP")
9091 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9092 attrs += build_attr_msg_type(WPS_WSC_DONE)
9093 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9094 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9095 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9096 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9097
9098 wps_wait_eap_failure(hapd, dev[0])
9099
9100def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9101 """WPS proto: WSC_Done without r_nonce"""
9102 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9103
9104 logger.debug("Send WSC_Done to AP")
9105 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9106 attrs += build_attr_msg_type(WPS_WSC_DONE)
9107 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9108 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9109 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9110 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9111
9112 wps_wait_eap_failure(hapd, dev[0])
9113
9fd6804d 9114@remote_compatible
7511ead0
JM
9115def test_wps_ext_m7_no_encr_settings(dev, apdev):
9116 """WPS proto: M7 without Encr Settings"""
9117 pin = "12345670"
9118 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9119 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9120 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9121
9122 logger.debug("Receive WSC/Start from AP")
9123 msg = get_wsc_msg(hapd)
9124 if msg['wsc_opcode'] != WSC_Start:
9125 raise Exception("Unexpected Op-Code for WSC/Start")
9126
9127 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9128 uuid_e = 16*'\x11'
9129 e_nonce = 16*'\x22'
9130 own_private, e_pk = wsc_dh_init()
9131
9132 logger.debug("Send M1 to AP")
9133 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9134 e_nonce, e_pk)
9135 send_wsc_msg(hapd, addr, m1)
9136
9137 logger.debug("Receive M2 from AP")
9138 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9139 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9140 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9141
9142 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9143 r_nonce)
9144 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9145
9146 logger.debug("Send M3 to AP")
9147 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9148 attrs += build_attr_msg_type(WPS_M3)
9149 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9150 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9151 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9152 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9153 raw_m3_attrs = attrs
9154 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9155 send_wsc_msg(hapd, addr, m3)
9156
9157 logger.debug("Receive M4 from AP")
9158 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9159
9160 logger.debug("Send M5 to AP")
9161 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9162 attrs += build_attr_msg_type(WPS_M5)
9163 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9164 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9165 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9166 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9167 raw_m5_attrs = attrs
9168 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9169 send_wsc_msg(hapd, addr, m5)
9170
9171 logger.debug("Receive M6 from AP")
9172 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9173
9174 logger.debug("Send M7 to AP")
9175 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9176 attrs += build_attr_msg_type(WPS_M7)
9177 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9178 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9179 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9180 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9181 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9182 raw_m7_attrs = attrs
9183 send_wsc_msg(hapd, addr, m7)
9184
9185 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9186
9fd6804d 9187@remote_compatible
7511ead0
JM
9188def test_wps_ext_m1_workaround(dev, apdev):
9189 """WPS proto: M1 Manufacturer/Model workaround"""
9190 pin = "12345670"
9191 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9192 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9193 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9194
9195 logger.debug("Receive WSC/Start from AP")
9196 msg = get_wsc_msg(hapd)
9197 if msg['wsc_opcode'] != WSC_Start:
9198 raise Exception("Unexpected Op-Code for WSC/Start")
9199
9200 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9201 uuid_e = 16*'\x11'
9202 e_nonce = 16*'\x22'
9203 own_private, e_pk = wsc_dh_init()
9204
9205 logger.debug("Send M1 to AP")
9206 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9207 e_nonce, e_pk, manufacturer='Apple TEST',
9208 model_name='AirPort', config_methods='\xff\xff')
9209 send_wsc_msg(hapd, addr, m1)
9210
9211 logger.debug("Receive M2 from AP")
9212 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
53bd8653 9213
9fd6804d 9214@remote_compatible
53bd8653
JM
9215def test_ap_wps_disable_enable(dev, apdev):
9216 """WPS and DISABLE/ENABLE AP"""
9217 hapd = wps_start_ap(apdev[0])
9218 hapd.disable()
9219 hapd.enable()
9220 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
dd124ee8
JM
9221
9222def test_ap_wps_upnp_web_oom(dev, apdev, params):
9223 """hostapd WPS UPnP web OOM"""
9224 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 9225 hapd = add_ssdp_ap(apdev[0], ap_uuid)
dd124ee8
JM
9226
9227 location = ssdp_get_location(ap_uuid)
9228 url = urlparse.urlparse(location)
9229 urls = upnp_get_urls(location)
9230 eventurl = urlparse.urlparse(urls['event_sub_url'])
9231 ctrlurl = urlparse.urlparse(urls['control_url'])
9232
9233 conn = httplib.HTTPConnection(url.netloc)
9234 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9235 conn.request("GET", "/wps_device.xml")
9236 try:
9237 resp = conn.getresponse()
9238 except:
9239 pass
9240
9241 conn = httplib.HTTPConnection(url.netloc)
9242 conn.request("GET", "/unknown")
9243 resp = conn.getresponse()
9244 if resp.status != 404:
9245 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9246
9247 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9248 conn.request("GET", "/unknown")
9249 try:
9250 resp = conn.getresponse()
9251 print resp.status
9252 except:
9253 pass
9254
9255 conn = httplib.HTTPConnection(url.netloc)
9256 conn.request("GET", "/wps_device.xml")
9257 resp = conn.getresponse()
9258 if resp.status != 200:
9259 raise Exception("GET /wps_device.xml failed")
9260
9261 conn = httplib.HTTPConnection(url.netloc)
9262 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9263 if resp.status != 200:
9264 raise Exception("GetDeviceInfo failed")
9265
9266 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9267 conn = httplib.HTTPConnection(url.netloc)
9268 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9269 if resp.status != 500:
9270 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9271
9272 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9273 conn = httplib.HTTPConnection(url.netloc)
9274 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9275 if resp.status != 500:
9276 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9277
9278 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9279 conn = httplib.HTTPConnection(url.netloc)
9280 try:
9281 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9282 except:
9283 pass
9284
9285 conn = httplib.HTTPConnection(url.netloc)
9286 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9287 if resp.status != 200:
9288 raise Exception("GetDeviceInfo failed")
9289
9290 # No NewWLANEventType in PutWLANResponse NewMessage
9291 conn = httplib.HTTPConnection(url.netloc)
9292 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9293 if resp.status != 600:
9294 raise Exception("Unexpected HTTP response: %d" % resp.status)
9295
9296 # No NewWLANEventMAC in PutWLANResponse NewMessage
9297 conn = httplib.HTTPConnection(url.netloc)
9298 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9299 newmsg="foo", neweventtype="1")
9300 if resp.status != 600:
9301 raise Exception("Unexpected HTTP response: %d" % resp.status)
9302
9303 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9304 conn = httplib.HTTPConnection(url.netloc)
9305 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9306 newmsg="foo", neweventtype="1",
9307 neweventmac="foo")
9308 if resp.status != 600:
9309 raise Exception("Unexpected HTTP response: %d" % resp.status)
9310
9311 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9312 # Ignored unexpected PutWLANResponse WLANEventType 1
9313 conn = httplib.HTTPConnection(url.netloc)
9314 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9315 newmsg="foo", neweventtype="1",
9316 neweventmac="00.11.22.33.44.55")
9317 if resp.status != 500:
9318 raise Exception("Unexpected HTTP response: %d" % resp.status)
9319
9320 # PutWLANResponse NewMessage with invalid EAP message
9321 conn = httplib.HTTPConnection(url.netloc)
9322 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9323 newmsg="foo", neweventtype="2",
9324 neweventmac="00:11:22:33:44:55")
9325 if resp.status != 200:
9326 raise Exception("Unexpected HTTP response: %d" % resp.status)
9327
9328 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9329 conn = httplib.HTTPConnection(url.netloc)
9330 headers = { "callback": '<http://127.0.0.1:12345/event>',
9331 "NT": "upnp:event",
9332 "timeout": "Second-1234" }
9333 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9334 try:
9335 resp = conn.getresponse()
9336 except:
9337 pass
9338
9339 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9340 conn = httplib.HTTPConnection(url.netloc)
9341 headers = { "callback": '<http://127.0.0.1:12345/event>',
9342 "NT": "upnp:event",
9343 "timeout": "Second-1234" }
9344 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9345 resp = conn.getresponse()
9346 if resp.status != 500:
9347 raise Exception("Unexpected HTTP response: %d" % resp.status)
9348
9349 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9350 conn = httplib.HTTPConnection(url.netloc)
9351 headers = { "callback": '<http://127.0.0.1:12345/event>',
9352 "NT": "upnp:event",
9353 "timeout": "Second-1234" }
9354 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9355 try:
9356 resp = conn.getresponse()
9357 except:
9358 pass
9359
9360 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9361 conn = httplib.HTTPConnection(url.netloc)
9362 conn.request("HEAD", "/wps_device.xml")
9363 try:
9364 resp = conn.getresponse()
9365 except:
9366 pass
d1341917
JM
9367
9368def test_ap_wps_frag_ack_oom(dev, apdev):
9369 """WPS and fragment ack OOM"""
9370 dev[0].request("SET wps_fragment_size 50")
9371 hapd = wps_start_ap(apdev[0])
9372 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9373 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
1e35aa15
JM
9374
9375def wait_scan_stopped(dev):
9376 dev.request("ABORT_SCAN")
9377 for i in range(50):
9378 res = dev.get_driver_status_field("scan_state")
9379 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9380 break
9381 logger.debug("Waiting for scan to complete")
9382 time.sleep(0.1)
9383
9fd6804d 9384@remote_compatible
1e35aa15
JM
9385def test_ap_wps_eap_wsc_errors(dev, apdev):
9386 """WPS and EAP-WSC error cases"""
9387 ssid = "test-wps-conf-pin"
9388 appin = "12345670"
9389 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9390 "wpa_passphrase": "12345678", "wpa": "2",
9391 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9392 "fragment_size": "300", "ap_pin": appin }
8b8a1864 9393 hapd = hostapd.add_ap(apdev[0], params)
1e35aa15
JM
9394 bssid = apdev[0]['bssid']
9395
9396 pin = dev[0].wps_read_pin()
9397 hapd.request("WPS_PIN any " + pin)
9398 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9399 dev[0].dump_monitor()
9400
9401 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9402 "new passphrase", no_wait=True)
9403 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9404 if ev is None:
9405 raise Exception("WPS-FAIL not reported")
9406 dev[0].request("WPS_CANCEL")
9407 dev[0].wait_disconnected()
9408 wait_scan_stopped(dev[0])
9409 dev[0].dump_monitor()
9410
9411 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9412 "new passphrase", no_wait=True)
9413 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9414 if ev is None:
9415 raise Exception("WPS-FAIL not reported")
9416 dev[0].request("WPS_CANCEL")
9417 dev[0].wait_disconnected()
9418 wait_scan_stopped(dev[0])
9419 dev[0].dump_monitor()
9420
9421 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9422 "new passphrase", no_wait=True)
9423 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9424 if ev is None:
9425 raise Exception("WPS-FAIL not reported")
9426 dev[0].request("WPS_CANCEL")
9427 dev[0].wait_disconnected()
9428 wait_scan_stopped(dev[0])
9429 dev[0].dump_monitor()
9430
9431 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9432 "new passphrase", no_wait=True)
9433 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9434 if ev is None:
9435 raise Exception("WPS-FAIL not reported")
9436 dev[0].request("WPS_CANCEL")
9437 dev[0].wait_disconnected()
9438 wait_scan_stopped(dev[0])
9439 dev[0].dump_monitor()
9440
9441 tests = [ "eap_wsc_init",
9442 "eap_msg_alloc;eap_wsc_build_msg",
9443 "wpabuf_alloc;eap_wsc_process_fragment" ]
9444 for func in tests:
9445 with alloc_fail(dev[0], 1, func):
9446 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9447 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9448 dev[0].request("WPS_CANCEL")
9449 dev[0].wait_disconnected()
9450 wait_scan_stopped(dev[0])
9451 dev[0].dump_monitor()
d8e5a55f 9452
bd3948c0
JM
9453 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9454 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9455 "CCMP", "new passphrase", no_wait=True)
9456 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9457 dev[0].request("WPS_CANCEL")
9458 dev[0].wait_disconnected()
9459 wait_scan_stopped(dev[0])
9460 dev[0].dump_monitor()
9461
d8e5a55f
JM
9462def test_ap_wps_eap_wsc(dev, apdev):
9463 """WPS and EAP-WSC in network profile"""
9464 params = int_eap_server_params()
9465 params["wps_state"] = "2"
8b8a1864 9466 hapd = hostapd.add_ap(apdev[0], params)
d8e5a55f
JM
9467 bssid = apdev[0]['bssid']
9468
9469 logger.info("Unexpected identity")
9470 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9471 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9472 wait_connect=False)
9473 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9474 if ev is None:
9475 raise Exception("No EAP-Failure seen")
9476 dev[0].request("REMOVE_NETWORK all")
9477 dev[0].wait_disconnected()
9478
9479 logger.info("No phase1 parameter")
9480 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9481 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9482 wait_connect=False)
9483 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9484 if ev is None:
9485 raise Exception("Timeout on EAP method start")
9486 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9487 if ev is None:
9488 raise Exception("No EAP-Failure seen")
9489 dev[0].request("REMOVE_NETWORK all")
9490 dev[0].wait_disconnected()
9491
9492 logger.info("No PIN/PBC in phase1")
9493 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9494 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9495 phase1="foo", wait_connect=False)
9496 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9497 if ev is None:
9498 raise Exception("Timeout on EAP method start")
9499 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9500 if ev is None:
9501 raise Exception("No EAP-Failure seen")
9502 dev[0].request("REMOVE_NETWORK all")
9503 dev[0].wait_disconnected()
9504
9505 logger.info("Invalid pkhash in phase1")
9506 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9507 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9508 phase1="foo pkhash=q pbc=1", wait_connect=False)
9509 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9510 if ev is None:
9511 raise Exception("Timeout on EAP method start")
9512 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9513 if ev is None:
9514 raise Exception("No EAP-Failure seen")
9515 dev[0].request("REMOVE_NETWORK all")
9516 dev[0].wait_disconnected()
9517
9518 logger.info("Zero fragment_size")
9519 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9520 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9521 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9522 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9523 if ev is None:
9524 raise Exception("Timeout on EAP method start")
9525 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9526 if ev is None:
9527 raise Exception("No M2D seen")
9528 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9529 if ev is None:
9530 raise Exception("No EAP-Failure seen")
9531 dev[0].request("REMOVE_NETWORK all")
9532 dev[0].wait_disconnected()
9533
9534 logger.info("Missing new_auth")
9535 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9536 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9537 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9538 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9539 if ev is None:
9540 raise Exception("Timeout on EAP method start")
9541 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9542 if ev is None:
9543 raise Exception("No EAP-Failure seen")
9544 dev[0].request("REMOVE_NETWORK all")
9545 dev[0].wait_disconnected()
9546
9547 logger.info("Missing new_encr")
9548 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9549 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9550 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9551 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9552 if ev is None:
9553 raise Exception("Timeout on EAP method start")
9554 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9555 if ev is None:
9556 raise Exception("No EAP-Failure seen")
9557 dev[0].request("REMOVE_NETWORK all")
9558 dev[0].wait_disconnected()
9559
9560 logger.info("Missing new_key")
9561 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9562 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9563 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9564 wait_connect=False)
9565 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9566 if ev is None:
9567 raise Exception("Timeout on EAP method start")
9568 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9569 if ev is None:
9570 raise Exception("No EAP-Failure seen")
9571 dev[0].request("REMOVE_NETWORK all")
9572 dev[0].wait_disconnected()
4425b1ed
JM
9573
9574def test_ap_wps_and_bss_limit(dev, apdev):
9575 """WPS and wpa_supplicant BSS entry limit"""
9576 try:
9577 _test_ap_wps_and_bss_limit(dev, apdev)
9578 finally:
9579 dev[0].request("SET bss_max_count 200")
9580 pass
9581
9582def _test_ap_wps_and_bss_limit(dev, apdev):
9583 params = { "ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9584 "wpa_passphrase": "12345678", "wpa": "2",
9585 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
9586 hapd = hostapd.add_ap(apdev[0], params)
9587
9588 params = { "ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9589 "wpa_passphrase": "1234567890", "wpa": "2",
9590 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
9591 hapd2 = hostapd.add_ap(apdev[1], params)
9592
9593 id = dev[1].add_network()
9594 dev[1].set_network(id, "mode", "2")
9595 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9596 dev[1].set_network_quoted(id, "psk", "12345678")
9597 dev[1].set_network(id, "frequency", "2462")
9598 dev[1].set_network(id, "scan_freq", "2462")
9599 dev[1].set_network(id, "wps_disabled", "1")
9600 dev[1].select_network(id)
9601
9602 id = dev[2].add_network()
9603 dev[2].set_network(id, "mode", "2")
9604 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9605 dev[2].set_network_quoted(id, "psk", "12345678")
9606 dev[2].set_network(id, "frequency", "2437")
9607 dev[2].set_network(id, "scan_freq", "2437")
9608 dev[2].select_network(id)
9609
9610 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9611 wpas.interface_add("wlan5")
9612 id = wpas.add_network()
9613 wpas.set_network(id, "mode", "2")
9614 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9615 wpas.set_network_quoted(id, "psk", "12345678")
9616 wpas.set_network(id, "frequency", "2437")
9617 wpas.set_network(id, "scan_freq", "2437")
9618 wpas.select_network(id)
9619
9620 dev[1].wait_connected()
9621 dev[2].wait_connected()
9622 wpas.wait_connected()
9623 wpas.request("WPS_PIN any 12345670")
9624
9625 hapd.request("WPS_PBC")
9626 hapd2.request("WPS_PBC")
9627
9628 dev[0].request("SET bss_max_count 1")
9629
9630 id = dev[0].add_network()
9631 dev[0].set_network_quoted(id, "ssid", "testing")
9632
9633 id = dev[0].add_network()
9634 dev[0].set_network_quoted(id, "ssid", "testing")
9635 dev[0].set_network(id, "key_mgmt", "WPS")
9636
9637 dev[0].request("WPS_PBC")
9638 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9639 dev[0].request("WPS_CANCEL")
9640
9641 id = dev[0].add_network()
9642 dev[0].set_network_quoted(id, "ssid", "testing")
9643 dev[0].set_network(id, "key_mgmt", "WPS")
9644
9645 dev[0].scan(freq="2412")
74b23faf
JM
9646
9647def test_ap_wps_pbc_2ap(dev, apdev):
9648 """WPS PBC with two APs advertising same SSID"""
9649 params = { "ssid": "wps", "eap_server": "1", "wps_state": "2",
9650 "wpa_passphrase": "12345678", "wpa": "2",
9651 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9652 "wps_independent": "1"}
9653 hapd = hostapd.add_ap(apdev[0], params)
9654 params = { "ssid": "wps", "eap_server": "1", "wps_state": "2",
9655 "wpa_passphrase": "123456789", "wpa": "2",
9656 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9657 "wps_independent": "1"}
9658 hapd2 = hostapd.add_ap(apdev[1], params)
9659 hapd.request("WPS_PBC")
9660
9661 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9662 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9663 wpas.dump_monitor()
9664
9665 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9666 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9667 wpas.request("WPS_PBC")
9668 wpas.wait_connected()
9669 wpas.request("DISCONNECT")
9670 hapd.request("DISABLE")
9671 hapd2.request("DISABLE")
9672 wpas.flush_scan_cache()
aed9e23a
JM
9673
9674def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9675 """WPS ER enrolling a new device to a configured AP"""
9676 try:
9677 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9678 finally:
9679 dev[0].request("WPS_ER_STOP")
9680
9681def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9682 ssid = "wps-er-enrollee-to-conf-ap"
9683 ap_pin = "12345670"
9684 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9685 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9686 "wpa_passphrase": "12345678", "wpa": "2",
9687 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9688 "device_name": "Wireless AP", "manufacturer": "Company",
9689 "model_name": "WAP", "model_number": "123",
9690 "serial_number": "12345", "device_type": "6-0050F204-1",
9691 "os_version": "01020300",
9692 "config_methods": "label push_button",
9693 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9694 hapd = hostapd.add_ap(apdev[0], params)
9695 bssid = hapd.own_addr()
9696
9697 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9698 dev[0].dump_monitor()
9699
9700 dev[0].request("WPS_ER_START ifname=lo")
9701 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9702 if ev is None:
9703 raise Exception("AP discovery timed out")
9704 if ap_uuid not in ev:
9705 raise Exception("Expected AP UUID not found")
9706
9707 pin = dev[2].wps_read_pin()
9708 addr2 = dev[2].own_addr()
9709 dev[0].dump_monitor()
9710 dev[2].scan_for_bss(bssid, freq=2412)
9711 dev[2].dump_monitor()
9712 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9713
9714 for i in range(3):
9715 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9716 if ev is None:
9717 raise Exception("Enrollee not seen")
9718 if addr2 in ev:
9719 break
9720 if addr2 not in ev:
9721 raise Exception("Unexpected Enrollee MAC address")
9722 dev[0].dump_monitor()
9723
9724 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9725 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9726 dev[2].wait_connected(timeout=30)
9727 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9728 if ev is None:
9729 raise Exception("WPS ER did not report success")
9730
9731def test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9732 """WPS ER enrolling a new device to a configured AP (2)"""
9733 try:
9734 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9735 finally:
9736 dev[0].request("WPS_ER_STOP")
9737
9738def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9739 ssid = "wps-er-enrollee-to-conf-ap"
9740 ap_pin = "12345670"
9741 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9742 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9743 "wpa_passphrase": "12345678", "wpa": "2",
9744 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9745 "device_name": "Wireless AP", "manufacturer": "Company",
9746 "model_name": "WAP", "model_number": "123",
9747 "serial_number": "12345", "device_type": "6-0050F204-1",
9748 "os_version": "01020300",
9749 "config_methods": "label push_button",
9750 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9751 hapd = hostapd.add_ap(apdev[0], params)
9752 bssid = hapd.own_addr()
9753
9754 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9755 dev[0].dump_monitor()
9756
9757 dev[0].request("WPS_ER_START ifname=lo")
9758 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9759 if ev is None:
9760 raise Exception("AP discovery timed out")
9761 if ap_uuid not in ev:
9762 raise Exception("Expected AP UUID not found")
9763
9764 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
9765 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
9766 if ev is None:
9767 raise Exception("AP learn timed out")
9768 if ap_uuid not in ev:
9769 raise Exception("Expected AP UUID not in settings")
9770 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
9771 if ev is None:
9772 raise Exception("WPS-FAIL after AP learn timed out")
9773 time.sleep(0.1)
9774
9775 pin = dev[1].wps_read_pin()
9776 addr1 = dev[1].own_addr()
9777 dev[0].dump_monitor()
9778 dev[0].request("WPS_ER_PIN any " + pin)
9779 time.sleep(0.1)
9780 dev[1].scan_for_bss(bssid, freq=2412)
9781 dev[1].request("WPS_PIN any %s" % pin)
9782 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
9783 if ev is None:
9784 raise Exception("Enrollee did not report success")
9785 dev[1].wait_connected(timeout=15)
9786 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9787 if ev is None:
9788 raise Exception("WPS ER did not report success")
5026406d
JM
9789
9790def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
9791 """WPS AP trying to ignore broadcast SSID"""
9792 ssid = "test-wps"
9793 hapd = hostapd.add_ap(apdev[0],
9794 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9795 "ignore_broadcast_ssid": "1" })
9796 if "FAIL" not in hapd.request("WPS_PBC"):
9797 raise Exception("WPS unexpectedly enabled")
9798
9799def test_ap_wps_wep(dev, apdev):
9800 """WPS AP trying to enable WEP"""
9801 ssid = "test-wps"
9802 hapd = hostapd.add_ap(apdev[0],
9803 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9804 "ieee80211n": "0", "wep_key0": '"hello"' })
9805 if "FAIL" not in hapd.request("WPS_PBC"):
9806 raise Exception("WPS unexpectedly enabled")
9807
9808def test_ap_wps_tkip(dev, apdev):
9809 """WPS AP trying to enable TKIP"""
9810 ssid = "test-wps"
9811 hapd = hostapd.add_ap(apdev[0],
9812 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9813 "ieee80211n": "0", "wpa": '1',
9814 "wpa_key_mgmt": "WPA-PSK",
9815 "wpa_passphrase": "12345678" })
9816 if "FAIL" not in hapd.request("WPS_PBC"):
9817 raise Exception("WPS unexpectedly enabled")
454b66d2
JM
9818
9819def test_ap_wps_conf_dummy_cred(dev, apdev):
9820 """WPS PIN provisioning with configured AP using dummy cred"""
9821 ssid = "test-wps-conf"
9822 hapd = hostapd.add_ap(apdev[0],
9823 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9824 "wpa_passphrase": "12345678", "wpa": "2",
9825 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9826 hapd.request("WPS_PIN any 12345670")
9827 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9828 dev[0].dump_monitor()
9829 try:
9830 hapd.set("wps_testing_dummy_cred", "1")
9831 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
9832 for i in range(1, 3):
9833 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
9834 if ev is None:
9835 raise Exception("WPS credential %d not received" % i)
9836 dev[0].wait_connected(timeout=30)
9837 finally:
9838 hapd.set("wps_testing_dummy_cred", "0")
cde2143c
JM
9839
9840def test_ap_wps_rf_bands(dev, apdev):
9841 """WPS and wps_rf_bands configuration"""
9842 ssid = "test-wps-conf"
9843 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9844 "wpa_passphrase": "12345678", "wpa": "2",
9845 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9846 "wps_rf_bands": "ag" }
9847
9848 hapd = hostapd.add_ap(apdev[0], params)
9849 bssid = hapd.own_addr()
9850 hapd.request("WPS_PBC")
9851 dev[0].scan_for_bss(bssid, freq="2412")
9852 dev[0].dump_monitor()
9853 dev[0].request("WPS_PBC " + bssid)
9854 dev[0].wait_connected(timeout=30)
9855 bss = dev[0].get_bss(bssid)
9856 logger.info("BSS: " + str(bss))
9857 if "103c000103" not in bss['ie']:
9858 raise Exception("RF Bands attribute with expected values not found")
9859 dev[0].request("DISCONNECT")
9860 dev[0].wait_disconnected()
9861 hapd.set("wps_rf_bands", "ad")
9862 hapd.set("wps_rf_bands", "a")
9863 hapd.set("wps_rf_bands", "g")
9864 hapd.set("wps_rf_bands", "b")
9865 hapd.set("wps_rf_bands", "ga")
9866 hapd.disable()
9867 dev[0].dump_monitor()
9868 dev[0].flush_scan_cache()
93b85d44
JM
9869
9870def test_ap_wps_pbc_in_m1(dev, apdev):
9871 """WPS and pbc_in_m1"""
9872 ssid = "test-wps-conf"
9873 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9874 "wpa_passphrase": "12345678", "wpa": "2",
9875 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9876 "config_methods": "virtual_push_button virtual_display",
9877 "pbc_in_m1": "1" }
9878
9879 hapd = hostapd.add_ap(apdev[0], params)
9880 bssid = hapd.own_addr()
9881 hapd.request("WPS_PBC")
9882 dev[0].scan_for_bss(bssid, freq="2412")
9883 dev[0].dump_monitor()
9884 dev[0].request("WPS_PBC " + bssid)
9885 dev[0].wait_connected(timeout=30)
9886 dev[0].request("DISCONNECT")
9887 dev[0].wait_disconnected()
9888 hapd.disable()
9889 dev[0].dump_monitor()
9890 dev[0].flush_scan_cache()