]> git.ipfire.org Git - thirdparty/hostap.git/blame - tests/hwsim/test_ap_wps.py
tests: hostapd with zero length ap_pin parameter
[thirdparty/hostap.git] / tests / hwsim / test_ap_wps.py
CommitLineData
302b7a1b 1# WPS tests
3381d324 2# Copyright (c) 2013-2017, 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
d33222d1
JM
557def test_ap_wps_reg_connect_zero_len_ap_pin(dev, apdev):
558 """hostapd with zero length ap_pin parameter"""
559 ssid = "test-wps-reg-ap-pin"
560 appin = ""
561 hostapd.add_ap(apdev[0],
562 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
563 "wpa_passphrase": "12345678", "wpa": "2",
564 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
565 "ap_pin": appin})
566 logger.info("WPS provisioning step")
567 dev[0].dump_monitor()
568 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
569 dev[0].wps_reg(apdev[0]['bssid'], appin, no_wait=True)
570 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
571 if ev is None:
572 raise Exception("No WPS-FAIL reported")
573 if "msg=5 config_error=15" not in ev:
574 raise Exception("Unexpected WPS-FAIL: " + ev)
575
e60be3b3
JM
576def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
577 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
578 ssid = "test-wps-reg-ap-pin"
579 appin = "12345670"
8b8a1864 580 hostapd.add_ap(apdev[0],
e60be3b3
JM
581 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
582 "wpa_passphrase": "12345678", "wpa": "3",
583 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
584 "wpa_pairwise": "TKIP", "ap_pin": appin})
585 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
586 dev[0].wps_reg(apdev[0]['bssid'], appin)
587 status = dev[0].get_status()
588 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
589 raise Exception("Not fully connected")
590 if status['ssid'] != ssid:
591 raise Exception("Unexpected SSID")
592 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
593 raise Exception("Unexpected encryption configuration")
594 if status['key_mgmt'] != 'WPA2-PSK':
595 raise Exception("Unexpected key_mgmt")
596
7511ead0
JM
597def test_ap_wps_reg_override_ap_settings(dev, apdev):
598 """WPS registrar and ap_settings override"""
599 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
600 try:
601 os.remove(ap_settings)
602 except:
603 pass
604 # Override AP Settings with values that point to another AP
605 data = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
606 data += build_wsc_attr(ATTR_SSID, "test")
607 data += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
608 data += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
609 data += build_wsc_attr(ATTR_NETWORK_KEY, '')
610 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
611 with open(ap_settings, "w") as f:
612 f.write(data)
613 ssid = "test-wps-reg-ap-pin"
614 appin = "12345670"
8b8a1864 615 hostapd.add_ap(apdev[0],
7511ead0
JM
616 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
617 "wpa_passphrase": "12345678", "wpa": "2",
618 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
619 "ap_pin": appin, "ap_settings": ap_settings })
8b8a1864 620 hapd2 = hostapd.add_ap(apdev[1], { "ssid": "test" })
7511ead0
JM
621 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
622 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
623 dev[0].wps_reg(apdev[0]['bssid'], appin)
624 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
625 os.remove(ap_settings)
626 if ev is None:
627 raise Exception("No connection with the other AP")
628
9488858f
JM
629def check_wps_reg_failure(dev, ap, appin):
630 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
631 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
632 if ev is None:
633 raise Exception("WPS operation timed out")
634 if "WPS-SUCCESS" in ev:
635 raise Exception("WPS operation succeeded unexpectedly")
636 if "config_error=15" not in ev:
637 raise Exception("WPS setup locked state was not reported correctly")
638
e4357b19
JM
639def test_ap_wps_random_ap_pin(dev, apdev):
640 """WPS registrar using random AP PIN"""
641 ssid = "test-wps-reg-random-ap-pin"
642 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
6f334bf7
JD
643 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
644 "wpa_passphrase": "12345678", "wpa": "2",
645 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
646 "device_name": "Wireless AP", "manufacturer": "Company",
647 "model_name": "WAP", "model_number": "123",
648 "serial_number": "12345", "device_type": "6-0050F204-1",
649 "os_version": "01020300",
650 "config_methods": "label push_button",
651 "uuid": ap_uuid, "upnp_iface": "lo" }
652 hapd = hostapd.add_ap(apdev[0], params)
e4357b19
JM
653 appin = hapd.request("WPS_AP_PIN random")
654 if "FAIL" in appin:
655 raise Exception("Could not generate random AP PIN")
656 if appin not in hapd.request("WPS_AP_PIN get"):
657 raise Exception("Could not fetch current AP PIN")
658 logger.info("WPS provisioning step")
33d0b157 659 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
e4357b19
JM
660 dev[0].wps_reg(apdev[0]['bssid'], appin)
661
662 hapd.request("WPS_AP_PIN disable")
663 logger.info("WPS provisioning step with AP PIN disabled")
33d0b157 664 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9488858f
JM
665 check_wps_reg_failure(dev[1], apdev[0], appin)
666
667 logger.info("WPS provisioning step with AP PIN reset")
668 appin = "12345670"
669 hapd.request("WPS_AP_PIN set " + appin)
670 dev[1].wps_reg(apdev[0]['bssid'], appin)
671 dev[0].request("REMOVE_NETWORK all")
672 dev[1].request("REMOVE_NETWORK all")
5f35a5e2
JM
673 dev[0].wait_disconnected(timeout=10)
674 dev[1].wait_disconnected(timeout=10)
9488858f
JM
675
676 logger.info("WPS provisioning step after AP PIN timeout")
677 hapd.request("WPS_AP_PIN disable")
678 appin = hapd.request("WPS_AP_PIN random 1")
679 time.sleep(1.1)
680 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
681 raise Exception("AP PIN unexpectedly still enabled")
682 check_wps_reg_failure(dev[0], apdev[0], appin)
683
684 logger.info("WPS provisioning step after AP PIN timeout(2)")
685 hapd.request("WPS_AP_PIN disable")
686 appin = "12345670"
687 hapd.request("WPS_AP_PIN set " + appin + " 1")
688 time.sleep(1.1)
689 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
690 raise Exception("AP PIN unexpectedly still enabled")
691 check_wps_reg_failure(dev[1], apdev[0], appin)
e4357b19 692
24b7f282 693 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
20c48fd9 694 hapd.request("WPS_AP_PIN random 1")
24b7f282
JM
695 hapd.request("WPS_AP_PIN disable")
696
697 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
698 hapd.request("WPS_AP_PIN set 12345670")
699 hapd.request("WPS_AP_PIN disable")
700
82358a2a
JM
701 if "FAIL" not in hapd.request("WPS_AP_PIN set"):
702 raise Exception("Invalid WPS_AP_PIN accepted")
703 if "FAIL" not in hapd.request("WPS_AP_PIN foo"):
704 raise Exception("Invalid WPS_AP_PIN accepted")
705
ae3ad328 706def test_ap_wps_reg_config(dev, apdev):
4b727c5c 707 """WPS registrar configuring an AP using AP PIN"""
302b7a1b
JM
708 ssid = "test-wps-init-ap-pin"
709 appin = "12345670"
8b8a1864 710 hostapd.add_ap(apdev[0],
302b7a1b
JM
711 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
712 "ap_pin": appin})
713 logger.info("WPS configuration step")
33d0b157 714 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
302b7a1b
JM
715 dev[0].dump_monitor()
716 new_ssid = "wps-new-ssid"
717 new_passphrase = "1234567890"
6edaee9c
JM
718 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
719 new_passphrase)
302b7a1b 720 status = dev[0].get_status()
ae3ad328 721 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
302b7a1b
JM
722 raise Exception("Not fully connected")
723 if status['ssid'] != new_ssid:
724 raise Exception("Unexpected SSID")
725 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
726 raise Exception("Unexpected encryption configuration")
727 if status['key_mgmt'] != 'WPA2-PSK':
728 raise Exception("Unexpected key_mgmt")
729
375afd7c
JM
730 logger.info("Re-configure back to open")
731 dev[0].request("REMOVE_NETWORK all")
243dcc4a 732 dev[0].flush_scan_cache()
375afd7c
JM
733 dev[0].dump_monitor()
734 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
735 status = dev[0].get_status()
736 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
737 raise Exception("Not fully connected")
738 if status['ssid'] != "wps-open":
739 raise Exception("Unexpected SSID")
740 if status['key_mgmt'] != 'NONE':
741 raise Exception("Unexpected key_mgmt")
742
4b727c5c
JM
743def test_ap_wps_reg_config_ext_processing(dev, apdev):
744 """WPS registrar configuring an AP with external config processing"""
745 ssid = "test-wps-init-ap-pin"
746 appin = "12345670"
747 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
748 "wps_cred_processing": "1", "ap_pin": appin}
8b8a1864 749 hapd = hostapd.add_ap(apdev[0], params)
33d0b157 750 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
4b727c5c
JM
751 new_ssid = "wps-new-ssid"
752 new_passphrase = "1234567890"
753 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
754 new_passphrase, no_wait=True)
755 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
756 if ev is None:
757 raise Exception("WPS registrar operation timed out")
758 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
759 if ev is None:
760 raise Exception("WPS configuration timed out")
761 if "1026" not in ev:
762 raise Exception("AP Settings missing from event")
763 hapd.request("SET wps_cred_processing 0")
764 if "FAIL" in hapd.request("WPS_CONFIG " + new_ssid.encode("hex") + " WPA2PSK CCMP " + new_passphrase.encode("hex")):
765 raise Exception("WPS_CONFIG command failed")
5f35a5e2 766 dev[0].wait_connected(timeout=15)
4b727c5c 767
eeefe187
JM
768def test_ap_wps_reg_config_tkip(dev, apdev):
769 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
a1eabc74 770 skip_with_fips(dev[0])
eeefe187
JM
771 ssid = "test-wps-init-ap"
772 appin = "12345670"
8b8a1864 773 hostapd.add_ap(apdev[0],
eeefe187
JM
774 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
775 "ap_pin": appin})
776 logger.info("WPS configuration step")
eeefe187 777 dev[0].request("SET wps_version_number 0x10")
33d0b157 778 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
eeefe187
JM
779 dev[0].dump_monitor()
780 new_ssid = "wps-new-ssid-with-tkip"
781 new_passphrase = "1234567890"
782 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
783 new_passphrase)
784 logger.info("Re-connect to verify WPA2 mixed mode")
785 dev[0].request("DISCONNECT")
786 id = 0
787 dev[0].set_network(id, "pairwise", "CCMP")
788 dev[0].set_network(id, "proto", "RSN")
789 dev[0].connect_network(id)
790 status = dev[0].get_status()
791 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
3c086180 792 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
eeefe187
JM
793 if status['ssid'] != new_ssid:
794 raise Exception("Unexpected SSID")
795 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
796 raise Exception("Unexpected encryption configuration")
797 if status['key_mgmt'] != 'WPA2-PSK':
798 raise Exception("Unexpected key_mgmt")
799
6645ff50
JM
800def test_ap_wps_setup_locked(dev, apdev):
801 """WPS registrar locking up AP setup on AP PIN failures"""
802 ssid = "test-wps-incorrect-ap-pin"
803 appin = "12345670"
6f334bf7
JD
804 hapd = hostapd.add_ap(apdev[0],
805 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
806 "wpa_passphrase": "12345678", "wpa": "2",
807 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
808 "ap_pin": appin})
6645ff50
JM
809 new_ssid = "wps-new-ssid-test"
810 new_passphrase = "1234567890"
811
33d0b157 812 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6645ff50
JM
813 ap_setup_locked=False
814 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
815 dev[0].dump_monitor()
816 logger.info("Try incorrect AP PIN - attempt " + pin)
817 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
818 "CCMP", new_passphrase, no_wait=True)
819 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
820 if ev is None:
821 raise Exception("Timeout on receiving WPS operation failure event")
822 if "CTRL-EVENT-CONNECTED" in ev:
823 raise Exception("Unexpected connection")
824 if "config_error=15" in ev:
825 logger.info("AP Setup Locked")
826 ap_setup_locked=True
827 elif "config_error=18" not in ev:
828 raise Exception("config_error=18 not reported")
5f35a5e2 829 dev[0].wait_disconnected(timeout=10)
6645ff50
JM
830 time.sleep(0.1)
831 if not ap_setup_locked:
832 raise Exception("AP setup was not locked")
24b7f282
JM
833 dev[0].request("WPS_CANCEL")
834 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
835 only_new=True)
836 bss = dev[0].get_bss(apdev[0]['bssid'])
837 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
838 logger.info("BSS: " + str(bss))
839 raise Exception("AP Setup Locked not indicated in scan results")
6645ff50 840
d671a420
JM
841 status = hapd.request("WPS_GET_STATUS")
842 if "Last WPS result: Failed" not in status:
843 raise Exception("WPS failure result not shown correctly")
844 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
845 raise Exception("Peer address not shown correctly")
846
6645ff50
JM
847 time.sleep(0.5)
848 dev[0].dump_monitor()
849 logger.info("WPS provisioning step")
850 pin = dev[0].wps_read_pin()
6645ff50 851 hapd.request("WPS_PIN any " + pin)
33d0b157 852 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
6645ff50
JM
853 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
854 if ev is None:
855 raise Exception("WPS success was not reported")
5f35a5e2 856 dev[0].wait_connected(timeout=30)
6645ff50 857
c1cec68b
JM
858 appin = hapd.request("WPS_AP_PIN random")
859 if "FAIL" in appin:
860 raise Exception("Could not generate random AP PIN")
861 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
862 if ev is None:
863 raise Exception("Failed to unlock AP PIN")
864
33c9b8d8
JM
865def test_ap_wps_setup_locked_timeout(dev, apdev):
866 """WPS re-enabling AP PIN after timeout"""
867 ssid = "test-wps-incorrect-ap-pin"
868 appin = "12345670"
6f334bf7
JD
869 hapd = hostapd.add_ap(apdev[0],
870 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
871 "wpa_passphrase": "12345678", "wpa": "2",
872 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
873 "ap_pin": appin})
33c9b8d8
JM
874 new_ssid = "wps-new-ssid-test"
875 new_passphrase = "1234567890"
876
33d0b157 877 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
33c9b8d8
JM
878 ap_setup_locked=False
879 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
880 dev[0].dump_monitor()
881 logger.info("Try incorrect AP PIN - attempt " + pin)
882 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
883 "CCMP", new_passphrase, no_wait=True)
9ed53f5e 884 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
33c9b8d8
JM
885 if ev is None:
886 raise Exception("Timeout on receiving WPS operation failure event")
887 if "CTRL-EVENT-CONNECTED" in ev:
888 raise Exception("Unexpected connection")
889 if "config_error=15" in ev:
890 logger.info("AP Setup Locked")
891 ap_setup_locked=True
892 break
893 elif "config_error=18" not in ev:
894 raise Exception("config_error=18 not reported")
5f35a5e2 895 dev[0].wait_disconnected(timeout=10)
33c9b8d8
JM
896 time.sleep(0.1)
897 if not ap_setup_locked:
898 raise Exception("AP setup was not locked")
33c9b8d8
JM
899 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
900 if ev is None:
901 raise Exception("AP PIN did not get unlocked on 60 second timeout")
902
4c355e3e
JM
903def test_ap_wps_setup_locked_2(dev, apdev):
904 """WPS AP configured for special ap_setup_locked=2 mode"""
905 ssid = "test-wps-ap-pin"
906 appin = "12345670"
907 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
908 "wpa_passphrase": "12345678", "wpa": "2",
909 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
910 "ap_pin": appin, "ap_setup_locked": "2" }
8b8a1864 911 hapd = hostapd.add_ap(apdev[0], params)
4c355e3e
JM
912 new_ssid = "wps-new-ssid-test"
913 new_passphrase = "1234567890"
914
915 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
916 dev[0].wps_reg(apdev[0]['bssid'], appin)
917 dev[0].request("REMOVE_NETWORK all")
918 dev[0].wait_disconnected()
919
920 hapd.dump_monitor()
921 dev[0].dump_monitor()
922 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
923 "CCMP", new_passphrase, no_wait=True)
924
925 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
926 if ev is None:
927 raise Exception("hostapd did not report WPS failure")
928 if "msg=12 config_error=15" not in ev:
929 raise Exception("Unexpected failure reason (AP): " + ev)
930
931 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
932 if ev is None:
933 raise Exception("Timeout on receiving WPS operation failure event")
934 if "CTRL-EVENT-CONNECTED" in ev:
935 raise Exception("Unexpected connection")
936 if "config_error=15" not in ev:
937 raise Exception("Unexpected failure reason (STA): " + ev)
938 dev[0].request("WPS_CANCEL")
939 dev[0].wait_disconnected()
940
9fd6804d 941@remote_compatible
ae3ad328 942def test_ap_wps_pbc_overlap_2ap(dev, apdev):
302b7a1b 943 """WPS PBC session overlap with two active APs"""
6f334bf7
JD
944 params = { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
945 "wpa_passphrase": "12345678", "wpa": "2",
946 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
947 "wps_independent": "1"}
948 hapd = hostapd.add_ap(apdev[0], params)
949 params = { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
950 "wpa_passphrase": "123456789", "wpa": "2",
951 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
952 "wps_independent": "1"}
953 hapd2 = hostapd.add_ap(apdev[1], params)
302b7a1b 954 hapd.request("WPS_PBC")
302b7a1b
JM
955 hapd2.request("WPS_PBC")
956 logger.info("WPS provisioning step")
84a40841
JM
957 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
958 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
302b7a1b
JM
959 dev[0].request("WPS_PBC")
960 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
961 if ev is None:
962 raise Exception("PBC session overlap not detected")
492c3a91
JM
963 hapd.request("DISABLE")
964 hapd2.request("DISABLE")
965 dev[0].flush_scan_cache()
302b7a1b 966
9fd6804d 967@remote_compatible
ae3ad328 968def test_ap_wps_pbc_overlap_2sta(dev, apdev):
302b7a1b
JM
969 """WPS PBC session overlap with two active STAs"""
970 ssid = "test-wps-pbc-overlap"
6f334bf7
JD
971 hapd = hostapd.add_ap(apdev[0],
972 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
973 "wpa_passphrase": "12345678", "wpa": "2",
974 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
302b7a1b
JM
975 logger.info("WPS provisioning step")
976 hapd.request("WPS_PBC")
33d0b157 977 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 978 dev[0].dump_monitor()
33d0b157 979 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
302b7a1b 980 dev[1].dump_monitor()
33d0b157
JM
981 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
982 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
302b7a1b
JM
983 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
984 if ev is None:
985 raise Exception("PBC session overlap not detected (dev0)")
986 if "config_error=12" not in ev:
987 raise Exception("PBC session overlap not correctly reported (dev0)")
492c3a91
JM
988 dev[0].request("WPS_CANCEL")
989 dev[0].request("DISCONNECT")
302b7a1b
JM
990 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
991 if ev is None:
992 raise Exception("PBC session overlap not detected (dev1)")
993 if "config_error=12" not in ev:
994 raise Exception("PBC session overlap not correctly reported (dev1)")
492c3a91
JM
995 dev[1].request("WPS_CANCEL")
996 dev[1].request("DISCONNECT")
11e7eeba
JM
997 hapd.request("WPS_CANCEL")
998 ret = hapd.request("WPS_PBC")
999 if "FAIL" not in ret:
1000 raise Exception("PBC mode allowed to be started while PBC overlap still active")
492c3a91
JM
1001 hapd.request("DISABLE")
1002 dev[0].flush_scan_cache()
1003 dev[1].flush_scan_cache()
6edaee9c 1004
9fd6804d 1005@remote_compatible
71afe834
JM
1006def test_ap_wps_cancel(dev, apdev):
1007 """WPS AP cancelling enabled config method"""
1008 ssid = "test-wps-ap-cancel"
6f334bf7
JD
1009 hapd = hostapd.add_ap(apdev[0],
1010 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1011 "wpa_passphrase": "12345678", "wpa": "2",
1012 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
71afe834 1013 bssid = apdev[0]['bssid']
71afe834
JM
1014
1015 logger.info("Verify PBC enable/cancel")
1016 hapd.request("WPS_PBC")
71afe834 1017 dev[0].scan(freq="2412")
84a40841 1018 dev[0].scan(freq="2412")
71afe834
JM
1019 bss = dev[0].get_bss(apdev[0]['bssid'])
1020 if "[WPS-PBC]" not in bss['flags']:
1021 raise Exception("WPS-PBC flag missing")
1022 if "FAIL" in hapd.request("WPS_CANCEL"):
1023 raise Exception("WPS_CANCEL failed")
1024 dev[0].scan(freq="2412")
84a40841 1025 dev[0].scan(freq="2412")
71afe834
JM
1026 bss = dev[0].get_bss(apdev[0]['bssid'])
1027 if "[WPS-PBC]" in bss['flags']:
1028 raise Exception("WPS-PBC flag not cleared")
1029
1030 logger.info("Verify PIN enable/cancel")
1031 hapd.request("WPS_PIN any 12345670")
1032 dev[0].scan(freq="2412")
84a40841 1033 dev[0].scan(freq="2412")
71afe834
JM
1034 bss = dev[0].get_bss(apdev[0]['bssid'])
1035 if "[WPS-AUTH]" not in bss['flags']:
1036 raise Exception("WPS-AUTH flag missing")
1037 if "FAIL" in hapd.request("WPS_CANCEL"):
1038 raise Exception("WPS_CANCEL failed")
1039 dev[0].scan(freq="2412")
84a40841 1040 dev[0].scan(freq="2412")
71afe834
JM
1041 bss = dev[0].get_bss(apdev[0]['bssid'])
1042 if "[WPS-AUTH]" in bss['flags']:
1043 raise Exception("WPS-AUTH flag not cleared")
1044
6edaee9c
JM
1045def test_ap_wps_er_add_enrollee(dev, apdev):
1046 """WPS ER configuring AP and adding a new enrollee using PIN"""
be9f1562
JM
1047 try:
1048 _test_ap_wps_er_add_enrollee(dev, apdev)
1049 finally:
1050 dev[0].request("WPS_ER_STOP")
1051
1052def _test_ap_wps_er_add_enrollee(dev, apdev):
6edaee9c
JM
1053 ssid = "wps-er-add-enrollee"
1054 ap_pin = "12345670"
1055 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1056 hostapd.add_ap(apdev[0],
6edaee9c
JM
1057 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
1058 "device_name": "Wireless AP", "manufacturer": "Company",
1059 "model_name": "WAP", "model_number": "123",
1060 "serial_number": "12345", "device_type": "6-0050F204-1",
1061 "os_version": "01020300",
24b7f282 1062 'friendly_name': "WPS AP - <>&'\" - TEST",
6edaee9c
JM
1063 "config_methods": "label push_button",
1064 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1065 logger.info("WPS configuration step")
1066 new_passphrase = "1234567890"
1067 dev[0].dump_monitor()
33d0b157 1068 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c
JM
1069 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1070 new_passphrase)
1071 status = dev[0].get_status()
1072 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1073 raise Exception("Not fully connected")
1074 if status['ssid'] != ssid:
1075 raise Exception("Unexpected SSID")
1076 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1077 raise Exception("Unexpected encryption configuration")
1078 if status['key_mgmt'] != 'WPA2-PSK':
1079 raise Exception("Unexpected key_mgmt")
1080
1081 logger.info("Start ER")
1082 dev[0].request("WPS_ER_START ifname=lo")
1083 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1084 if ev is None:
1085 raise Exception("AP discovery timed out")
1086 if ap_uuid not in ev:
1087 raise Exception("Expected AP UUID not found")
24b7f282
JM
1088 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1089 raise Exception("Expected friendly name not found")
6edaee9c
JM
1090
1091 logger.info("Learn AP configuration through UPnP")
1092 dev[0].dump_monitor()
1093 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1094 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1095 if ev is None:
1096 raise Exception("AP learn timed out")
1097 if ap_uuid not in ev:
1098 raise Exception("Expected AP UUID not in settings")
1099 if "ssid=" + ssid not in ev:
1100 raise Exception("Expected SSID not in settings")
1101 if "key=" + new_passphrase not in ev:
1102 raise Exception("Expected passphrase not in settings")
33d0b157
JM
1103 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1104 if ev is None:
1105 raise Exception("WPS-FAIL after AP learn timed out")
1106 time.sleep(0.1)
6edaee9c
JM
1107
1108 logger.info("Add Enrollee using ER")
1109 pin = dev[1].wps_read_pin()
1110 dev[0].dump_monitor()
1111 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
33d0b157 1112 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1113 dev[1].dump_monitor()
33d0b157 1114 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
846be889 1115 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
6edaee9c
JM
1116 if ev is None:
1117 raise Exception("Enrollee did not report success")
5f35a5e2 1118 dev[1].wait_connected(timeout=15)
6edaee9c
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 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1123
11c26f1b
JM
1124 logger.info("Add a specific Enrollee using ER")
1125 pin = dev[2].wps_read_pin()
1126 addr2 = dev[2].p2p_interface_addr()
1127 dev[0].dump_monitor()
33d0b157 1128 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
11c26f1b 1129 dev[2].dump_monitor()
33d0b157 1130 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
11c26f1b
JM
1131 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1132 if ev is None:
1133 raise Exception("Enrollee not seen")
1134 if addr2 not in ev:
1135 raise Exception("Unexpected Enrollee MAC address")
1136 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
5f35a5e2 1137 dev[2].wait_connected(timeout=30)
11c26f1b
JM
1138 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1139 if ev is None:
1140 raise Exception("WPS ER did not report success")
1141
38ae43de
JM
1142 logger.info("Verify registrar selection behavior")
1143 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1144 dev[1].request("DISCONNECT")
5f35a5e2 1145 dev[1].wait_disconnected(timeout=10)
84a40841 1146 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
38ae43de
JM
1147 dev[1].scan(freq="2412")
1148 bss = dev[1].get_bss(apdev[0]['bssid'])
1149 if "[WPS-AUTH]" not in bss['flags']:
321c7f60
JM
1150 # It is possible for scan to miss an update especially when running
1151 # tests under load with multiple VMs, so allow another attempt.
1152 dev[1].scan(freq="2412")
1153 bss = dev[1].get_bss(apdev[0]['bssid'])
1154 if "[WPS-AUTH]" not in bss['flags']:
1155 raise Exception("WPS-AUTH flag missing")
38ae43de
JM
1156
1157 logger.info("Stop ER")
1158 dev[0].dump_monitor()
1159 dev[0].request("WPS_ER_STOP")
1160 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1161 if ev is None:
1162 raise Exception("WPS ER unsubscription timed out")
8697cbc0 1163 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
befd671c 1164 # a bit before verifying that the scan results have changed.
8697cbc0 1165 time.sleep(0.2)
38ae43de 1166
befd671c
JM
1167 for i in range(0, 10):
1168 dev[1].request("BSS_FLUSH 0")
1169 dev[1].scan(freq="2412", only_new=True)
1170 bss = dev[1].get_bss(apdev[0]['bssid'])
1171 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1172 break
1173 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1174 time.sleep(0.1)
38ae43de
JM
1175 if "[WPS-AUTH]" in bss['flags']:
1176 raise Exception("WPS-AUTH flag not removed")
1177
c965ae03
JM
1178def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1179 """WPS ER adding a new enrollee identified by UUID"""
1180 try:
1181 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1182 finally:
1183 dev[0].request("WPS_ER_STOP")
1184
1185def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1186 ssid = "wps-er-add-enrollee"
1187 ap_pin = "12345670"
1188 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1189 hostapd.add_ap(apdev[0],
c965ae03
JM
1190 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1191 "wpa_passphrase": "12345678", "wpa": "2",
1192 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1193 "device_name": "Wireless AP", "manufacturer": "Company",
1194 "model_name": "WAP", "model_number": "123",
1195 "serial_number": "12345", "device_type": "6-0050F204-1",
1196 "os_version": "01020300",
1197 "config_methods": "label push_button",
1198 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1199 logger.info("WPS configuration step")
1200 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1201 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1202
1203 logger.info("Start ER")
1204 dev[0].request("WPS_ER_START ifname=lo")
1205 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1206 if ev is None:
1207 raise Exception("AP discovery timed out")
1208 if ap_uuid not in ev:
1209 raise Exception("Expected AP UUID not found")
1210
1211 logger.info("Learn AP configuration through UPnP")
1212 dev[0].dump_monitor()
1213 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1214 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1215 if ev is None:
1216 raise Exception("AP learn timed out")
1217 if ap_uuid not in ev:
1218 raise Exception("Expected AP UUID not in settings")
1219 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1220 if ev is None:
1221 raise Exception("WPS-FAIL after AP learn timed out")
1222 time.sleep(0.1)
1223
1224 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1225 addr1 = dev[1].p2p_interface_addr()
1226 dev[0].dump_monitor()
1227 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1228 dev[1].dump_monitor()
1229 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
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 addr1 not in ev:
1234 raise Exception("Unexpected Enrollee MAC address")
1235 uuid = ev.split(' ')[1]
1236 dev[0].request("WPS_ER_PBC " + uuid)
1237 dev[1].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
1242 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1243 pin = dev[2].wps_read_pin()
1244 addr2 = dev[2].p2p_interface_addr()
1245 dev[0].dump_monitor()
1246 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1247 dev[2].dump_monitor()
1248 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1249 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1250 if ev is None:
1251 raise Exception("Enrollee not seen")
1252 if addr2 not in ev:
1253 raise Exception("Unexpected Enrollee MAC address")
1254 uuid = ev.split(' ')[1]
1255 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1256 dev[2].wait_connected(timeout=30)
1257 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1258 if ev is None:
1259 raise Exception("WPS ER did not report success")
1260
ea982de1
JM
1261 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1262 if ev is None:
1263 raise Exception("No Enrollee STA entry timeout seen")
1264
c965ae03
JM
1265 logger.info("Stop ER")
1266 dev[0].dump_monitor()
1267 dev[0].request("WPS_ER_STOP")
1268
61c3d464
JM
1269def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1270 """Multiple WPS ERs adding a new enrollee using PIN"""
1271 try:
1272 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1273 finally:
d887ed3f
JM
1274 for i in range(2):
1275 dev[i].request("WPS_ER_STOP")
61c3d464
JM
1276
1277def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1278 ssid = "wps-er-add-enrollee"
1279 ap_pin = "12345670"
1280 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1281 hostapd.add_ap(apdev[0],
61c3d464
JM
1282 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1283 "wpa_passphrase": "12345678", "wpa": "2",
1284 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1285 "device_name": "Wireless AP", "manufacturer": "Company",
1286 "model_name": "WAP", "model_number": "123",
1287 "serial_number": "12345", "device_type": "6-0050F204-1",
1288 "os_version": "01020300",
1289 'friendly_name': "WPS AP",
1290 "config_methods": "label push_button",
1291 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1292
1293 for i in range(2):
1294 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1295 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
6a5f578c 1296 for i in range(2):
61c3d464
JM
1297 dev[i].request("WPS_ER_START ifname=lo")
1298 for i in range(2):
1299 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1300 if ev is None:
1301 raise Exception("AP discovery timed out")
1302 dev[i].dump_monitor()
6a5f578c 1303 for i in range(2):
61c3d464 1304 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
6a5f578c 1305 for i in range(2):
61c3d464
JM
1306 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1307 if ev is None:
1308 raise Exception("AP learn timed out")
1309 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1310 if ev is None:
1311 raise Exception("WPS-FAIL after AP learn timed out")
1312
1313 time.sleep(0.1)
1314
1315 pin = dev[2].wps_read_pin()
1316 addr = dev[2].own_addr()
1317 dev[0].dump_monitor()
1318 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1319 dev[1].dump_monitor()
1320 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1321
1322 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1323 dev[2].dump_monitor()
1324 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1325 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1326 if ev is None:
1327 raise Exception("Enrollee did not report success")
1328 dev[2].wait_connected(timeout=15)
1329
6edaee9c
JM
1330def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1331 """WPS ER connected to AP and adding a new enrollee using PBC"""
be9f1562
JM
1332 try:
1333 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1334 finally:
1335 dev[0].request("WPS_ER_STOP")
1336
1337def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
6edaee9c
JM
1338 ssid = "wps-er-add-enrollee-pbc"
1339 ap_pin = "12345670"
1340 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1341 hostapd.add_ap(apdev[0],
6edaee9c
JM
1342 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1343 "wpa_passphrase": "12345678", "wpa": "2",
1344 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1345 "device_name": "Wireless AP", "manufacturer": "Company",
1346 "model_name": "WAP", "model_number": "123",
1347 "serial_number": "12345", "device_type": "6-0050F204-1",
1348 "os_version": "01020300",
1349 "config_methods": "label push_button",
1350 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1351 logger.info("Learn AP configuration")
33d0b157 1352 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
6edaee9c 1353 dev[0].dump_monitor()
6edaee9c
JM
1354 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1355 status = dev[0].get_status()
1356 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1357 raise Exception("Not fully connected")
1358
1359 logger.info("Start ER")
1360 dev[0].request("WPS_ER_START ifname=lo")
1361 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1362 if ev is None:
1363 raise Exception("AP discovery timed out")
1364 if ap_uuid not in ev:
1365 raise Exception("Expected AP UUID not found")
1366
d6b916c9
JM
1367 enrollee = dev[1].p2p_interface_addr()
1368
1369 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1370 raise Exception("Unknown UUID not reported")
6edaee9c
JM
1371
1372 logger.info("Add Enrollee using ER and PBC")
1373 dev[0].dump_monitor()
6edaee9c
JM
1374 dev[1].dump_monitor()
1375 dev[1].request("WPS_PBC")
1376
8674c022
JM
1377 for i in range(0, 2):
1378 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1379 if ev is None:
1380 raise Exception("Enrollee discovery timed out")
1381 if enrollee in ev:
1382 break
1383 if i == 1:
1384 raise Exception("Expected Enrollee not found")
d6b916c9
JM
1385 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1386 raise Exception("Unknown UUID not reported")
1387 logger.info("Use learned network configuration on ER")
1388 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1389 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1390 raise Exception("WPS_ER_PBC failed")
6edaee9c
JM
1391
1392 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1393 if ev is None:
1394 raise Exception("Enrollee did not report success")
5f35a5e2 1395 dev[1].wait_connected(timeout=15)
6edaee9c
JM
1396 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1397 if ev is None:
1398 raise Exception("WPS ER did not report success")
1399 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
bff3ac5b 1400
d6b916c9
JM
1401def test_ap_wps_er_pbc_overlap(dev, apdev):
1402 """WPS ER connected to AP and PBC session overlap"""
be9f1562
JM
1403 try:
1404 _test_ap_wps_er_pbc_overlap(dev, apdev)
1405 finally:
1406 dev[0].request("WPS_ER_STOP")
1407
1408def _test_ap_wps_er_pbc_overlap(dev, apdev):
d6b916c9
JM
1409 ssid = "wps-er-add-enrollee-pbc"
1410 ap_pin = "12345670"
1411 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1412 hostapd.add_ap(apdev[0],
d6b916c9
JM
1413 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1414 "wpa_passphrase": "12345678", "wpa": "2",
1415 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1416 "device_name": "Wireless AP", "manufacturer": "Company",
1417 "model_name": "WAP", "model_number": "123",
1418 "serial_number": "12345", "device_type": "6-0050F204-1",
1419 "os_version": "01020300",
1420 "config_methods": "label push_button",
1421 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1422 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1423 dev[0].dump_monitor()
1424 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1425
fba25c99
JM
1426 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1427 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1428 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1429 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1430
d6b916c9
JM
1431 dev[0].dump_monitor()
1432 dev[0].request("WPS_ER_START ifname=lo")
1433
1434 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1435 if ev is None:
1436 raise Exception("AP discovery timed out")
1437 if ap_uuid not in ev:
1438 raise Exception("Expected AP UUID not found")
1439
800bcf4e
JM
1440 # verify BSSID selection of the AP instead of UUID
1441 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1442 raise Exception("Could not select AP based on BSSID")
1443
fba25c99 1444 dev[0].dump_monitor()
d6b916c9
JM
1445 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1446 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1447 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1448 if ev is None:
1449 raise Exception("PBC scan failed")
1450 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1451 if ev is None:
1452 raise Exception("PBC scan failed")
fba25c99
JM
1453 found1 = False
1454 found2 = False
1455 addr1 = dev[1].own_addr()
1456 addr2 = dev[2].own_addr()
1457 for i in range(3):
d6b916c9
JM
1458 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1459 if ev is None:
1460 raise Exception("Enrollee discovery timed out")
fba25c99
JM
1461 if addr1 in ev:
1462 found1 = True
1463 if found2:
1464 break
1465 if addr2 in ev:
1466 found2 = True
1467 if found1:
1468 break
d6b916c9
JM
1469 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1470 raise Exception("PBC overlap not reported")
1471 dev[1].request("WPS_CANCEL")
1472 dev[2].request("WPS_CANCEL")
1473 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1474 raise Exception("Invalid WPS_ER_PBC accepted")
1475
1f020f5e
JM
1476def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1477 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
be9f1562
JM
1478 try:
1479 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1480 finally:
1481 dev[0].request("WPS_ER_STOP")
1482
1483def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1f020f5e
JM
1484 ssid = "wps-er-add-enrollee-pbc"
1485 ap_pin = "12345670"
1486 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1487 hostapd.add_ap(apdev[0],
1f020f5e
JM
1488 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1489 "wpa_passphrase": "12345678", "wpa": "2",
1490 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1491 "device_name": "Wireless AP", "manufacturer": "Company",
1492 "model_name": "WAP", "model_number": "123",
1493 "serial_number": "12345", "device_type": "6-0050F204-1",
1494 "os_version": "01020300",
1495 "config_methods": "label push_button",
1496 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1497 logger.info("Learn AP configuration")
1498 dev[0].request("SET wps_version_number 0x10")
33d0b157 1499 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e
JM
1500 dev[0].dump_monitor()
1501 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1502 status = dev[0].get_status()
1503 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1504 raise Exception("Not fully connected")
1505
1506 logger.info("Start ER")
1507 dev[0].request("WPS_ER_START ifname=lo")
1508 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1509 if ev is None:
1510 raise Exception("AP discovery timed out")
1511 if ap_uuid not in ev:
1512 raise Exception("Expected AP UUID not found")
1513
1514 logger.info("Use learned network configuration on ER")
1515 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1516
1517 logger.info("Add Enrollee using ER and PIN")
1518 enrollee = dev[1].p2p_interface_addr()
1519 pin = dev[1].wps_read_pin()
1520 dev[0].dump_monitor()
1521 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
33d0b157 1522 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1f020f5e 1523 dev[1].dump_monitor()
33d0b157 1524 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1525 dev[1].wait_connected(timeout=30)
1f020f5e
JM
1526 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1527 if ev is None:
1528 raise Exception("WPS ER did not report success")
1529
9fd6804d 1530@remote_compatible
be923570
JM
1531def test_ap_wps_er_config_ap(dev, apdev):
1532 """WPS ER configuring AP over UPnP"""
be9f1562
JM
1533 try:
1534 _test_ap_wps_er_config_ap(dev, apdev)
1535 finally:
1536 dev[0].request("WPS_ER_STOP")
1537
1538def _test_ap_wps_er_config_ap(dev, apdev):
be923570
JM
1539 ssid = "wps-er-ap-config"
1540 ap_pin = "12345670"
1541 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 1542 hostapd.add_ap(apdev[0],
be923570
JM
1543 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1544 "wpa_passphrase": "12345678", "wpa": "2",
1545 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1546 "device_name": "Wireless AP", "manufacturer": "Company",
1547 "model_name": "WAP", "model_number": "123",
1548 "serial_number": "12345", "device_type": "6-0050F204-1",
1549 "os_version": "01020300",
1550 "config_methods": "label push_button",
1551 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1552
1553 logger.info("Connect ER to the AP")
1554 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1555
1556 logger.info("WPS configuration step")
1557 dev[0].request("WPS_ER_START ifname=lo")
1558 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1559 if ev is None:
1560 raise Exception("AP discovery timed out")
1561 if ap_uuid not in ev:
1562 raise Exception("Expected AP UUID not found")
1563 new_passphrase = "1234567890"
1564 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1565 ssid.encode("hex") + " WPA2PSK CCMP " +
1566 new_passphrase.encode("hex"))
1567 ev = dev[0].wait_event(["WPS-SUCCESS"])
1568 if ev is None:
1569 raise Exception("WPS ER configuration operation timed out")
5f35a5e2 1570 dev[0].wait_disconnected(timeout=10)
be923570
JM
1571 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1572
8f8c2fe8
JM
1573 logger.info("WPS ER restart")
1574 dev[0].request("WPS_ER_START")
1575 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1576 if ev is None:
1577 raise Exception("AP discovery timed out on ER restart")
1578 if ap_uuid not in ev:
1579 raise Exception("Expected AP UUID not found on ER restart")
1580 if "OK" not in dev[0].request("WPS_ER_STOP"):
1581 raise Exception("WPS_ER_STOP failed")
1582 if "OK" not in dev[0].request("WPS_ER_STOP"):
1583 raise Exception("WPS_ER_STOP failed")
1584
9fd6804d 1585@remote_compatible
6aaa661a
JM
1586def test_ap_wps_er_cache_ap_settings(dev, apdev):
1587 """WPS ER caching AP settings"""
1588 try:
1589 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1590 finally:
1591 dev[0].request("WPS_ER_STOP")
1592
1593def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1594 ssid = "wps-er-add-enrollee"
1595 ap_pin = "12345670"
1596 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1597 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1598 "wpa_passphrase": "12345678", "wpa": "2",
1599 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1600 "device_name": "Wireless AP", "manufacturer": "Company",
1601 "model_name": "WAP", "model_number": "123",
1602 "serial_number": "12345", "device_type": "6-0050F204-1",
1603 "os_version": "01020300",
1604 "config_methods": "label push_button",
1605 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1606 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a
JM
1607 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1608 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1609 id = int(dev[0].list_networks()[0]['id'])
1610 dev[0].set_network(id, "scan_freq", "2412")
1611
1612 dev[0].request("WPS_ER_START ifname=lo")
1613 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1614 if ev is None:
1615 raise Exception("AP discovery timed out")
1616 if ap_uuid not in ev:
1617 raise Exception("Expected AP UUID not found")
1618
1619 dev[0].dump_monitor()
1620 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1621 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1622 if ev is None:
1623 raise Exception("AP learn timed out")
1624 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1625 if ev is None:
1626 raise Exception("WPS-FAIL after AP learn timed out")
1627 time.sleep(0.1)
1628
1629 hapd.disable()
1630
1631 for i in range(2):
1632 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1633 "CTRL-EVENT-DISCONNECTED" ],
1634 timeout=15)
1635 if ev is None:
1636 raise Exception("AP removal or disconnection timed out")
1637
8b8a1864 1638 hapd = hostapd.add_ap(apdev[0], params)
6aaa661a
JM
1639 for i in range(2):
1640 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1641 timeout=15)
1642 if ev is None:
1643 raise Exception("AP discovery or connection timed out")
1644
1645 pin = dev[1].wps_read_pin()
1646 dev[0].dump_monitor()
1647 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1648
1649 time.sleep(0.2)
1650
1651 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1652 dev[1].dump_monitor()
1653 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1654 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1655 if ev is None:
1656 raise Exception("Enrollee did not report success")
1657 dev[1].wait_connected(timeout=15)
1658 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1659 if ev is None:
1660 raise Exception("WPS ER did not report success")
1661
1662 dev[0].dump_monitor()
1663 dev[0].request("WPS_ER_STOP")
1664
d840350a
JM
1665def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1666 """WPS ER caching AP settings (OOM)"""
1667 try:
1668 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1669 finally:
1670 dev[0].request("WPS_ER_STOP")
1671
1672def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1673 ssid = "wps-er-add-enrollee"
1674 ap_pin = "12345670"
1675 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1676 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1677 "wpa_passphrase": "12345678", "wpa": "2",
1678 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1679 "device_name": "Wireless AP", "manufacturer": "Company",
1680 "model_name": "WAP", "model_number": "123",
1681 "serial_number": "12345", "device_type": "6-0050F204-1",
1682 "os_version": "01020300",
1683 "config_methods": "label push_button",
1684 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1685 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1686 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1687 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1688 id = int(dev[0].list_networks()[0]['id'])
1689 dev[0].set_network(id, "scan_freq", "2412")
1690
1691 dev[0].request("WPS_ER_START ifname=lo")
1692 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1693 if ev is None:
1694 raise Exception("AP discovery timed out")
1695 if ap_uuid not in ev:
1696 raise Exception("Expected AP UUID not found")
1697
1698 dev[0].dump_monitor()
1699 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1700 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1701 if ev is None:
1702 raise Exception("AP learn timed out")
1703 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1704 if ev is None:
1705 raise Exception("WPS-FAIL after AP learn timed out")
1706 time.sleep(0.1)
1707
1708 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1709 hapd.disable()
1710
1711 for i in range(2):
1712 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1713 "CTRL-EVENT-DISCONNECTED" ],
1714 timeout=15)
1715 if ev is None:
1716 raise Exception("AP removal or disconnection timed out")
1717
8b8a1864 1718 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1719 for i in range(2):
1720 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1721 timeout=15)
1722 if ev is None:
1723 raise Exception("AP discovery or connection timed out")
1724
1725 dev[0].request("WPS_ER_STOP")
1726
1727def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1728 """WPS ER caching AP settings (OOM 2)"""
1729 try:
1730 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1731 finally:
1732 dev[0].request("WPS_ER_STOP")
1733
1734def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1735 ssid = "wps-er-add-enrollee"
1736 ap_pin = "12345670"
1737 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1738 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1739 "wpa_passphrase": "12345678", "wpa": "2",
1740 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1741 "device_name": "Wireless AP", "manufacturer": "Company",
1742 "model_name": "WAP", "model_number": "123",
1743 "serial_number": "12345", "device_type": "6-0050F204-1",
1744 "os_version": "01020300",
1745 "config_methods": "label push_button",
1746 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1747 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1748 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1749 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1750 id = int(dev[0].list_networks()[0]['id'])
1751 dev[0].set_network(id, "scan_freq", "2412")
1752
1753 dev[0].request("WPS_ER_START ifname=lo")
1754 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1755 if ev is None:
1756 raise Exception("AP discovery timed out")
1757 if ap_uuid not in ev:
1758 raise Exception("Expected AP UUID not found")
1759
1760 dev[0].dump_monitor()
1761 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1762 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1763 if ev is None:
1764 raise Exception("AP learn timed out")
1765 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1766 if ev is None:
1767 raise Exception("WPS-FAIL after AP learn timed out")
1768 time.sleep(0.1)
1769
1770 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1771 hapd.disable()
1772
1773 for i in range(2):
1774 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1775 "CTRL-EVENT-DISCONNECTED" ],
1776 timeout=15)
1777 if ev is None:
1778 raise Exception("AP removal or disconnection timed out")
1779
8b8a1864 1780 hapd = hostapd.add_ap(apdev[0], params)
d840350a
JM
1781 for i in range(2):
1782 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1783 timeout=15)
1784 if ev is None:
1785 raise Exception("AP discovery or connection timed out")
1786
1787 dev[0].request("WPS_ER_STOP")
1788
eb95ced2
JM
1789def test_ap_wps_er_subscribe_oom(dev, apdev):
1790 """WPS ER subscribe OOM"""
1791 try:
1792 _test_ap_wps_er_subscribe_oom(dev, apdev)
1793 finally:
1794 dev[0].request("WPS_ER_STOP")
1795
1796def _test_ap_wps_er_subscribe_oom(dev, apdev):
1797 ssid = "wps-er-add-enrollee"
1798 ap_pin = "12345670"
1799 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1800 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1801 "wpa_passphrase": "12345678", "wpa": "2",
1802 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1803 "device_name": "Wireless AP", "manufacturer": "Company",
1804 "model_name": "WAP", "model_number": "123",
1805 "serial_number": "12345", "device_type": "6-0050F204-1",
1806 "os_version": "01020300",
1807 "config_methods": "label push_button",
1808 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1809 hapd = hostapd.add_ap(apdev[0], params)
eb95ced2
JM
1810 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1811 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1812 id = int(dev[0].list_networks()[0]['id'])
1813 dev[0].set_network(id, "scan_freq", "2412")
1814
1815 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1816 dev[0].request("WPS_ER_START ifname=lo")
1817 for i in range(50):
1818 res = dev[0].request("GET_ALLOC_FAIL")
1819 if res.startswith("0:"):
1820 break
1821 time.sleep(0.1)
1822 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1823 if ev:
1824 raise Exception("Unexpected AP discovery during OOM")
1825
1826 dev[0].request("WPS_ER_STOP")
1827
db9c88eb
JM
1828def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1829 """WPS ER SetSelectedRegistrar OOM"""
1830 try:
1831 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1832 finally:
1833 dev[0].request("WPS_ER_STOP")
1834
1835def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1836 ssid = "wps-er-add-enrollee"
1837 ap_pin = "12345670"
1838 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1839 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1840 "wpa_passphrase": "12345678", "wpa": "2",
1841 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1842 "device_name": "Wireless AP", "manufacturer": "Company",
1843 "model_name": "WAP", "model_number": "123",
1844 "serial_number": "12345", "device_type": "6-0050F204-1",
1845 "os_version": "01020300",
1846 "config_methods": "label push_button",
1847 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1848 hapd = hostapd.add_ap(apdev[0], params)
db9c88eb
JM
1849 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1850 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1851
1852 dev[0].request("WPS_ER_START ifname=lo")
1853 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1854 if ev is None:
1855 raise Exception("AP not discovered")
1856
1857 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1858 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1859 if ev is None:
1860 raise Exception("AP learn timed out")
1861 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1862 if ev is None:
1863 raise Exception("WPS-FAIL timed out")
1864 time.sleep(0.1)
1865
1866 for func in [ "http_client_url_parse;wps_er_send_set_sel_reg",
1867 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1868 "http_client_addr;wps_er_send_set_sel_reg",
1869 "wpabuf_alloc;wps_er_set_sel_reg" ]:
1870 with alloc_fail(dev[0], 1, func):
1871 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1872 raise Exception("WPS_ER_PBC failed")
1873 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1874 if ev is None:
1875 raise Exception("WPS-PBC-ACTIVE not seen")
1876
1877 dev[0].request("WPS_ER_STOP")
1878
9fd6804d 1879@remote_compatible
ae3eacf7
JM
1880def test_ap_wps_er_learn_oom(dev, apdev):
1881 """WPS ER learn OOM"""
1882 try:
1883 _test_ap_wps_er_learn_oom(dev, apdev)
1884 finally:
1885 dev[0].request("WPS_ER_STOP")
1886
1887def _test_ap_wps_er_learn_oom(dev, apdev):
1888 ssid = "wps-er-add-enrollee"
1889 ap_pin = "12345670"
1890 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1891 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1892 "wpa_passphrase": "12345678", "wpa": "2",
1893 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1894 "device_name": "Wireless AP", "manufacturer": "Company",
1895 "model_name": "WAP", "model_number": "123",
1896 "serial_number": "12345", "device_type": "6-0050F204-1",
1897 "os_version": "01020300",
1898 "config_methods": "label push_button",
1899 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
8b8a1864 1900 hapd = hostapd.add_ap(apdev[0], params)
ae3eacf7
JM
1901 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1902 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1903
1904 dev[0].request("WPS_ER_START ifname=lo")
1905 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1906 if ev is None:
1907 raise Exception("AP not discovered")
1908
1909 for func in [ "wps_er_http_put_message_cb",
1910 "xml_get_base64_item;wps_er_http_put_message_cb",
1911 "http_client_url_parse;wps_er_ap_put_message",
1912 "wps_er_soap_hdr;wps_er_ap_put_message",
1913 "http_client_addr;wps_er_ap_put_message" ]:
1914 with alloc_fail(dev[0], 1, func):
1915 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1916 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1917 if ev is not None:
1918 raise Exception("AP learn succeeded during OOM")
1919
1920 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1921 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1922 if ev is None:
1923 raise Exception("AP learn did not succeed")
1924
1925 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1926 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1927
1928 dev[0].request("WPS_ER_STOP")
1929
bff3ac5b
JM
1930def test_ap_wps_fragmentation(dev, apdev):
1931 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1932 ssid = "test-wps-fragmentation"
9602b355 1933 appin = "12345670"
6f334bf7
JD
1934 hapd = hostapd.add_ap(apdev[0],
1935 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1936 "wpa_passphrase": "12345678", "wpa": "3",
1937 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1938 "wpa_pairwise": "TKIP", "ap_pin": appin,
1939 "fragment_size": "50" })
9602b355 1940 logger.info("WPS provisioning step (PBC)")
bff3ac5b 1941 hapd.request("WPS_PBC")
33d0b157 1942 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
bff3ac5b
JM
1943 dev[0].dump_monitor()
1944 dev[0].request("SET wps_fragment_size 50")
33d0b157 1945 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1946 dev[0].wait_connected(timeout=30)
bff3ac5b
JM
1947 status = dev[0].get_status()
1948 if status['wpa_state'] != 'COMPLETED':
9602b355
JM
1949 raise Exception("Not fully connected")
1950 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1951 raise Exception("Unexpected encryption configuration")
1952 if status['key_mgmt'] != 'WPA2-PSK':
1953 raise Exception("Unexpected key_mgmt")
1954
1955 logger.info("WPS provisioning step (PIN)")
1956 pin = dev[1].wps_read_pin()
1957 hapd.request("WPS_PIN any " + pin)
33d0b157 1958 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355 1959 dev[1].request("SET wps_fragment_size 50")
33d0b157 1960 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5f35a5e2 1961 dev[1].wait_connected(timeout=30)
9602b355
JM
1962 status = dev[1].get_status()
1963 if status['wpa_state'] != 'COMPLETED':
1964 raise Exception("Not fully connected")
1965 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1966 raise Exception("Unexpected encryption configuration")
1967 if status['key_mgmt'] != 'WPA2-PSK':
1968 raise Exception("Unexpected key_mgmt")
1969
1970 logger.info("WPS connection as registrar")
33d0b157 1971 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
9602b355
JM
1972 dev[2].request("SET wps_fragment_size 50")
1973 dev[2].wps_reg(apdev[0]['bssid'], appin)
1974 status = dev[2].get_status()
1975 if status['wpa_state'] != 'COMPLETED':
bff3ac5b
JM
1976 raise Exception("Not fully connected")
1977 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1978 raise Exception("Unexpected encryption configuration")
1979 if status['key_mgmt'] != 'WPA2-PSK':
1980 raise Exception("Unexpected key_mgmt")
10ea6848 1981
9fd6804d 1982@remote_compatible
10ea6848
JM
1983def test_ap_wps_new_version_sta(dev, apdev):
1984 """WPS compatibility with new version number on the station"""
1985 ssid = "test-wps-ver"
6f334bf7
JD
1986 hapd = hostapd.add_ap(apdev[0],
1987 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1988 "wpa_passphrase": "12345678", "wpa": "2",
1989 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
10ea6848
JM
1990 logger.info("WPS provisioning step")
1991 hapd.request("WPS_PBC")
33d0b157 1992 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848
JM
1993 dev[0].dump_monitor()
1994 dev[0].request("SET wps_version_number 0x43")
dccafedb 1995 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
33d0b157 1996 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 1997 dev[0].wait_connected(timeout=30)
10ea6848 1998
9fd6804d 1999@remote_compatible
10ea6848
JM
2000def test_ap_wps_new_version_ap(dev, apdev):
2001 """WPS compatibility with new version number on the AP"""
2002 ssid = "test-wps-ver"
6f334bf7
JD
2003 hapd = hostapd.add_ap(apdev[0],
2004 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2005 "wpa_passphrase": "12345678", "wpa": "2",
2006 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
10ea6848
JM
2007 logger.info("WPS provisioning step")
2008 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
2009 raise Exception("Failed to enable test functionality")
2010 hapd.request("WPS_PBC")
33d0b157 2011 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10ea6848 2012 dev[0].dump_monitor()
33d0b157 2013 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2014 dev[0].wait_connected(timeout=30)
10ea6848 2015 hapd.request("SET wps_version_number 0x20")
3bdf7d7f 2016
9fd6804d 2017@remote_compatible
3bdf7d7f
JM
2018def test_ap_wps_check_pin(dev, apdev):
2019 """Verify PIN checking through control interface"""
6f334bf7
JD
2020 hapd = hostapd.add_ap(apdev[0],
2021 { "ssid": "wps", "eap_server": "1", "wps_state": "2",
2022 "wpa_passphrase": "12345678", "wpa": "2",
2023 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
3bdf7d7f
JM
2024 for t in [ ("12345670", "12345670"),
2025 ("12345678", "FAIL-CHECKSUM"),
df58939c 2026 ("12345", "FAIL"),
6e12eaa4 2027 ("123456789", "FAIL"),
3bdf7d7f
JM
2028 ("1234-5670", "12345670"),
2029 ("1234 5670", "12345670"),
2030 ("1-2.3:4 5670", "12345670") ]:
2031 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2032 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2033 if res != res2:
2034 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
2035 if res != t[1]:
2036 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
9ba1fcb0 2037
ac786d67
JM
2038 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
2039 raise Exception("Unexpected WPS_CHECK_PIN success")
2040 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
2041 raise Exception("Unexpected WPS_CHECK_PIN success")
2042
acd9b45a
JM
2043 for i in range(0, 10):
2044 pin = dev[0].request("WPS_PIN get")
2045 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
2046 if pin != rpin:
2047 raise Exception("Random PIN validation failed for " + pin)
2048
3381d324
JM
2049def test_ap_wps_pin_get_failure(dev, apdev):
2050 """PIN generation failure"""
2051 with fail_test(dev[0], 1,
2052 "os_get_random;wpa_supplicant_ctrl_iface_wps_pin"):
2053 if "FAIL" not in dev[0].request("WPS_PIN get"):
2054 raise Exception("WPS_PIN did not report failure")
2055
9ba1fcb0
JM
2056def test_ap_wps_wep_config(dev, apdev):
2057 """WPS 2.0 AP rejecting WEP configuration"""
2058 ssid = "test-wps-config"
2059 appin = "12345670"
6f334bf7
JD
2060 hapd = hostapd.add_ap(apdev[0],
2061 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2062 "ap_pin": appin})
33d0b157 2063 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
9ba1fcb0
JM
2064 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2065 "hello", no_wait=True)
2066 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2067 if ev is None:
2068 raise Exception("WPS-FAIL timed out")
2069 if "reason=2" not in ev:
2070 raise Exception("Unexpected reason code in WPS-FAIL")
2071 status = hapd.request("WPS_GET_STATUS")
2072 if "Last WPS result: Failed" not in status:
2073 raise Exception("WPS failure result not shown correctly")
2074 if "Failure Reason: WEP Prohibited" not in status:
2075 raise Exception("Failure reason not reported correctly")
2076 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2077 raise Exception("Peer address not shown correctly")
1013a576 2078
11d78bb1
JM
2079def test_ap_wps_wep_enroll(dev, apdev):
2080 """WPS 2.0 STA rejecting WEP configuration"""
2081 ssid = "test-wps-wep"
6f334bf7
JD
2082 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2083 "skip_cred_build": "1", "extra_cred": "wps-wep-cred" }
2084 hapd = hostapd.add_ap(apdev[0], params)
11d78bb1 2085 hapd.request("WPS_PBC")
33d0b157
JM
2086 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2087 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
11d78bb1
JM
2088 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2089 if ev is None:
2090 raise Exception("WPS-FAIL event timed out")
2091 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2092 raise Exception("Unexpected WPS-FAIL event: " + ev)
2093
9fd6804d 2094@remote_compatible
1013a576
JM
2095def test_ap_wps_ie_fragmentation(dev, apdev):
2096 """WPS AP using fragmented WPS IE"""
2097 ssid = "test-wps-ie-fragmentation"
2098 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2099 "wpa_passphrase": "12345678", "wpa": "2",
2100 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2101 "device_name": "1234567890abcdef1234567890abcdef",
2102 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2103 "model_name": "1234567890abcdef1234567890abcdef",
2104 "model_number": "1234567890abcdef1234567890abcdef",
2105 "serial_number": "1234567890abcdef1234567890abcdef" }
6f334bf7 2106 hapd = hostapd.add_ap(apdev[0], params)
1013a576 2107 hapd.request("WPS_PBC")
33d0b157
JM
2108 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2109 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2110 dev[0].wait_connected(timeout=30)
1013a576
JM
2111 bss = dev[0].get_bss(apdev[0]['bssid'])
2112 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8 2113 logger.info("Device Name not received correctly")
d7a68ad6 2114 logger.info(bss)
cf3f0ec8
JM
2115 # This can fail if Probe Response frame is missed and Beacon frame was
2116 # used to fill in the BSS entry. This can happen, e.g., during heavy
2117 # load every now and then and is not really an error, so try to
2118 # workaround by runnign another scan.
2119 dev[0].scan(freq="2412", only_new=True)
2120 bss = dev[0].get_bss(apdev[0]['bssid'])
84a40841 2121 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
cf3f0ec8
JM
2122 logger.info(bss)
2123 raise Exception("Device Name not received correctly")
1013a576
JM
2124 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2125 raise Exception("Unexpected number of WPS IEs")
44ff0400 2126
2035b170
JM
2127def get_psk(pskfile):
2128 psks = {}
2129 with open(pskfile, "r") as f:
2130 lines = f.read().splitlines()
2131 for l in lines:
2132 if l == "# WPA PSKs":
2133 continue
2134 (addr,psk) = l.split(' ')
2135 psks[addr] = psk
2136 return psks
2137
2138def test_ap_wps_per_station_psk(dev, apdev):
2139 """WPS PBC provisioning with per-station PSK"""
1d21a5be
B
2140 addr0 = dev[0].own_addr()
2141 addr1 = dev[1].own_addr()
2142 addr2 = dev[2].own_addr()
2035b170
JM
2143 ssid = "wps"
2144 appin = "12345670"
2145 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2146 try:
2147 os.remove(pskfile)
2148 except:
2149 pass
2150
4f524e99 2151 hapd = None
2035b170
JM
2152 try:
2153 with open(pskfile, "w") as f:
2154 f.write("# WPA PSKs\n")
2155
2156 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2157 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2158 "rsn_pairwise": "CCMP", "ap_pin": appin,
2159 "wpa_psk_file": pskfile }
8b8a1864 2160 hapd = hostapd.add_ap(apdev[0], params)
2035b170
JM
2161
2162 logger.info("First enrollee")
2163 hapd.request("WPS_PBC")
33d0b157
JM
2164 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2165 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2166 dev[0].wait_connected(timeout=30)
2035b170
JM
2167
2168 logger.info("Second enrollee")
2169 hapd.request("WPS_PBC")
33d0b157
JM
2170 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2171 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2172 dev[1].wait_connected(timeout=30)
2035b170
JM
2173
2174 logger.info("External registrar")
33d0b157 2175 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2176 dev[2].wps_reg(apdev[0]['bssid'], appin)
2177
2178 logger.info("Verifying PSK results")
2179 psks = get_psk(pskfile)
2180 if addr0 not in psks:
2181 raise Exception("No PSK recorded for sta0")
2182 if addr1 not in psks:
2183 raise Exception("No PSK recorded for sta1")
2184 if addr2 not in psks:
2185 raise Exception("No PSK recorded for sta2")
2186 if psks[addr0] == psks[addr1]:
2187 raise Exception("Same PSK recorded for sta0 and sta1")
2188 if psks[addr0] == psks[addr2]:
2189 raise Exception("Same PSK recorded for sta0 and sta2")
2190 if psks[addr1] == psks[addr2]:
2191 raise Exception("Same PSK recorded for sta1 and sta2")
2192
2193 dev[0].request("REMOVE_NETWORK all")
2194 logger.info("Second external registrar")
33d0b157 2195 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2035b170
JM
2196 dev[0].wps_reg(apdev[0]['bssid'], appin)
2197 psks2 = get_psk(pskfile)
2198 if addr0 not in psks2:
2199 raise Exception("No PSK recorded for sta0(reg)")
2200 if psks[addr0] == psks2[addr0]:
2201 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2202 finally:
2203 os.remove(pskfile)
4f524e99
JM
2204 if hapd:
2205 dev[0].request("DISCONNECT")
2206 dev[1].request("DISCONNECT")
2207 dev[2].request("DISCONNECT")
2208 hapd.disable()
2209 dev[0].flush_scan_cache()
2210 dev[1].flush_scan_cache()
2211 dev[2].flush_scan_cache()
2035b170 2212
373cce55
JM
2213def test_ap_wps_per_station_psk_failure(dev, apdev):
2214 """WPS PBC provisioning with per-station PSK (file not writable)"""
2215 addr0 = dev[0].p2p_dev_addr()
2216 addr1 = dev[1].p2p_dev_addr()
2217 addr2 = dev[2].p2p_dev_addr()
2218 ssid = "wps"
2219 appin = "12345670"
2220 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2221 try:
2222 os.remove(pskfile)
2223 except:
2224 pass
2225
3615bde6 2226 hapd = None
373cce55
JM
2227 try:
2228 with open(pskfile, "w") as f:
2229 f.write("# WPA PSKs\n")
2230
2231 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2232 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2233 "rsn_pairwise": "CCMP", "ap_pin": appin,
2234 "wpa_psk_file": pskfile }
8b8a1864 2235 hapd = hostapd.add_ap(apdev[0], params)
373cce55
JM
2236 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2237 raise Exception("Failed to set wpa_psk_file")
2238
2239 logger.info("First enrollee")
2240 hapd.request("WPS_PBC")
33d0b157
JM
2241 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2242 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2243 dev[0].wait_connected(timeout=30)
373cce55
JM
2244
2245 logger.info("Second enrollee")
2246 hapd.request("WPS_PBC")
33d0b157
JM
2247 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2248 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2249 dev[1].wait_connected(timeout=30)
373cce55
JM
2250
2251 logger.info("External registrar")
33d0b157 2252 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
373cce55
JM
2253 dev[2].wps_reg(apdev[0]['bssid'], appin)
2254
2255 logger.info("Verifying PSK results")
2256 psks = get_psk(pskfile)
2257 if len(psks) > 0:
2258 raise Exception("PSK recorded unexpectedly")
2259 finally:
3615bde6
JM
2260 if hapd:
2261 for i in range(3):
2262 dev[i].request("DISCONNECT")
2263 hapd.disable()
2264 for i in range(3):
2265 dev[i].flush_scan_cache()
373cce55
JM
2266 os.remove(pskfile)
2267
e8518757
JM
2268def test_ap_wps_pin_request_file(dev, apdev):
2269 """WPS PIN provisioning with configured AP"""
2270 ssid = "wps"
2271 pinfile = "/tmp/ap_wps_pin_request_file.log"
2272 if os.path.exists(pinfile):
b638f703 2273 os.remove(pinfile)
6f334bf7
JD
2274 hapd = hostapd.add_ap(apdev[0],
2275 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2276 "wps_pin_requests": pinfile,
2277 "wpa_passphrase": "12345678", "wpa": "2",
2278 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e8518757
JM
2279 uuid = dev[0].get_status_field("uuid")
2280 pin = dev[0].wps_read_pin()
2281 try:
33d0b157
JM
2282 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2283 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
e8518757
JM
2284 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2285 if ev is None:
2286 raise Exception("PIN needed event not shown")
2287 if uuid not in ev:
2288 raise Exception("UUID mismatch")
2289 dev[0].request("WPS_CANCEL")
2290 success = False
2291 with open(pinfile, "r") as f:
2292 lines = f.readlines()
2293 for l in lines:
2294 if uuid in l:
2295 success = True
2296 break
2297 if not success:
2298 raise Exception("PIN request entry not in the log file")
2299 finally:
b638f703
JM
2300 try:
2301 os.remove(pinfile)
2302 except:
2303 pass
e8518757 2304
56887c35
JM
2305def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2306 """WPS auto-setup with configuration file"""
2307 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2308 ifname = apdev[0]['ifname']
2309 try:
2310 with open(conffile, "w") as f:
2311 f.write("driver=nl80211\n")
2312 f.write("hw_mode=g\n")
2313 f.write("channel=1\n")
2314 f.write("ieee80211n=1\n")
2315 f.write("interface=%s\n" % ifname)
2316 f.write("ctrl_interface=/var/run/hostapd\n")
2317 f.write("ssid=wps\n")
2318 f.write("eap_server=1\n")
2319 f.write("wps_state=1\n")
5148b392 2320 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
56887c35 2321 hapd.request("WPS_PBC")
33d0b157
JM
2322 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2323 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 2324 dev[0].wait_connected(timeout=30)
56887c35
JM
2325 with open(conffile, "r") as f:
2326 lines = f.read().splitlines()
2327 vals = dict()
2328 for l in lines:
2329 try:
2330 [name,value] = l.split('=', 1)
2331 vals[name] = value
2332 except ValueError, e:
2333 if "# WPS configuration" in l:
2334 pass
2335 else:
2336 raise Exception("Unexpected configuration line: " + l)
2337 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2338 raise Exception("Incorrect configuration: " + str(vals))
2339 finally:
b638f703
JM
2340 try:
2341 os.remove(conffile)
2342 except:
2343 pass
56887c35 2344
91f3cf69 2345def test_ap_wps_pbc_timeout(dev, apdev, params):
31e56b95 2346 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
91f3cf69 2347 if not params['long']:
81e787b7 2348 raise HwsimSkip("Skip test case with long duration due to --long not specified")
31e56b95 2349 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2350 hapd = add_ssdp_ap(apdev[0], ap_uuid)
31e56b95
JM
2351
2352 location = ssdp_get_location(ap_uuid)
2353 urls = upnp_get_urls(location)
2354 eventurl = urlparse.urlparse(urls['event_sub_url'])
2355 ctrlurl = urlparse.urlparse(urls['control_url'])
2356
2357 url = urlparse.urlparse(location)
2358 conn = httplib.HTTPConnection(url.netloc)
2359
2360 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
2361 def handle(self):
2362 data = self.rfile.readline().strip()
2363 logger.debug(data)
2364 self.wfile.write(gen_wps_event())
2365
2366 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2367 server.timeout = 1
2368
2369 headers = { "callback": '<http://127.0.0.1:12345/event>',
2370 "NT": "upnp:event",
2371 "timeout": "Second-1234" }
2372 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2373 resp = conn.getresponse()
2374 if resp.status != 200:
2375 raise Exception("Unexpected HTTP response: %d" % resp.status)
2376 sid = resp.getheader("sid")
2377 logger.debug("Subscription SID " + sid)
2378
2379 msg = '''<?xml version="1.0"?>
2380<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2381<s:Body>
2382<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2383<NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2384VFi5hrLk
2385</NewMessage>
2386</u:SetSelectedRegistrar>
2387</s:Body>
2388</s:Envelope>'''
2389 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2390 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2391 conn.request("POST", ctrlurl.path, msg, headers)
2392 resp = conn.getresponse()
2393 if resp.status != 200:
2394 raise Exception("Unexpected HTTP response: %d" % resp.status)
2395
2396 server.handle_request()
2397
91f3cf69
JM
2398 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2399 if "OK" not in dev[0].request("WPS_PBC"):
2400 raise Exception("WPS_PBC failed")
31e56b95
JM
2401
2402 start = os.times()[4]
2403
2404 server.handle_request()
2405 dev[1].request("BSS_FLUSH 0")
2406 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2407 only_new=True)
2408 bss = dev[1].get_bss(apdev[0]['bssid'])
2409 logger.debug("BSS: " + str(bss))
2410 if '[WPS-AUTH]' not in bss['flags']:
2411 raise Exception("WPS not indicated authorized")
2412
2413 server.handle_request()
2414
2415 wps_timeout_seen = False
2416
2417 while True:
2418 hapd.dump_monitor()
2419 dev[1].dump_monitor()
2420 if not wps_timeout_seen:
2421 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2422 if ev is not None:
2423 logger.info("PBC timeout seen")
2424 wps_timeout_seen = True
2425 else:
2426 dev[0].dump_monitor()
2427 now = os.times()[4]
2428 if now - start > 130:
2429 raise Exception("Selected registration information not removed")
2430 dev[1].request("BSS_FLUSH 0")
2431 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2432 only_new=True)
2433 bss = dev[1].get_bss(apdev[0]['bssid'])
2434 logger.debug("BSS: " + str(bss))
2435 if '[WPS-AUTH]' not in bss['flags']:
2436 break
2437 server.handle_request()
2438
2439 server.server_close()
2440
2441 if wps_timeout_seen:
2442 return
2443
2444 now = os.times()[4]
2445 if now < start + 150:
2446 dur = start + 150 - now
2447 else:
2448 dur = 1
2449 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2450 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
91f3cf69
JM
2451 if ev is None:
2452 raise Exception("WPS-TIMEOUT not reported")
2453
21aa8b7e 2454def add_ssdp_ap(ap, ap_uuid):
44ff0400
JM
2455 ssid = "wps-ssdp"
2456 ap_pin = "12345670"
24b7f282
JM
2457 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2458 "wpa_passphrase": "12345678", "wpa": "2",
2459 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2460 "device_name": "Wireless AP", "manufacturer": "Company",
2461 "model_name": "WAP", "model_number": "123",
2462 "serial_number": "12345", "device_type": "6-0050F204-1",
2463 "os_version": "01020300",
2464 "config_methods": "label push_button",
2465 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2466 "friendly_name": "WPS Access Point",
2467 "manufacturer_url": "http://www.example.com/",
2468 "model_description": "Wireless Access Point",
2469 "model_url": "http://www.example.com/model/",
2470 "upc": "123456789012" }
21aa8b7e 2471 return hostapd.add_ap(ap, params)
44ff0400
JM
2472
2473def ssdp_send(msg, no_recv=False):
2474 socket.setdefaulttimeout(1)
2475 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2476 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2477 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2478 sock.bind(("127.0.0.1", 0))
2479 sock.sendto(msg, ("239.255.255.250", 1900))
2480 if no_recv:
2481 return None
2482 return sock.recv(1000)
2483
96038a5f 2484def ssdp_send_msearch(st, no_recv=False):
44ff0400
JM
2485 msg = '\r\n'.join([
2486 'M-SEARCH * HTTP/1.1',
2487 'HOST: 239.255.255.250:1900',
2488 'MX: 1',
2489 'MAN: "ssdp:discover"',
2490 'ST: ' + st,
2491 '', ''])
96038a5f 2492 return ssdp_send(msg, no_recv=no_recv)
44ff0400
JM
2493
2494def test_ap_wps_ssdp_msearch(dev, apdev):
2495 """WPS AP and SSDP M-SEARCH messages"""
2496 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2497 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2498
2499 msg = '\r\n'.join([
2500 'M-SEARCH * HTTP/1.1',
2501 'Host: 239.255.255.250:1900',
2502 'Mx: 1',
2503 'Man: "ssdp:discover"',
2504 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2505 '', ''])
2506 ssdp_send(msg)
2507
2508 msg = '\r\n'.join([
2509 'M-SEARCH * HTTP/1.1',
2510 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2511 'mx: \t1\t\t ',
2512 'man: \t \t "ssdp:discover" ',
2513 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2514 '', ''])
2515 ssdp_send(msg)
2516
2517 ssdp_send_msearch("ssdp:all")
2518 ssdp_send_msearch("upnp:rootdevice")
2519 ssdp_send_msearch("uuid:" + ap_uuid)
2520 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
bc6e3288 2521 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1")
44ff0400
JM
2522
2523 msg = '\r\n'.join([
2524 'M-SEARCH * HTTP/1.1',
2525 'HOST:\t239.255.255.250:1900',
2526 'MAN: "ssdp:discover"',
2527 'MX: 130',
2528 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2529 '', ''])
2530 ssdp_send(msg, no_recv=True)
2531
2532def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2533 """WPS AP and invalid SSDP M-SEARCH messages"""
2534 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2535 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2536
2537 socket.setdefaulttimeout(1)
2538 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2539 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2540 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2541 sock.bind(("127.0.0.1", 0))
2542
2543 logger.debug("Missing MX")
2544 msg = '\r\n'.join([
2545 'M-SEARCH * HTTP/1.1',
2546 'HOST: 239.255.255.250:1900',
2547 'MAN: "ssdp:discover"',
2548 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2549 '', ''])
2550 sock.sendto(msg, ("239.255.255.250", 1900))
2551
2552 logger.debug("Negative MX")
2553 msg = '\r\n'.join([
2554 'M-SEARCH * HTTP/1.1',
2555 'HOST: 239.255.255.250:1900',
2556 'MX: -1',
2557 'MAN: "ssdp:discover"',
2558 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2559 '', ''])
2560 sock.sendto(msg, ("239.255.255.250", 1900))
2561
2562 logger.debug("Invalid MX")
2563 msg = '\r\n'.join([
2564 'M-SEARCH * HTTP/1.1',
2565 'HOST: 239.255.255.250:1900',
2566 'MX; 1',
2567 'MAN: "ssdp:discover"',
2568 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2569 '', ''])
2570 sock.sendto(msg, ("239.255.255.250", 1900))
2571
2572 logger.debug("Missing MAN")
2573 msg = '\r\n'.join([
2574 'M-SEARCH * HTTP/1.1',
2575 'HOST: 239.255.255.250:1900',
2576 'MX: 1',
2577 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2578 '', ''])
2579 sock.sendto(msg, ("239.255.255.250", 1900))
2580
2581 logger.debug("Invalid MAN")
2582 msg = '\r\n'.join([
2583 'M-SEARCH * HTTP/1.1',
2584 'HOST: 239.255.255.250:1900',
2585 'MX: 1',
2586 'MAN: foo',
2587 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2588 '', ''])
2589 sock.sendto(msg, ("239.255.255.250", 1900))
2590 msg = '\r\n'.join([
2591 'M-SEARCH * HTTP/1.1',
2592 'HOST: 239.255.255.250:1900',
2593 'MX: 1',
2594 'MAN; "ssdp:discover"',
2595 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2596 '', ''])
2597 sock.sendto(msg, ("239.255.255.250", 1900))
2598
2599 logger.debug("Missing HOST")
2600 msg = '\r\n'.join([
2601 'M-SEARCH * HTTP/1.1',
2602 'MAN: "ssdp:discover"',
2603 'MX: 1',
2604 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2605 '', ''])
2606 sock.sendto(msg, ("239.255.255.250", 1900))
2607
2608 logger.debug("Missing ST")
2609 msg = '\r\n'.join([
2610 'M-SEARCH * HTTP/1.1',
2611 'HOST: 239.255.255.250:1900',
2612 'MAN: "ssdp:discover"',
2613 'MX: 1',
2614 '', ''])
2615 sock.sendto(msg, ("239.255.255.250", 1900))
2616
2617 logger.debug("Mismatching 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: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2624 '', ''])
2625 sock.sendto(msg, ("239.255.255.250", 1900))
2626 msg = '\r\n'.join([
2627 'M-SEARCH * HTTP/1.1',
2628 'HOST: 239.255.255.250:1900',
2629 'MAN: "ssdp:discover"',
2630 'MX: 1',
2631 'ST: foo:bar',
2632 '', ''])
2633 sock.sendto(msg, ("239.255.255.250", 1900))
2634 msg = '\r\n'.join([
2635 'M-SEARCH * HTTP/1.1',
2636 'HOST: 239.255.255.250:1900',
2637 'MAN: "ssdp:discover"',
2638 'MX: 1',
2639 'ST: foobar',
2640 '', ''])
2641 sock.sendto(msg, ("239.255.255.250", 1900))
2642
2643 logger.debug("Invalid ST")
2644 msg = '\r\n'.join([
2645 'M-SEARCH * HTTP/1.1',
2646 'HOST: 239.255.255.250:1900',
2647 'MAN: "ssdp:discover"',
2648 'MX: 1',
2649 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2650 '', ''])
2651 sock.sendto(msg, ("239.255.255.250", 1900))
2652
2653 logger.debug("Invalid M-SEARCH")
2654 msg = '\r\n'.join([
2655 'M+SEARCH * HTTP/1.1',
2656 'HOST: 239.255.255.250:1900',
2657 'MAN: "ssdp:discover"',
2658 'MX: 1',
2659 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2660 '', ''])
2661 sock.sendto(msg, ("239.255.255.250", 1900))
2662 msg = '\r\n'.join([
2663 'M-SEARCH-* HTTP/1.1',
2664 'HOST: 239.255.255.250:1900',
2665 'MAN: "ssdp:discover"',
2666 'MX: 1',
2667 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2668 '', ''])
2669 sock.sendto(msg, ("239.255.255.250", 1900))
2670
2671 logger.debug("Invalid message format")
2672 sock.sendto("NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2673 msg = '\r'.join([
2674 'M-SEARCH * HTTP/1.1',
2675 'HOST: 239.255.255.250:1900',
2676 'MAN: "ssdp:discover"',
2677 'MX: 1',
2678 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2679 '', ''])
2680 sock.sendto(msg, ("239.255.255.250", 1900))
2681
2682 try:
2683 r = sock.recv(1000)
2684 raise Exception("Unexpected M-SEARCH response: " + r)
2685 except socket.timeout:
2686 pass
2687
2688 logger.debug("Valid M-SEARCH")
2689 msg = '\r\n'.join([
2690 'M-SEARCH * HTTP/1.1',
2691 'HOST: 239.255.255.250:1900',
2692 'MAN: "ssdp:discover"',
2693 'MX: 1',
2694 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2695 '', ''])
2696 sock.sendto(msg, ("239.255.255.250", 1900))
2697
2698 try:
2699 r = sock.recv(1000)
2700 pass
2701 except socket.timeout:
2702 raise Exception("No SSDP response")
2703
2704def test_ap_wps_ssdp_burst(dev, apdev):
2705 """WPS AP and SSDP burst"""
2706 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2707 add_ssdp_ap(apdev[0], ap_uuid)
44ff0400
JM
2708
2709 msg = '\r\n'.join([
2710 'M-SEARCH * HTTP/1.1',
2711 'HOST: 239.255.255.250:1900',
2712 'MAN: "ssdp:discover"',
2713 'MX: 1',
2714 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2715 '', ''])
2716 socket.setdefaulttimeout(1)
2717 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2718 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2719 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2720 sock.bind(("127.0.0.1", 0))
2721 for i in range(0, 25):
2722 sock.sendto(msg, ("239.255.255.250", 1900))
2723 resp = 0
2724 while True:
2725 try:
2726 r = sock.recv(1000)
2727 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2728 raise Exception("Unexpected message: " + r)
2729 resp += 1
2730 except socket.timeout:
2731 break
2732 if resp < 20:
2733 raise Exception("Too few SSDP responses")
2734
2735 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2736 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2737 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2738 sock.bind(("127.0.0.1", 0))
2739 for i in range(0, 25):
2740 sock.sendto(msg, ("239.255.255.250", 1900))
2741 while True:
2742 try:
2743 r = sock.recv(1000)
2744 if ap_uuid in r:
2745 break
2746 except socket.timeout:
2747 raise Exception("No SSDP response")
47c549fd
JM
2748
2749def ssdp_get_location(uuid):
2750 res = ssdp_send_msearch("uuid:" + uuid)
2751 location = None
2752 for l in res.splitlines():
2753 if l.lower().startswith("location:"):
2754 location = l.split(':', 1)[1].strip()
2755 break
2756 if location is None:
2757 raise Exception("No UPnP location found")
2758 return location
2759
2760def upnp_get_urls(location):
aa713e71 2761 conn = urllib.urlopen(location, proxies={})
47c549fd
JM
2762 tree = ET.parse(conn)
2763 root = tree.getroot()
2764 urn = '{urn:schemas-upnp-org:device-1-0}'
2765 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2766 res = {}
2767 res['scpd_url'] = urlparse.urljoin(location, service.find(urn + 'SCPDURL').text)
2768 res['control_url'] = urlparse.urljoin(location, service.find(urn + 'controlURL').text)
2769 res['event_sub_url'] = urlparse.urljoin(location, service.find(urn + 'eventSubURL').text)
2770 return res
2771
dd124ee8
JM
2772def upnp_soap_action(conn, path, action, include_soap_action=True,
2773 soap_action_override=None, newmsg=None, neweventtype=None,
2774 neweventmac=None):
47c549fd
JM
2775 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2776 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2777 ET.register_namespace('soapenv', soapns)
2778 ET.register_namespace('wfa', wpsns)
2779 attrib = {}
2780 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2781 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2782 body = ET.SubElement(root, "{%s}Body" % soapns)
2783 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
dd124ee8
JM
2784 if newmsg:
2785 msg = ET.SubElement(act, "NewMessage")
2786 msg.text = base64.b64encode(newmsg)
2787 if neweventtype:
2788 msg = ET.SubElement(act, "NewWLANEventType")
2789 msg.text = neweventtype
2790 if neweventmac:
2791 msg = ET.SubElement(act, "NewWLANEventMAC")
2792 msg.text = neweventmac
47c549fd
JM
2793 tree = ET.ElementTree(root)
2794 soap = StringIO.StringIO()
2795 tree.write(soap, xml_declaration=True, encoding='utf-8')
2796
2797 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2798 if include_soap_action:
2799 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2800 elif soap_action_override:
2801 headers["SOAPAction"] = soap_action_override
2802 conn.request("POST", path, soap.getvalue(), headers)
2803 return conn.getresponse()
2804
2805def test_ap_wps_upnp(dev, apdev):
2806 """WPS AP and UPnP operations"""
2807 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2808 add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2809
2810 location = ssdp_get_location(ap_uuid)
2811 urls = upnp_get_urls(location)
2812
aa713e71 2813 conn = urllib.urlopen(urls['scpd_url'], proxies={})
47c549fd
JM
2814 scpd = conn.read()
2815
aa713e71
AO
2816 conn = urllib.urlopen(urlparse.urljoin(location, "unknown.html"),
2817 proxies={})
47c549fd
JM
2818 if conn.getcode() != 404:
2819 raise Exception("Unexpected HTTP response to GET unknown URL")
2820
2821 url = urlparse.urlparse(location)
2822 conn = httplib.HTTPConnection(url.netloc)
2823 #conn.set_debuglevel(1)
2824 headers = { "Content-type": 'text/xml; charset="utf-8"',
2825 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2826 conn.request("POST", "hello", "\r\n\r\n", headers)
2827 resp = conn.getresponse()
2828 if resp.status != 404:
5c267d71 2829 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2830
2831 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2832 resp = conn.getresponse()
2833 if resp.status != 501:
5c267d71 2834 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2835
2836 headers = { "Content-type": 'text/xml; charset="utf-8"',
2837 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2838 ctrlurl = urlparse.urlparse(urls['control_url'])
2839 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2840 resp = conn.getresponse()
2841 if resp.status != 401:
5c267d71 2842 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2843
2844 logger.debug("GetDeviceInfo without SOAPAction header")
2845 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2846 include_soap_action=False)
2847 if resp.status != 401:
5c267d71 2848 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2849
2850 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2851 for act in [ "foo",
2852 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2853 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2854 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2855 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2856 include_soap_action=False,
2857 soap_action_override=act)
2858 if resp.status != 401:
5c267d71 2859 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2860
2861 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2862 if resp.status != 200:
5c267d71 2863 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2864 dev = resp.read()
2865 if "NewDeviceInfo" not in dev:
2866 raise Exception("Unexpected GetDeviceInfo response")
2867
2868 logger.debug("PutMessage without required parameters")
2869 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2870 if resp.status != 600:
5c267d71 2871 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2872
2873 logger.debug("PutWLANResponse without required parameters")
2874 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2875 if resp.status != 600:
5c267d71 2876 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2877
2878 logger.debug("SetSelectedRegistrar from unregistered ER")
2879 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2880 if resp.status != 501:
5c267d71 2881 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2882
2883 logger.debug("Unknown action")
2884 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2885 if resp.status != 401:
5c267d71 2886 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2887
2888def test_ap_wps_upnp_subscribe(dev, apdev):
2889 """WPS AP and UPnP event subscription"""
2890 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 2891 hapd = add_ssdp_ap(apdev[0], ap_uuid)
47c549fd
JM
2892
2893 location = ssdp_get_location(ap_uuid)
2894 urls = upnp_get_urls(location)
2895 eventurl = urlparse.urlparse(urls['event_sub_url'])
2896
2897 url = urlparse.urlparse(location)
2898 conn = httplib.HTTPConnection(url.netloc)
2899 #conn.set_debuglevel(1)
2900 headers = { "callback": '<http://127.0.0.1:12345/event>',
2901 "timeout": "Second-1234" }
2902 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2903 resp = conn.getresponse()
2904 if resp.status != 412:
5c267d71 2905 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2906
2907 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2908 resp = conn.getresponse()
2909 if resp.status != 412:
5c267d71 2910 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2911
2912 headers = { "NT": "upnp:event",
2913 "timeout": "Second-1234" }
2914 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2915 resp = conn.getresponse()
2916 if resp.status != 412:
5c267d71 2917 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2918
2919 headers = { "callback": '<http://127.0.0.1:12345/event>',
2920 "NT": "upnp:foobar",
2921 "timeout": "Second-1234" }
2922 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2923 resp = conn.getresponse()
2924 if resp.status != 400:
5c267d71 2925 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2926
2927 logger.debug("Valid subscription")
2928 headers = { "callback": '<http://127.0.0.1:12345/event>',
2929 "NT": "upnp:event",
2930 "timeout": "Second-1234" }
2931 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2932 resp = conn.getresponse()
2933 if resp.status != 200:
5c267d71 2934 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2935 sid = resp.getheader("sid")
2936 logger.debug("Subscription SID " + sid)
2937
2938 logger.debug("Invalid re-subscription")
2939 headers = { "NT": "upnp:event",
2940 "sid": "123456734567854",
2941 "timeout": "Second-1234" }
2942 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2943 resp = conn.getresponse()
2944 if resp.status != 400:
5c267d71 2945 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2946
2947 logger.debug("Invalid re-subscription")
2948 headers = { "NT": "upnp:event",
2949 "sid": "uuid:123456734567854",
2950 "timeout": "Second-1234" }
2951 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2952 resp = conn.getresponse()
2953 if resp.status != 400:
5c267d71 2954 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2955
2956 logger.debug("Invalid re-subscription")
2957 headers = { "callback": '<http://127.0.0.1:12345/event>',
2958 "NT": "upnp:event",
2959 "sid": sid,
2960 "timeout": "Second-1234" }
2961 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2962 resp = conn.getresponse()
2963 if resp.status != 400:
5c267d71 2964 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2965
2966 logger.debug("SID mismatch in re-subscription")
2967 headers = { "NT": "upnp:event",
2968 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2969 "timeout": "Second-1234" }
2970 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2971 resp = conn.getresponse()
2972 if resp.status != 412:
5c267d71 2973 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2974
2975 logger.debug("Valid re-subscription")
2976 headers = { "NT": "upnp:event",
2977 "sid": sid,
2978 "timeout": "Second-1234" }
2979 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2980 resp = conn.getresponse()
2981 if resp.status != 200:
5c267d71 2982 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2983 sid2 = resp.getheader("sid")
2984 logger.debug("Subscription SID " + sid2)
2985
2986 if sid != sid2:
2987 raise Exception("Unexpected SID change")
2988
2989 logger.debug("Valid re-subscription")
2990 headers = { "NT": "upnp:event",
2991 "sid": "uuid: \t \t" + sid.split(':')[1],
2992 "timeout": "Second-1234" }
2993 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2994 resp = conn.getresponse()
2995 if resp.status != 200:
5c267d71 2996 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
2997
2998 logger.debug("Invalid unsubscription")
2999 headers = { "sid": sid }
3000 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
3001 resp = conn.getresponse()
3002 if resp.status != 412:
5c267d71 3003 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3004 headers = { "foo": "bar" }
3005 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3006 resp = conn.getresponse()
3007 if resp.status != 412:
5c267d71 3008 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3009
3010 logger.debug("Valid unsubscription")
3011 headers = { "sid": sid }
3012 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3013 resp = conn.getresponse()
3014 if resp.status != 200:
5c267d71 3015 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3016
3017 logger.debug("Unsubscription for not existing SID")
3018 headers = { "sid": sid }
3019 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3020 resp = conn.getresponse()
3021 if resp.status != 412:
5c267d71 3022 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3023
3024 logger.debug("Invalid unsubscription")
3025 headers = { "sid": " \t \tfoo" }
3026 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3027 resp = conn.getresponse()
3028 if resp.status != 400:
5c267d71 3029 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3030
3031 logger.debug("Invalid unsubscription")
3032 headers = { "sid": "uuid:\t \tfoo" }
3033 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3034 resp = conn.getresponse()
3035 if resp.status != 400:
5c267d71 3036 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3037
3038 logger.debug("Invalid unsubscription")
3039 headers = { "NT": "upnp:event",
3040 "sid": sid }
3041 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3042 resp = conn.getresponse()
3043 if resp.status != 400:
5c267d71 3044 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3045 headers = { "callback": '<http://127.0.0.1:12345/event>',
3046 "sid": sid }
3047 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3048 resp = conn.getresponse()
3049 if resp.status != 400:
5c267d71 3050 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3051
3052 logger.debug("Valid subscription with multiple callbacks")
3053 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>',
3054 "NT": "upnp:event",
3055 "timeout": "Second-1234" }
3056 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3057 resp = conn.getresponse()
3058 if resp.status != 200:
5c267d71 3059 raise Exception("Unexpected HTTP response: %d" % resp.status)
47c549fd
JM
3060 sid = resp.getheader("sid")
3061 logger.debug("Subscription SID " + sid)
d352c407 3062
24b7f282
JM
3063 # Force subscription to be deleted due to errors
3064 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3065 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3066 with alloc_fail(hapd, 1, "event_build_message"):
3067 for i in range(10):
3068 dev[1].dump_monitor()
3069 dev[2].dump_monitor()
3070 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3071 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3072 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3073 dev[1].request("WPS_CANCEL")
3074 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3075 dev[2].request("WPS_CANCEL")
3076 if i % 4 == 1:
3077 time.sleep(1)
3078 else:
3079 time.sleep(0.1)
3080 time.sleep(0.2)
3081
3082 headers = { "sid": sid }
3083 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3084 resp = conn.getresponse()
3085 if resp.status != 200 and resp.status != 412:
3086 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3087
3088 headers = { "callback": '<http://127.0.0.1:12345/event>',
3089 "NT": "upnp:event",
3090 "timeout": "Second-1234" }
3091 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3092 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3093 resp = conn.getresponse()
3094 if resp.status != 200:
3095 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3096 sid = resp.getheader("sid")
3097 logger.debug("Subscription SID " + sid)
3098
3099 headers = { "sid": sid }
3100 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3101 resp = conn.getresponse()
3102 if resp.status != 200:
3103 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3104
3105 headers = { "callback": '<http://127.0.0.1:12345/event>',
3106 "NT": "upnp:event",
3107 "timeout": "Second-1234" }
3108 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3109 resp = conn.getresponse()
3110 if resp.status != 200:
3111 raise Exception("Unexpected HTTP response: %d" % resp.status)
3112 sid = resp.getheader("sid")
3113 logger.debug("Subscription SID " + sid)
3114
3115 with alloc_fail(hapd, 1, "=event_add"):
3116 for i in range(2):
3117 dev[1].dump_monitor()
3118 dev[2].dump_monitor()
3119 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3120 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3121 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3122 dev[1].request("WPS_CANCEL")
3123 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3124 dev[2].request("WPS_CANCEL")
3125 if i == 0:
3126 time.sleep(1)
3127 else:
3128 time.sleep(0.1)
3129
3130 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3131 resp = conn.getresponse()
3132 if resp.status != 200:
3133 raise Exception("Unexpected HTTP response: %d" % resp.status)
3134
3135 with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
3136 dev[1].dump_monitor()
3137 dev[2].dump_monitor()
3138 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3139 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3140 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3141 dev[1].request("WPS_CANCEL")
3142 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3143 dev[2].request("WPS_CANCEL")
3144 time.sleep(0.1)
3145
3146 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3147 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3148 resp = conn.getresponse()
3149 if resp.status != 500:
3150 raise Exception("Unexpected HTTP response: %d" % resp.status)
3151
3152 with alloc_fail(hapd, 1, "=subscription_start"):
3153 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3154 resp = conn.getresponse()
3155 if resp.status != 500:
3156 raise Exception("Unexpected HTTP response: %d" % resp.status)
3157
3158 headers = { "callback": '',
3159 "NT": "upnp:event",
3160 "timeout": "Second-1234" }
3161 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3162 resp = conn.getresponse()
3163 if resp.status != 500:
3164 raise Exception("Unexpected HTTP response: %d" % resp.status)
3165
3166 headers = { "callback": ' <',
3167 "NT": "upnp:event",
3168 "timeout": "Second-1234" }
3169 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3170 resp = conn.getresponse()
3171 if resp.status != 500:
3172 raise Exception("Unexpected HTTP response: %d" % resp.status)
3173
3174 headers = { "callback": '<http://127.0.0.1:12345/event>',
3175 "NT": "upnp:event",
3176 "timeout": "Second-1234" }
3177 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3178 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3179 resp = conn.getresponse()
3180 if resp.status != 500:
3181 raise Exception("Unexpected HTTP response: %d" % resp.status)
3182
3183 with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
3184 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3185 resp = conn.getresponse()
3186 if resp.status != 500:
3187 raise Exception("Unexpected HTTP response: %d" % resp.status)
3188
3189 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3190 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3191 resp = conn.getresponse()
3192 if resp.status != 500:
3193 raise Exception("Unexpected HTTP response: %d" % resp.status)
3194
3195 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3196 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3197 resp = conn.getresponse()
3198 if resp.status != 500:
3199 raise Exception("Unexpected HTTP response: %d" % resp.status)
3200
3201 for i in range(6):
3202 headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3203 "NT": "upnp:event",
3204 "timeout": "Second-1234" }
3205 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3206 resp = conn.getresponse()
3207 if resp.status != 200:
3208 raise Exception("Unexpected HTTP response: %d" % resp.status)
3209
3210 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3211 dev[1].dump_monitor()
3212 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3213 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3214 dev[1].request("WPS_CANCEL")
3215 time.sleep(0.1)
3216
3217 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3218 dev[1].dump_monitor()
3219 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3220 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3221 dev[1].request("WPS_CANCEL")
3222 time.sleep(0.1)
3223
5b52e1ad
JM
3224 with alloc_fail(hapd, 1,
3225 "base64_gen_encode;?base64_encode;upnp_wps_device_send_wlan_event"):
24b7f282
JM
3226 dev[1].dump_monitor()
3227 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3228 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3229 dev[1].request("WPS_CANCEL")
3230 time.sleep(0.1)
3231
3232 hapd.disable()
3233 with alloc_fail(hapd, 1, "get_netif_info"):
3234 if "FAIL" not in hapd.request("ENABLE"):
3235 raise Exception("ENABLE succeeded during OOM")
3236
d91a64c4
JM
3237def test_ap_wps_upnp_subscribe_events(dev, apdev):
3238 """WPS AP and UPnP event subscription and many events"""
3239 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3240 hapd = add_ssdp_ap(apdev[0], ap_uuid)
d91a64c4
JM
3241
3242 location = ssdp_get_location(ap_uuid)
3243 urls = upnp_get_urls(location)
3244 eventurl = urlparse.urlparse(urls['event_sub_url'])
3245
3246 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
3247 def handle(self):
3248 data = self.rfile.readline().strip()
3249 logger.debug(data)
3250 self.wfile.write(gen_wps_event())
3251
3252 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3253 server.timeout = 1
3254
3255 url = urlparse.urlparse(location)
3256 conn = httplib.HTTPConnection(url.netloc)
3257
3258 headers = { "callback": '<http://127.0.0.1:12345/event>',
3259 "NT": "upnp:event",
3260 "timeout": "Second-1234" }
3261 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3262 resp = conn.getresponse()
3263 if resp.status != 200:
3264 raise Exception("Unexpected HTTP response: %d" % resp.status)
3265 sid = resp.getheader("sid")
3266 logger.debug("Subscription SID " + sid)
3267
3268 # Fetch the first event message
3269 server.handle_request()
3270
3271 # Force subscription event queue to reach the maximum length by generating
3272 # new proxied events without the ER fetching any of the pending events.
3273 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3274 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3275 for i in range(16):
3276 dev[1].dump_monitor()
3277 dev[2].dump_monitor()
3278 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3279 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3280 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3281 dev[1].request("WPS_CANCEL")
3282 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3283 dev[2].request("WPS_CANCEL")
3284 if i % 4 == 1:
3285 time.sleep(1)
3286 else:
3287 time.sleep(0.1)
3288
3289 hapd.request("WPS_PIN any 12345670")
3290 dev[1].dump_monitor()
3291 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3292 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3293 if ev is None:
3294 raise Exception("WPS success not reported")
3295
3296 # Close the WPS ER HTTP server without fetching all the pending events.
3297 # This tests hostapd code path that clears subscription and the remaining
3298 # event queue when the interface is deinitialized.
3299 server.handle_request()
3300 server.server_close()
3301
3302 dev[1].wait_connected()
3303
b2047531
JM
3304def test_ap_wps_upnp_http_proto(dev, apdev):
3305 """WPS AP and UPnP/HTTP protocol testing"""
3306 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3307 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3308
3309 location = ssdp_get_location(ap_uuid)
3310
3311 url = urlparse.urlparse(location)
81f8e7e9 3312 conn = httplib.HTTPConnection(url.netloc, timeout=0.2)
b2047531
JM
3313 #conn.set_debuglevel(1)
3314
3315 conn.request("HEAD", "hello")
3316 resp = conn.getresponse()
3317 if resp.status != 501:
3318 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3319 conn.close()
3320
3321 for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
3322 try:
3323 conn.request(cmd, "hello")
3324 resp = conn.getresponse()
3325 except Exception, e:
3326 pass
3327 conn.close()
3328
3329 headers = { "Content-Length": 'abc' }
3330 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3331 try:
3332 resp = conn.getresponse()
3333 except Exception, e:
3334 pass
3335 conn.close()
3336
3337 headers = { "Content-Length": '-10' }
3338 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3339 try:
3340 resp = conn.getresponse()
3341 except Exception, e:
3342 pass
3343 conn.close()
3344
3345 headers = { "Content-Length": '10000000000000' }
3346 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3347 try:
3348 resp = conn.getresponse()
3349 except Exception, e:
3350 pass
3351 conn.close()
3352
3353 headers = { "Transfer-Encoding": 'abc' }
3354 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3355 resp = conn.getresponse()
3356 if resp.status != 501:
3357 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3358 conn.close()
3359
3360 headers = { "Transfer-Encoding": 'chunked' }
3361 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3362 resp = conn.getresponse()
3363 if resp.status != 501:
3364 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3365 conn.close()
3366
3367 # Too long a header
3368 conn.request("HEAD", 5000 * 'A')
3369 try:
3370 resp = conn.getresponse()
3371 except Exception, e:
3372 pass
3373 conn.close()
3374
3375 # Long URL but within header length limits
3376 conn.request("HEAD", 3000 * 'A')
3377 resp = conn.getresponse()
3378 if resp.status != 501:
3379 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3380 conn.close()
3381
3382 headers = { "Content-Length": '20' }
3383 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3384 try:
3385 resp = conn.getresponse()
3386 except Exception, e:
3387 pass
3388 conn.close()
3389
3390 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
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.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3397 try:
3398 resp = conn.getresponse()
3399 except Exception, e:
3400 pass
3401 conn.close()
3402
3403def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3404 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3405 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 3406 add_ssdp_ap(apdev[0], ap_uuid)
b2047531
JM
3407
3408 location = ssdp_get_location(ap_uuid)
3409
3410 url = urlparse.urlparse(location)
3411 conn = httplib.HTTPConnection(url.netloc)
3412 #conn.set_debuglevel(1)
3413
3414 headers = { "Transfer-Encoding": 'chunked' }
3415 conn.request("POST", "hello",
3416 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3417 headers)
3418 resp = conn.getresponse()
3419 if resp.status != 404:
5c267d71 3420 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3421 conn.close()
3422
3423 conn.putrequest("POST", "hello")
3424 conn.putheader('Transfer-Encoding', 'chunked')
3425 conn.endheaders()
3426 conn.send("a\r\nabcdefghij\r\n")
3427 time.sleep(0.1)
3428 conn.send("2\r\nkl\r\n")
3429 conn.send("0\r\n\r\n")
3430 resp = conn.getresponse()
3431 if resp.status != 404:
5c267d71 3432 raise Exception("Unexpected HTTP response: %d" % resp.status)
b2047531
JM
3433 conn.close()
3434
3435 conn.putrequest("POST", "hello")
3436 conn.putheader('Transfer-Encoding', 'chunked')
3437 conn.endheaders()
3438 completed = False
3439 try:
3440 for i in range(20000):
3441 conn.send("1\r\nZ\r\n")
3442 conn.send("0\r\n\r\n")
3443 resp = conn.getresponse()
3444 completed = True
3445 except Exception, e:
3446 pass
3447 conn.close()
3448 if completed:
3449 raise Exception("Too long chunked request did not result in connection reset")
3450
3451 headers = { "Transfer-Encoding": 'chunked' }
3452 conn.request("POST", "hello", "80000000\r\na", headers)
3453 try:
3454 resp = conn.getresponse()
3455 except Exception, e:
3456 pass
3457 conn.close()
3458
3459 conn.request("POST", "hello", "10000000\r\na", headers)
3460 try:
3461 resp = conn.getresponse()
3462 except Exception, e:
3463 pass
3464 conn.close()
3465
9fd6804d 3466@remote_compatible
d352c407
JM
3467def test_ap_wps_disabled(dev, apdev):
3468 """WPS operations while WPS is disabled"""
3469 ssid = "test-wps-disabled"
6f334bf7 3470 hapd = hostapd.add_ap(apdev[0], { "ssid": ssid })
d352c407
JM
3471 if "FAIL" not in hapd.request("WPS_PBC"):
3472 raise Exception("WPS_PBC succeeded unexpectedly")
3473 if "FAIL" not in hapd.request("WPS_CANCEL"):
3474 raise Exception("WPS_CANCEL succeeded unexpectedly")
a0fd2ae6
JM
3475
3476def test_ap_wps_mixed_cred(dev, apdev):
3477 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3478 ssid = "test-wps-wep"
6f334bf7
JD
3479 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3480 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" }
3481 hapd = hostapd.add_ap(apdev[0], params)
a0fd2ae6 3482 hapd.request("WPS_PBC")
33d0b157
JM
3483 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3484 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
9ed53f5e 3485 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
a0fd2ae6
JM
3486 if ev is None:
3487 raise Exception("WPS-SUCCESS event timed out")
3488 nets = dev[0].list_networks()
3489 if len(nets) != 1:
3490 raise Exception("Unexpected number of network blocks")
3491 id = nets[0]['id']
3492 proto = dev[0].get_network(id, "proto")
3493 if proto != "WPA RSN":
3494 raise Exception("Unexpected merged proto field value: " + proto)
3495 pairwise = dev[0].get_network(id, "pairwise")
72a8e30b 3496 if pairwise != "CCMP TKIP" and pairwise != "CCMP GCMP TKIP":
a0fd2ae6 3497 raise Exception("Unexpected merged pairwise field value: " + pairwise)
e5a79e3f 3498
9fd6804d 3499@remote_compatible
e5a79e3f
JM
3500def test_ap_wps_while_connected(dev, apdev):
3501 """WPS PBC provisioning while connected to another AP"""
3502 ssid = "test-wps-conf"
6f334bf7
JD
3503 hapd = hostapd.add_ap(apdev[0],
3504 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3505 "wpa_passphrase": "12345678", "wpa": "2",
3506 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3507
8b8a1864 3508 hostapd.add_ap(apdev[1], { "ssid": "open" })
e5a79e3f
JM
3509 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3510
3511 logger.info("WPS provisioning step")
3512 hapd.request("WPS_PBC")
3513 dev[0].dump_monitor()
33d0b157 3514 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3515 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3516 status = dev[0].get_status()
3517 if status['bssid'] != apdev[0]['bssid']:
3518 raise Exception("Unexpected BSSID")
3519
9fd6804d 3520@remote_compatible
e5a79e3f
JM
3521def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3522 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3523 ssid = "test-wps-conf"
6f334bf7
JD
3524 hapd = hostapd.add_ap(apdev[0],
3525 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3526 "wpa_passphrase": "12345678", "wpa": "2",
3527 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
e5a79e3f 3528
8b8a1864 3529 hostapd.add_ap(apdev[1], { "ssid": "open" })
e5a79e3f
JM
3530
3531 try:
3532 dev[0].request("STA_AUTOCONNECT 0")
3533 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3534
3535 logger.info("WPS provisioning step")
3536 hapd.request("WPS_PBC")
3537 dev[0].dump_monitor()
33d0b157 3538 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5f35a5e2 3539 dev[0].wait_connected(timeout=30)
e5a79e3f
JM
3540 status = dev[0].get_status()
3541 if status['bssid'] != apdev[0]['bssid']:
3542 raise Exception("Unexpected BSSID")
3543 finally:
3544 dev[0].request("STA_AUTOCONNECT 1")
3f08d1cd 3545
9fd6804d 3546@remote_compatible
3f08d1cd
JM
3547def test_ap_wps_from_event(dev, apdev):
3548 """WPS PBC event on AP to enable PBC"""
3549 ssid = "test-wps-conf"
8b8a1864 3550 hapd = hostapd.add_ap(apdev[0],
3f08d1cd
JM
3551 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3552 "wpa_passphrase": "12345678", "wpa": "2",
3553 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
33d0b157 3554 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3f08d1cd 3555 dev[0].dump_monitor()
33d0b157
JM
3556 hapd.dump_monitor()
3557 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3f08d1cd
JM
3558
3559 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3560 if ev is None:
3561 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3562 vals = ev.split(' ')
3563 if vals[1] != dev[0].p2p_interface_addr():
3564 raise Exception("Unexpected enrollee address: " + vals[1])
3565 if vals[5] != '4':
3566 raise Exception("Unexpected Device Password Id: " + vals[5])
3567 hapd.request("WPS_PBC")
5f35a5e2 3568 dev[0].wait_connected(timeout=30)
1531402e
JM
3569
3570def test_ap_wps_ap_scan_2(dev, apdev):
3571 """AP_SCAN 2 for WPS"""
3572 ssid = "test-wps-conf"
8b8a1864 3573 hapd = hostapd.add_ap(apdev[0],
1531402e
JM
3574 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3575 "wpa_passphrase": "12345678", "wpa": "2",
3576 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3577 hapd.request("WPS_PBC")
3578
3579 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3580 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
4b9d79b6 3581 wpas.dump_monitor()
1531402e
JM
3582
3583 if "OK" not in wpas.request("AP_SCAN 2"):
3584 raise Exception("Failed to set AP_SCAN 2")
3585
e51c8b2e 3586 wpas.flush_scan_cache()
33d0b157 3587 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
4b9d79b6 3588 wpas.dump_monitor()
33d0b157 3589 wpas.request("WPS_PBC " + apdev[0]['bssid'])
1531402e
JM
3590 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3591 if ev is None:
3592 raise Exception("WPS-SUCCESS event timed out")
5f35a5e2 3593 wpas.wait_connected(timeout=30)
4b9d79b6 3594 wpas.dump_monitor()
1531402e
JM
3595 wpas.request("DISCONNECT")
3596 wpas.request("BSS_FLUSH 0")
3597 wpas.dump_monitor()
3598 wpas.request("REASSOCIATE")
5f35a5e2 3599 wpas.wait_connected(timeout=30)
4b9d79b6 3600 wpas.dump_monitor()
a08fdb17 3601
9fd6804d 3602@remote_compatible
a08fdb17
JM
3603def test_ap_wps_eapol_workaround(dev, apdev):
3604 """EAPOL workaround code path for 802.1X header length mismatch"""
3605 ssid = "test-wps"
6f334bf7
JD
3606 hapd = hostapd.add_ap(apdev[0],
3607 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
a08fdb17
JM
3608 bssid = apdev[0]['bssid']
3609 hapd.request("SET ext_eapol_frame_io 1")
3610 dev[0].request("SET ext_eapol_frame_io 1")
3611 hapd.request("WPS_PBC")
3612 dev[0].request("WPS_PBC")
3613
3614 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3615 if ev is None:
3616 raise Exception("Timeout on EAPOL-TX from hostapd")
3617
3618 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3619 if "OK" not in res:
3620 raise Exception("EAPOL_RX to wpa_supplicant failed")
46dea617
JM
3621
3622def test_ap_wps_iteration(dev, apdev):
3623 """WPS PIN and iterate through APs without selected registrar"""
3624 ssid = "test-wps-conf"
8b8a1864 3625 hapd = hostapd.add_ap(apdev[0],
46dea617
JM
3626 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3627 "wpa_passphrase": "12345678", "wpa": "2",
3628 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3629
3630 ssid2 = "test-wps-conf2"
8b8a1864 3631 hapd2 = hostapd.add_ap(apdev[1],
46dea617
JM
3632 { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
3633 "wpa_passphrase": "12345678", "wpa": "2",
3634 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3635
3636 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3637 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3638 dev[0].dump_monitor()
3639 pin = dev[0].request("WPS_PIN any")
3640
3641 # Wait for iteration through all WPS APs to happen before enabling any
3642 # Registrar.
3643 for i in range(2):
3644 ev = dev[0].wait_event(["Associated with"], timeout=30)
3645 if ev is None:
3646 raise Exception("No association seen")
3647 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3648 if ev is None:
3649 raise Exception("No M2D from AP")
3650 dev[0].wait_disconnected()
3651
3652 # Verify that each AP requested PIN
3653 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3654 if ev is None:
3655 raise Exception("No WPS-PIN-NEEDED event from AP")
3656 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3657 if ev is None:
3658 raise Exception("No WPS-PIN-NEEDED event from AP2")
3659
3660 # Provide PIN to one of the APs and verify that connection gets formed
3661 hapd.request("WPS_PIN any " + pin)
3662 dev[0].wait_connected(timeout=30)
2272f5aa
JM
3663
3664def test_ap_wps_iteration_error(dev, apdev):
3665 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3666 ssid = "test-wps-conf-pin"
8b8a1864 3667 hapd = hostapd.add_ap(apdev[0],
2272f5aa
JM
3668 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3669 "wpa_passphrase": "12345678", "wpa": "2",
3670 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3671 "wps_independent": "1" })
3672 hapd.request("SET ext_eapol_frame_io 1")
3673 bssid = apdev[0]['bssid']
3674 pin = dev[0].wps_read_pin()
3675 dev[0].request("WPS_PIN any " + pin)
3676
3677 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3678 if ev is None:
3679 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3680 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3681
3682 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3683 if ev is None:
3684 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3685 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3686 if ev is None:
3687 raise Exception("No CTRL-EVENT-EAP-STARTED")
3688
3689 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3690 # a case with an incorrectly behaving WPS AP.
3691
3692 # Start the real target AP and activate registrar on it.
8b8a1864 3693 hapd2 = hostapd.add_ap(apdev[1],
2272f5aa
JM
3694 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3695 "wpa_passphrase": "12345678", "wpa": "2",
3696 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3697 "wps_independent": "1" })
3698 hapd2.request("WPS_PIN any " + pin)
3699
3700 dev[0].wait_disconnected(timeout=15)
3701 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3702 if ev is None:
3703 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3704 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3705 if ev is None:
3706 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3707 dev[0].wait_connected(timeout=15)
d6f6a86a 3708
9fd6804d 3709@remote_compatible
d6f6a86a
JM
3710def test_ap_wps_priority(dev, apdev):
3711 """WPS PIN provisioning with configured AP and wps_priority"""
3712 ssid = "test-wps-conf-pin"
6f334bf7
JD
3713 hapd = hostapd.add_ap(apdev[0],
3714 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3715 "wpa_passphrase": "12345678", "wpa": "2",
3716 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
d6f6a86a
JM
3717 logger.info("WPS provisioning step")
3718 pin = dev[0].wps_read_pin()
3719 hapd.request("WPS_PIN any " + pin)
3720 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3721 dev[0].dump_monitor()
3722 try:
3723 dev[0].request("SET wps_priority 6")
3724 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3725 dev[0].wait_connected(timeout=30)
3726 netw = dev[0].list_networks()
3727 prio = dev[0].get_network(netw[0]['id'], 'priority')
3728 if prio != '6':
3729 raise Exception("Unexpected network priority: " + prio)
3730 finally:
3731 dev[0].request("SET wps_priority 0")
2c3a0190 3732
9fd6804d 3733@remote_compatible
df1d01cf
JM
3734def test_ap_wps_and_non_wps(dev, apdev):
3735 """WPS and non-WPS AP in single hostapd process"""
3736 params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
8b8a1864 3737 hapd = hostapd.add_ap(apdev[0], params)
df1d01cf
JM
3738
3739 params = { "ssid": "no wps" }
8b8a1864 3740 hapd2 = hostapd.add_ap(apdev[1], params)
df1d01cf
JM
3741
3742 appin = hapd.request("WPS_AP_PIN random")
3743 if "FAIL" in appin:
3744 raise Exception("Could not generate random AP PIN")
3745 if appin not in hapd.request("WPS_AP_PIN get"):
3746 raise Exception("Could not fetch current AP PIN")
3747
3748 if "FAIL" in hapd.request("WPS_PBC"):
3749 raise Exception("WPS_PBC failed")
3750 if "FAIL" in hapd.request("WPS_CANCEL"):
3751 raise Exception("WPS_CANCEL failed")
3752
2c3a0190
JM
3753def test_ap_wps_init_oom(dev, apdev):
3754 """Initial AP configuration and OOM during PSK generation"""
3755 ssid = "test-wps"
3756 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
8b8a1864 3757 hapd = hostapd.add_ap(apdev[0], params)
2c3a0190 3758
5b52e1ad 3759 with alloc_fail(hapd, 1, "base64_gen_encode;?base64_encode;wps_build_cred"):
2c3a0190
JM
3760 pin = dev[0].wps_read_pin()
3761 hapd.request("WPS_PIN any " + pin)
3762 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3763 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3764 dev[0].wait_disconnected()
3765
3766 hapd.request("WPS_PIN any " + pin)
3767 dev[0].wait_connected(timeout=30)
ccf4d764 3768
9fd6804d 3769@remote_compatible
ccf4d764
JM
3770def test_ap_wps_er_oom(dev, apdev):
3771 """WPS ER OOM in XML processing"""
3772 try:
3773 _test_ap_wps_er_oom(dev, apdev)
3774 finally:
3775 dev[0].request("WPS_ER_STOP")
3776 dev[1].request("WPS_CANCEL")
3777 dev[0].request("DISCONNECT")
3778
3779def _test_ap_wps_er_oom(dev, apdev):
3780 ssid = "wps-er-ap-config"
3781 ap_pin = "12345670"
3782 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
8b8a1864 3783 hostapd.add_ap(apdev[0],
ccf4d764
JM
3784 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3785 "wpa_passphrase": "12345678", "wpa": "2",
3786 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3787 "device_name": "Wireless AP", "manufacturer": "Company",
3788 "model_name": "WAP", "model_number": "123",
3789 "serial_number": "12345", "device_type": "6-0050F204-1",
3790 "os_version": "01020300",
3791 "config_methods": "label push_button",
3792 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3793
3794 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3795
5b52e1ad
JM
3796 with alloc_fail(dev[0], 1,
3797 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
ccf4d764
JM
3798 dev[0].request("WPS_ER_START ifname=lo")
3799 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3800 if ev is not None:
3801 raise Exception("Unexpected AP discovery")
3802
3803 dev[0].request("WPS_ER_STOP")
3804 dev[0].request("WPS_ER_START ifname=lo")
3805 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3806 if ev is None:
3807 raise Exception("AP discovery timed out")
3808
3809 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
5b52e1ad
JM
3810 with alloc_fail(dev[0], 1,
3811 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
ccf4d764
JM
3812 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3813 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3814 if ev is None:
3815 raise Exception("PBC scan failed")
3816 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3817 if ev is None:
3818 raise Exception("Enrollee discovery timed out")
2602a2ff 3819
9fd6804d 3820@remote_compatible
c965ae03
JM
3821def test_ap_wps_er_init_oom(dev, apdev):
3822 """WPS ER and OOM during init"""
3823 try:
3824 _test_ap_wps_er_init_oom(dev, apdev)
3825 finally:
3826 dev[0].request("WPS_ER_STOP")
3827
3828def _test_ap_wps_er_init_oom(dev, apdev):
3829 with alloc_fail(dev[0], 1, "wps_er_init"):
3830 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3831 raise Exception("WPS_ER_START succeeded during OOM")
3832 with alloc_fail(dev[0], 1, "http_server_init"):
3833 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3834 raise Exception("WPS_ER_START succeeded during OOM")
3835 with alloc_fail(dev[0], 2, "http_server_init"):
3836 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3837 raise Exception("WPS_ER_START succeeded during OOM")
9b35afd6 3838 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
c965ae03
JM
3839 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3840 raise Exception("WPS_ER_START succeeded during OOM")
3841 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3842 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3843 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3844
9fd6804d 3845@remote_compatible
07536b18
JM
3846def test_ap_wps_er_init_fail(dev, apdev):
3847 """WPS ER init failure"""
3848 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3849 dev[0].request("WPS_ER_STOP")
3850 raise Exception("WPS_ER_START with non-existing ifname succeeded")
3851
2602a2ff
JM
3852def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3853 """WPS events and wpa_cli action script"""
8936b095
JM
3854 logdir = os.path.abspath(test_params['logdir'])
3855 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3856 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3857 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
2602a2ff
JM
3858
3859 with open(actionfile, 'w') as f:
3860 f.write('#!/bin/sh\n')
3861 f.write('echo $* >> %s\n' % logfile)
3862 # Kill the process and wait some time before returning to allow all the
3863 # pending events to be processed with some of this happening after the
3864 # eloop SIGALRM signal has been scheduled.
3865 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3866
8936b095
JM
3867 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3868 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
2602a2ff
JM
3869
3870 ssid = "test-wps-conf"
6f334bf7
JD
3871 hapd = hostapd.add_ap(apdev[0],
3872 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3873 "wpa_passphrase": "12345678", "wpa": "2",
3874 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2602a2ff
JM
3875
3876 prg = os.path.join(test_params['logdir'],
3877 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3878 if not os.path.exists(prg):
3879 prg = '../../wpa_supplicant/wpa_cli'
3880 arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
3881 subprocess.call(arg)
3882
3883 arg = [ 'ps', 'ax' ]
3884 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3885 out = cmd.communicate()[0]
3886 cmd.wait()
3887 logger.debug("Processes:\n" + out)
3888 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3889 raise Exception("Did not see wpa_cli running")
3890
3891 hapd.request("WPS_PIN any 12345670")
3892 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3893 dev[0].dump_monitor()
3894 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3895 dev[0].wait_connected(timeout=30)
3896
3897 for i in range(30):
3898 if not os.path.exists(pidfile):
3899 break
3900 time.sleep(0.1)
3901
3902 if not os.path.exists(logfile):
3903 raise Exception("wpa_cli action results file not found")
3904 with open(logfile, 'r') as f:
3905 res = f.read()
3906 if "WPS-SUCCESS" not in res:
3907 raise Exception("WPS-SUCCESS event not seen in action file")
3908
3909 arg = [ 'ps', 'ax' ]
3910 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3911 out = cmd.communicate()[0]
3912 cmd.wait()
3913 logger.debug("Remaining processes:\n" + out)
3914 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3915 raise Exception("wpa_cli still running")
3916
3917 if os.path.exists(pidfile):
3918 raise Exception("PID file not removed")
c965ae03
JM
3919
3920def test_ap_wps_er_ssdp_proto(dev, apdev):
3921 """WPS ER SSDP protocol testing"""
3922 try:
3923 _test_ap_wps_er_ssdp_proto(dev, apdev)
3924 finally:
3925 dev[0].request("WPS_ER_STOP")
3926
3927def _test_ap_wps_er_ssdp_proto(dev, apdev):
3928 socket.setdefaulttimeout(1)
3929 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3930 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3931 sock.bind(("239.255.255.250", 1900))
3932 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3933 raise Exception("Invalid filter accepted")
3934 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3935 raise Exception("WPS_ER_START with filter failed")
3936 (msg,addr) = sock.recvfrom(1000)
3937 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3938 if "M-SEARCH" not in msg:
3939 raise Exception("Not an M-SEARCH")
3940 sock.sendto("FOO", addr)
3941 time.sleep(0.1)
3942 dev[0].request("WPS_ER_STOP")
3943
3944 dev[0].request("WPS_ER_START ifname=lo")
3945 (msg,addr) = sock.recvfrom(1000)
3946 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3947 if "M-SEARCH" not in msg:
3948 raise Exception("Not an M-SEARCH")
3949 sock.sendto("FOO", addr)
3950 sock.sendto("HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3951 sock.sendto("HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3952 sock.sendto("HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3953 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
3954 sock.sendto("HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
3955 sock.sendto("HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3956 sock.sendto("HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3957 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
3958 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
3959 sock.sendto("HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
3960 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3961 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)
3962 sock.sendto("HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
3963 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3964 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)
3965 time.sleep(0.1)
3966 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
3967 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)
3968 time.sleep(0.1)
3969
3970 # Add an AP with bogus URL
3971 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)
3972 # Update timeout on AP without updating URL
3973 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)
3974 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3975 if ev is None:
3976 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3977
3978 # Add an AP with a valid URL (but no server listing to it)
3979 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)
3980 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
3981 if ev is None:
3982 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
3983
3984 sock.close()
3985
3986wps_event_url = None
3987
6aaa661a
JM
3988def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
3989 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4c3ae1c0 3990 payload = '''<?xml version="1.0"?>
c965ae03
JM
3991<root xmlns="urn:schemas-upnp-org:device-1-0">
3992<specVersion>
3993<major>1</major>
3994<minor>0</minor>
3995</specVersion>
3996<device>
3997<deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
3998<friendlyName>WPS Access Point</friendlyName>
3999<manufacturer>Company</manufacturer>
4000<modelName>WAP</modelName>
4001<modelNumber>123</modelNumber>
4002<serialNumber>12345</serialNumber>
6aaa661a
JM
4003'''
4004 if udn:
4005 payload += '<UDN>' + udn + '</UDN>'
4006 payload += '''<serviceList>
c965ae03
JM
4007<service>
4008<serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
4009<serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
4010<SCPDURL>wps_scpd.xml</SCPDURL>
4c3ae1c0 4011'''
6aaa661a
JM
4012 if controlURL:
4013 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4c3ae1c0 4014 if eventSubURL:
6aaa661a 4015 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4c3ae1c0 4016 payload += '''</service>
c965ae03
JM
4017</serviceList>
4018</device>
4019</root>
4020'''
4c3ae1c0
JM
4021 hdr = 'HTTP/1.1 200 OK\r\n' + \
4022 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4023 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4024 'Connection: close\r\n' + \
4025 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4026 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4027 return hdr + payload
4028
6aaa661a 4029def gen_wps_control(payload_override=None):
4c3ae1c0 4030 payload = '''<?xml version="1.0"?>
c965ae03
JM
4031<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4032<s:Body>
4033<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4034<NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
4035Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
4036+FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
40377zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
4038KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
4039AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
4040AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
4041AAYANyoAASA=
4042</NewDeviceInfo>
4043</u:GetDeviceInfoResponse>
4044</s:Body>
4045</s:Envelope>
4046'''
6aaa661a
JM
4047 if payload_override:
4048 payload = payload_override
4c3ae1c0
JM
4049 hdr = 'HTTP/1.1 200 OK\r\n' + \
4050 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4051 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4052 'Connection: close\r\n' + \
4053 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4054 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4055 return hdr + payload
4056
6aaa661a 4057def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4c3ae1c0
JM
4058 payload = ""
4059 hdr = 'HTTP/1.1 200 OK\r\n' + \
4060 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4061 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4062 'Connection: close\r\n' + \
6aaa661a
JM
4063 'Content-Length: ' + str(len(payload)) + '\r\n'
4064 if sid:
4065 hdr += 'SID: ' + sid + '\r\n'
4066 hdr += 'Timeout: Second-1801\r\n' + \
4c3ae1c0
JM
4067 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4068 return hdr + payload
4069
4070class WPSAPHTTPServer(SocketServer.StreamRequestHandler):
4071 def handle(self):
4072 data = self.rfile.readline().strip()
4073 logger.info("HTTP server received: " + data)
4074 while True:
4075 hdr = self.rfile.readline().strip()
4076 if len(hdr) == 0:
4077 break
4078 logger.info("HTTP header: " + hdr)
4079 if "CALLBACK:" in hdr:
4080 global wps_event_url
4081 wps_event_url = hdr.split(' ')[1].strip('<>')
4082
4083 if "GET /foo.xml" in data:
6aaa661a
JM
4084 self.handle_upnp_info()
4085 elif "POST /wps_control" in data:
4086 self.handle_wps_control()
4087 elif "SUBSCRIBE /wps_event" in data:
4088 self.handle_wps_event()
24b7f282
JM
4089 else:
4090 self.handle_others(data)
6aaa661a
JM
4091
4092 def handle_upnp_info(self):
4093 self.wfile.write(gen_upnp_info())
4c3ae1c0 4094
6aaa661a
JM
4095 def handle_wps_control(self):
4096 self.wfile.write(gen_wps_control())
c965ae03 4097
6aaa661a
JM
4098 def handle_wps_event(self):
4099 self.wfile.write(gen_wps_event())
c965ae03 4100
24b7f282
JM
4101 def handle_others(self, data):
4102 logger.info("Ignore HTTP request: " + data)
4103
4c3ae1c0
JM
4104class MyTCPServer(SocketServer.TCPServer):
4105 def __init__(self, addr, handler):
4106 self.allow_reuse_address = True
4107 SocketServer.TCPServer.__init__(self, addr, handler)
c965ae03 4108
24b7f282
JM
4109def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4110 location_url=None):
c965ae03
JM
4111 socket.setdefaulttimeout(1)
4112 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4113 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4114 sock.bind(("239.255.255.250", 1900))
4c3ae1c0 4115 dev.request("WPS_ER_START ifname=lo")
24b7f282
JM
4116 for i in range(100):
4117 (msg,addr) = sock.recvfrom(1000)
4118 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4119 if "M-SEARCH" in msg:
4120 break
4121 if not wait_m_search:
4122 raise Exception("Not an M-SEARCH")
4123 if i == 99:
4124 raise Exception("No M-SEARCH seen")
c965ae03
JM
4125
4126 # Add an AP with a valid URL and server listing to it
4c3ae1c0 4127 server = MyTCPServer(("127.0.0.1", 12345), http_server)
24b7f282
JM
4128 if not location_url:
4129 location_url = 'http://127.0.0.1:12345/foo.xml'
4130 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 4131 server.timeout = 1
4c3ae1c0
JM
4132 return server,sock
4133
4134def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4135 sock.close()
4136 server.server_close()
4137
4138 if on_alloc_fail:
4139 done = False
4140 for i in range(50):
4141 res = dev.request("GET_ALLOC_FAIL")
4142 if res.startswith("0:"):
4143 done = True
4144 break
4145 time.sleep(0.1)
4146 if not done:
4147 raise Exception("No allocation failure reported")
4148 else:
4149 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4150 if ev is None:
4151 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4152 dev.request("WPS_ER_STOP")
4153
24b7f282 4154def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
6aaa661a
JM
4155 try:
4156 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
24b7f282 4157 server,sock = wps_er_start(dev, handler, location_url=location_url)
6aaa661a
JM
4158 global wps_event_url
4159 wps_event_url = None
4160 server.handle_request()
4161 server.handle_request()
4162 server.handle_request()
4163 server.server_close()
4164 if no_event_url:
4165 if wps_event_url:
4166 raise Exception("Received event URL unexpectedly")
4167 return
4168 if wps_event_url is None:
4169 raise Exception("Did not get event URL")
4170 logger.info("Event URL: " + wps_event_url)
4171 finally:
24b7f282 4172 dev.request("WPS_ER_STOP")
6aaa661a 4173
18478107 4174def send_wlanevent(url, uuid, data, no_response=False):
6aaa661a
JM
4175 conn = httplib.HTTPConnection(url.netloc)
4176 payload = '''<?xml version="1.0" encoding="utf-8"?>
4177<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4178<e:property><STAStatus>1</STAStatus></e:property>
4179<e:property><APStatus>1</APStatus></e:property>
4180<e:property><WLANEvent>'''
4181 payload += base64.b64encode(data)
4182 payload += '</WLANEvent></e:property></e:propertyset>'
4183 headers = { "Content-type": 'text/xml; charset="utf-8"',
4184 "Server": "Unspecified, UPnP/1.0, Unspecified",
4185 "HOST": url.netloc,
4186 "NT": "upnp:event",
4187 "SID": "uuid:" + uuid,
4188 "SEQ": "0",
4189 "Content-Length": str(len(payload)) }
4190 conn.request("NOTIFY", url.path, payload, headers)
18478107
JM
4191 if no_response:
4192 try:
4193 conn.getresponse()
4194 except Exception, e:
4195 pass
4196 return
6aaa661a
JM
4197 resp = conn.getresponse()
4198 if resp.status != 200:
4199 raise Exception("Unexpected HTTP response: %d" % resp.status)
4200
4c3ae1c0
JM
4201def test_ap_wps_er_http_proto(dev, apdev):
4202 """WPS ER HTTP protocol testing"""
4203 try:
4204 _test_ap_wps_er_http_proto(dev, apdev)
4205 finally:
4206 dev[0].request("WPS_ER_STOP")
4207
4208def _test_ap_wps_er_http_proto(dev, apdev):
4209 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
6aaa661a 4210 server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
c965ae03
JM
4211 global wps_event_url
4212 wps_event_url = None
4213 server.handle_request()
4214 server.handle_request()
4215 server.handle_request()
4216 server.server_close()
4217 if wps_event_url is None:
4218 raise Exception("Did not get event URL")
4219 logger.info("Event URL: " + wps_event_url)
4220
4221 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4222 if ev is None:
4223 raise Exception("No WPS-ER-AP-ADD event")
4224 if uuid not in ev:
4225 raise Exception("UUID mismatch")
4226
4227 sock.close()
4228
4229 logger.info("Valid Probe Request notification")
4230 url = urlparse.urlparse(wps_event_url)
4231 conn = httplib.HTTPConnection(url.netloc)
4232 payload = '''<?xml version="1.0" encoding="utf-8"?>
4233<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4234<e:property><STAStatus>1</STAStatus></e:property>
4235<e:property><APStatus>1</APStatus></e:property>
4236<e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4237EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4238RGV2aWNlIEEQSQAGADcqAAEg
4239</WLANEvent></e:property>
4240</e:propertyset>
4241'''
4242 headers = { "Content-type": 'text/xml; charset="utf-8"',
4243 "Server": "Unspecified, UPnP/1.0, Unspecified",
4244 "HOST": url.netloc,
4245 "NT": "upnp:event",
4246 "SID": "uuid:" + uuid,
4247 "SEQ": "0",
4248 "Content-Length": str(len(payload)) }
4249 conn.request("NOTIFY", url.path, payload, headers)
4250 resp = conn.getresponse()
4251 if resp.status != 200:
4252 raise Exception("Unexpected HTTP response: %d" % resp.status)
4253
4254 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4255 if ev is None:
4256 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4257 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4258 raise Exception("No Enrollee UUID match")
4259
4260 logger.info("Incorrect event URL AP id")
4261 conn = httplib.HTTPConnection(url.netloc)
4262 conn.request("NOTIFY", url.path + '123', payload, headers)
4263 resp = conn.getresponse()
4264 if resp.status != 404:
4265 raise Exception("Unexpected HTTP response: %d" % resp.status)
4266
4267 logger.info("Missing AP id")
4268 conn = httplib.HTTPConnection(url.netloc)
4269 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4270 payload, headers)
4271 time.sleep(0.1)
4272
4273 logger.info("Incorrect event URL event id")
4274 conn = httplib.HTTPConnection(url.netloc)
4275 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4276 time.sleep(0.1)
4277
4278 logger.info("Incorrect event URL prefix")
4279 conn = httplib.HTTPConnection(url.netloc)
4280 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4281 resp = conn.getresponse()
4282 if resp.status != 404:
4283 raise Exception("Unexpected HTTP response: %d" % resp.status)
4284
4285 logger.info("Unsupported request")
4286 conn = httplib.HTTPConnection(url.netloc)
4287 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4288 resp = conn.getresponse()
4289 if resp.status != 501:
4290 raise Exception("Unexpected HTTP response: %d" % resp.status)
4291
4292 logger.info("Unsupported request and OOM")
4293 with alloc_fail(dev[0], 1, "wps_er_http_req"):
4294 conn = httplib.HTTPConnection(url.netloc)
4295 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4296 time.sleep(0.5)
4c3ae1c0 4297
6aaa661a
JM
4298 logger.info("Too short WLANEvent")
4299 data = '\x00'
4300 send_wlanevent(url, uuid, data)
4301
4302 logger.info("Invalid WLANEventMAC")
4303 data = '\x00qwertyuiopasdfghjklzxcvbnm'
4304 send_wlanevent(url, uuid, data)
4305
4306 logger.info("Unknown WLANEventType")
4307 data = '\xff02:00:00:00:00:00'
4308 send_wlanevent(url, uuid, data)
4309
4310 logger.info("Probe Request notification without any attributes")
4311 data = '\x0102:00:00:00:00:00'
4312 send_wlanevent(url, uuid, data)
4313
4314 logger.info("Probe Request notification with invalid attribute")
4315 data = '\x0102:00:00:00:00:00\xff'
4316 send_wlanevent(url, uuid, data)
4317
4318 logger.info("EAP message without any attributes")
4319 data = '\x0202:00:00:00:00:00'
4320 send_wlanevent(url, uuid, data)
4321
4322 logger.info("EAP message with invalid attribute")
4323 data = '\x0202:00:00:00:00:00\xff'
4324 send_wlanevent(url, uuid, data)
4325
4326 logger.info("EAP message from new STA and not M1")
4327 data = '\x0202:ff:ff:ff:ff:ff' + '\x10\x22\x00\x01\x05'
4328 send_wlanevent(url, uuid, data)
4329
4330 logger.info("EAP message: M1")
4331 data = '\x0202:00:00:00:00:00'
4332 data += '\x10\x22\x00\x01\x04'
4333 data += '\x10\x47\x00\x10' + 16*'\x00'
4334 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4335 data += '\x10\x1a\x00\x10' + 16*'\x00'
4336 data += '\x10\x32\x00\xc0' + 192*'\x00'
4337 data += '\x10\x04\x00\x02\x00\x00'
4338 data += '\x10\x10\x00\x02\x00\x00'
4339 data += '\x10\x0d\x00\x01\x00'
4340 data += '\x10\x08\x00\x02\x00\x00'
4341 data += '\x10\x44\x00\x01\x00'
4342 data += '\x10\x21\x00\x00'
4343 data += '\x10\x23\x00\x00'
4344 data += '\x10\x24\x00\x00'
4345 data += '\x10\x42\x00\x00'
4346 data += '\x10\x54\x00\x08' + 8*'\x00'
4347 data += '\x10\x11\x00\x00'
4348 data += '\x10\x3c\x00\x01\x00'
4349 data += '\x10\x02\x00\x02\x00\x00'
4350 data += '\x10\x12\x00\x02\x00\x00'
4351 data += '\x10\x09\x00\x02\x00\x00'
4352 data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4353 m1 = data
4354 send_wlanevent(url, uuid, data)
4355
4356 logger.info("EAP message: WSC_ACK")
4357 data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0d'
4358 send_wlanevent(url, uuid, data)
4359
4360 logger.info("EAP message: M1")
4361 send_wlanevent(url, uuid, m1)
4362
4363 logger.info("EAP message: WSC_NACK")
4364 data = '\x0202:00:00:00:00:00' + '\x10\x22\x00\x01\x0e'
4365 send_wlanevent(url, uuid, data)
4366
4367 logger.info("EAP message: M1 - Too long attribute values")
4368 data = '\x0202:00:00:00:00:00'
4369 data += '\x10\x11\x00\x21' + 33*'\x00'
4370 data += '\x10\x45\x00\x21' + 33*'\x00'
4371 data += '\x10\x42\x00\x21' + 33*'\x00'
4372 data += '\x10\x24\x00\x21' + 33*'\x00'
4373 data += '\x10\x23\x00\x21' + 33*'\x00'
4374 data += '\x10\x21\x00\x41' + 65*'\x00'
4375 data += '\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4376 send_wlanevent(url, uuid, data)
4377
4378 logger.info("EAP message: M1 missing UUID-E")
4379 data = '\x0202:00:00:00:00:00'
4380 data += '\x10\x22\x00\x01\x04'
4381 send_wlanevent(url, uuid, data)
4382
4383 logger.info("EAP message: M1 missing MAC Address")
4384 data += '\x10\x47\x00\x10' + 16*'\x00'
4385 send_wlanevent(url, uuid, data)
4386
4387 logger.info("EAP message: M1 missing Enrollee Nonce")
4388 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4389 send_wlanevent(url, uuid, data)
4390
4391 logger.info("EAP message: M1 missing Public Key")
4392 data += '\x10\x1a\x00\x10' + 16*'\x00'
4393 send_wlanevent(url, uuid, data)
4394
4395 logger.info("EAP message: M1 missing Authentication Type flags")
4396 data += '\x10\x32\x00\xc0' + 192*'\x00'
4397 send_wlanevent(url, uuid, data)
4398
4399 logger.info("EAP message: M1 missing Encryption Type Flags")
4400 data += '\x10\x04\x00\x02\x00\x00'
4401 send_wlanevent(url, uuid, data)
4402
4403 logger.info("EAP message: M1 missing Connection Type flags")
4404 data += '\x10\x10\x00\x02\x00\x00'
4405 send_wlanevent(url, uuid, data)
4406
4407 logger.info("EAP message: M1 missing Config Methods")
4408 data += '\x10\x0d\x00\x01\x00'
4409 send_wlanevent(url, uuid, data)
4410
4411 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4412 data += '\x10\x08\x00\x02\x00\x00'
4413 send_wlanevent(url, uuid, data)
4414
4415 logger.info("EAP message: M1 missing Manufacturer")
4416 data += '\x10\x44\x00\x01\x00'
4417 send_wlanevent(url, uuid, data)
4418
4419 logger.info("EAP message: M1 missing Model Name")
4420 data += '\x10\x21\x00\x00'
4421 send_wlanevent(url, uuid, data)
4422
4423 logger.info("EAP message: M1 missing Model Number")
4424 data += '\x10\x23\x00\x00'
4425 send_wlanevent(url, uuid, data)
4426
4427 logger.info("EAP message: M1 missing Serial Number")
4428 data += '\x10\x24\x00\x00'
4429 send_wlanevent(url, uuid, data)
4430
4431 logger.info("EAP message: M1 missing Primary Device Type")
4432 data += '\x10\x42\x00\x00'
4433 send_wlanevent(url, uuid, data)
4434
4435 logger.info("EAP message: M1 missing Device Name")
4436 data += '\x10\x54\x00\x08' + 8*'\x00'
4437 send_wlanevent(url, uuid, data)
4438
4439 logger.info("EAP message: M1 missing RF Bands")
4440 data += '\x10\x11\x00\x00'
4441 send_wlanevent(url, uuid, data)
4442
4443 logger.info("EAP message: M1 missing Association State")
4444 data += '\x10\x3c\x00\x01\x00'
4445 send_wlanevent(url, uuid, data)
4446
4447 logger.info("EAP message: M1 missing Device Password ID")
4448 data += '\x10\x02\x00\x02\x00\x00'
4449 send_wlanevent(url, uuid, data)
4450
4451 logger.info("EAP message: M1 missing Configuration Error")
4452 data += '\x10\x12\x00\x02\x00\x00'
4453 send_wlanevent(url, uuid, data)
4454
4455 logger.info("EAP message: M1 missing OS Version")
4456 data += '\x10\x09\x00\x02\x00\x00'
4457 send_wlanevent(url, uuid, data)
4c3ae1c0 4458
24b7f282
JM
4459 logger.info("Check max concurrent requests")
4460 addr = (url.hostname, url.port)
4461 socks = {}
4462 for i in range(20):
4463 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4464 socket.IPPROTO_TCP)
e5d3e13a
JM
4465 socks[i].settimeout(10)
4466 socks[i].connect(addr)
24b7f282
JM
4467 for i in range(20):
4468 socks[i].send("GET / HTTP/1.1\r\n\r\n")
4469 count = 0
4470 for i in range(20):
4471 try:
4472 res = socks[i].recv(100)
4473 if "HTTP/1" in res:
4474 count += 1
6f9b4de2
JM
4475 else:
4476 logger.info("recv[%d]: len=%d" % (i, len(res)))
24b7f282
JM
4477 except:
4478 pass
4479 socks[i].close()
4480 logger.info("%d concurrent HTTP GET operations returned response" % count)
6f9b4de2 4481 if count < 8:
24b7f282
JM
4482 raise Exception("Too few concurrent HTTP connections accepted")
4483
4484 logger.info("OOM in HTTP server")
4485 for func in [ "http_request_init", "httpread_create",
4486 "eloop_register_timeout;httpread_create",
9b35afd6 4487 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
24b7f282
JM
4488 "httpread_hdr_analyze" ]:
4489 with alloc_fail(dev[0], 1, func):
4490 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4491 socket.IPPROTO_TCP)
4492 sock.connect(addr)
4493 sock.send("GET / HTTP/1.1\r\n\r\n")
4494 try:
4495 sock.recv(100)
4496 except:
4497 pass
4498 sock.close()
4499
4500 logger.info("Invalid HTTP header")
4501 for req in [ " GET / HTTP/1.1\r\n\r\n",
4502 "HTTP/1.1 200 OK\r\n\r\n",
4503 "HTTP/\r\n\r\n",
4504 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4505 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4506 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4507 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4508 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4509 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4510 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4511 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
4512 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4513 socket.IPPROTO_TCP)
4514 sock.settimeout(0.1)
4515 sock.connect(addr)
4516 sock.send(req)
4517 try:
4518 sock.recv(100)
4519 except:
4520 pass
4521 sock.close()
4522
4523 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4524 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4525 socket.IPPROTO_TCP)
4526 sock.connect(addr)
4527 sock.send("NOTIFY / HTTP/1.1\r\n\r\n" + 4500*'a')
4528 try:
4529 sock.recv(100)
4530 except:
4531 pass
4532 sock.close()
4533
4534 conn = httplib.HTTPConnection(url.netloc)
4535 payload = '<foo'
4536 headers = { "Content-type": 'text/xml; charset="utf-8"',
4537 "Server": "Unspecified, UPnP/1.0, Unspecified",
4538 "HOST": url.netloc,
4539 "NT": "upnp:event",
4540 "SID": "uuid:" + uuid,
4541 "SEQ": "0",
4542 "Content-Length": str(len(payload)) }
4543 conn.request("NOTIFY", url.path, payload, headers)
4544 resp = conn.getresponse()
4545 if resp.status != 200:
4546 raise Exception("Unexpected HTTP response: %d" % resp.status)
4547
4548 conn = httplib.HTTPConnection(url.netloc)
4549 payload = '<WLANEvent foo></WLANEvent>'
4550 headers = { "Content-type": 'text/xml; charset="utf-8"',
4551 "Server": "Unspecified, UPnP/1.0, Unspecified",
4552 "HOST": url.netloc,
4553 "NT": "upnp:event",
4554 "SID": "uuid:" + uuid,
4555 "SEQ": "0",
4556 "Content-Length": str(len(payload)) }
4557 conn.request("NOTIFY", url.path, payload, headers)
4558 resp = conn.getresponse()
4559 if resp.status != 200:
4560 raise Exception("Unexpected HTTP response: %d" % resp.status)
4561
4562 with alloc_fail(dev[0], 1, "xml_get_first_item"):
4563 send_wlanevent(url, uuid, '')
4564
4565 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4566 send_wlanevent(url, uuid, 'foo')
4567
4568 for func in [ "wps_init",
4569 "wps_process_manufacturer",
4570 "wps_process_model_name",
4571 "wps_process_model_number",
4572 "wps_process_serial_number",
4573 "wps_process_dev_name" ]:
4574 with alloc_fail(dev[0], 1, func):
4575 send_wlanevent(url, uuid, m1)
4576
18478107
JM
4577 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4578 send_wlanevent(url, uuid, m1, no_response=True)
4579
4580 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4581 url2 = urlparse.urlparse(wps_event_url.replace('/event/', '/notfound/'))
4582 send_wlanevent(url2, uuid, m1, no_response=True)
4583
3d105cdf
JM
4584 logger.info("EAP message: M1")
4585 data = '\x0202:11:22:00:00:00'
4586 data += '\x10\x22\x00\x01\x04'
4587 data += '\x10\x47\x00\x10' + 16*'\x00'
4588 data += '\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4589 data += '\x10\x1a\x00\x10' + 16*'\x00'
4590 data += '\x10\x32\x00\xc0' + 192*'\x00'
4591 data += '\x10\x04\x00\x02\x00\x00'
4592 data += '\x10\x10\x00\x02\x00\x00'
4593 data += '\x10\x0d\x00\x01\x00'
4594 data += '\x10\x08\x00\x02\x00\x00'
4595 data += '\x10\x44\x00\x01\x00'
4596 data += '\x10\x21\x00\x00'
4597 data += '\x10\x23\x00\x00'
4598 data += '\x10\x24\x00\x00'
4599 data += '\x10\x42\x00\x00'
4600 data += '\x10\x54\x00\x08' + 8*'\x00'
4601 data += '\x10\x11\x00\x00'
4602 data += '\x10\x3c\x00\x01\x00'
4603 data += '\x10\x02\x00\x02\x00\x00'
4604 data += '\x10\x12\x00\x02\x00\x00'
4605 data += '\x10\x09\x00\x02\x00\x00'
4606 data += '\x10\x2d\x00\x04\x00\x00\x00\x00'
4607 dev[0].dump_monitor()
4608 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4609 send_wlanevent(url, uuid, data)
4610 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4611 if ev is not None:
4612 raise Exception("Unexpected enrollee add event")
4613 send_wlanevent(url, uuid, data)
4614 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4615 if ev is None:
4616 raise Exception("Enrollee add event not seen")
4617
5b52e1ad
JM
4618 with alloc_fail(dev[0], 1,
4619 "base64_gen_encode;?base64_encode;wps_er_soap_hdr"):
fe67b945
JM
4620 send_wlanevent(url, uuid, data)
4621
4622 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4623 send_wlanevent(url, uuid, data)
4624
4625 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4626 send_wlanevent(url, uuid, data)
4627
4628 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4629 send_wlanevent(url, uuid, data)
4630
4c3ae1c0
JM
4631def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4632 """WPS ER HTTP protocol testing - no eventSubURL"""
6aaa661a
JM
4633 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4634 def handle_upnp_info(self):
4635 self.wfile.write(gen_upnp_info(eventSubURL=None))
4636 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4637 no_event_url=True)
4c3ae1c0
JM
4638
4639def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4640 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
6aaa661a
JM
4641 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4642 def handle_upnp_info(self):
4643 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4644 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4645 no_event_url=True)
4c3ae1c0
JM
4646
4647def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4648 """WPS ER HTTP protocol testing - subscribe OOM"""
4649 try:
4650 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4651 finally:
4652 dev[0].request("WPS_ER_STOP")
4653
4654def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4655 tests = [ (1, "http_client_url_parse"),
4656 (1, "wpabuf_alloc;wps_er_subscribe"),
4657 (1, "http_client_addr"),
9b35afd6 4658 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4c3ae1c0
JM
4659 (1, "eloop_register_timeout;http_client_addr") ]
4660 for count,func in tests:
4661 with alloc_fail(dev[0], count, func):
4662 server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
4663 server.handle_request()
4664 server.handle_request()
4665 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
6aaa661a
JM
4666
4667def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4668 """WPS ER HTTP protocol testing - no SID"""
4669 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4670 def handle_wps_event(self):
4671 self.wfile.write(gen_wps_event(sid=None))
4672 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4673
4674def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4675 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4676 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4677 def handle_wps_event(self):
4678 self.wfile.write(gen_wps_event(sid='FOO'))
4679 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4680
4681def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4682 """WPS ER HTTP protocol testing - invalid SID UUID"""
4683 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4684 def handle_wps_event(self):
4685 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4686 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4687
4688def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4689 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4690 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4691 def handle_wps_event(self):
4692 payload = ""
4693 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4694 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4695 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4696 'Connection: close\r\n' + \
4697 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4698 'Timeout: Second-1801\r\n' + \
4699 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4700 self.wfile.write(hdr + payload)
4701 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4702
4703def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4704 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4705 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4706 def handle_wps_event(self):
4707 payload = ""
4708 hdr = 'HTTP/1.1 FOO\r\n' + \
4709 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4710 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4711 'Connection: close\r\n' + \
4712 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4713 'Timeout: Second-1801\r\n' + \
4714 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4715 self.wfile.write(hdr + payload)
4716 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4717
4718def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4719 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4720 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4721 def handle_wps_control(self):
4722 payload = '''<?xml version="1.0"?>
4723<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4724<s:Body>
4725<u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4726<NewDeviceInfo>Rk9P</NewDeviceInfo>
4727</u:GetDeviceInfoResponse>
4728</s:Body>
4729</s:Envelope>
4730'''
4731 self.wfile.write(gen_wps_control(payload_override=payload))
4732 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4733
4734def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4735 """WPS ER HTTP protocol testing - No device in UPnP info"""
4736 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4737 def handle_upnp_info(self):
4738 payload = '''<?xml version="1.0"?>
4739<root xmlns="urn:schemas-upnp-org:device-1-0">
4740<specVersion>
4741<major>1</major>
4742<minor>0</minor>
4743</specVersion>
4744</root>
4745'''
4746 hdr = 'HTTP/1.1 200 OK\r\n' + \
4747 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4748 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4749 'Connection: close\r\n' + \
4750 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4751 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4752 self.wfile.write(hdr + payload)
4753 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4754
4755def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4756 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4757 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4758 def handle_upnp_info(self):
4759 payload = '''<?xml version="1.0"?>
4760<root xmlns="urn:schemas-upnp-org:device-1-0">
4761<specVersion>
4762<major>1</major>
4763<minor>0</minor>
4764</specVersion>
4765<device>
4766</device>
4767</root>
4768'''
4769 hdr = 'HTTP/1.1 200 OK\r\n' + \
4770 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4771 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4772 'Connection: close\r\n' + \
4773 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4774 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4775 self.wfile.write(hdr + payload)
4776 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4777
4778def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4779 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4780 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4781 def handle_upnp_info(self):
4782 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4783 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4784
4785def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4786 """WPS ER HTTP protocol testing - no controlURL"""
4787 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4788 def handle_upnp_info(self):
4789 self.wfile.write(gen_upnp_info(controlURL=None))
4790 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4791 no_event_url=True)
4792
4793def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4794 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4795 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4796 def handle_upnp_info(self):
4797 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4798 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4799 no_event_url=True)
24b7f282
JM
4800
4801def test_ap_wps_http_timeout(dev, apdev):
4802 """WPS AP/ER and HTTP timeout"""
4803 try:
4804 _test_ap_wps_http_timeout(dev, apdev)
4805 finally:
4806 dev[0].request("WPS_ER_STOP")
4807
4808def _test_ap_wps_http_timeout(dev, apdev):
4809 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 4810 add_ssdp_ap(apdev[0], ap_uuid)
24b7f282
JM
4811
4812 location = ssdp_get_location(ap_uuid)
4813 url = urlparse.urlparse(location)
4814 addr = (url.hostname, url.port)
4815 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4816 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4817 socket.IPPROTO_TCP)
4818 sock.connect(addr)
4819 sock.send("G")
4820
4821 class DummyServer(SocketServer.StreamRequestHandler):
4822 def handle(self):
4823 logger.debug("DummyServer - start 31 sec wait")
4824 time.sleep(31)
4825 logger.debug("DummyServer - wait done")
4826
4827 logger.debug("Start WPS ER")
4828 server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4829 wait_m_search=True)
4830
4831 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4832 # This will wait for 31 seconds..
4833 server.handle_request()
4834
4835 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4836 try:
4837 sock.send("ET / HTTP/1.1\r\n\r\n")
4838 res = sock.recv(100)
4839 sock.close()
4840 except:
4841 pass
4842
4843def test_ap_wps_er_url_parse(dev, apdev):
4844 """WPS ER and URL parsing special cases"""
4845 try:
4846 _test_ap_wps_er_url_parse(dev, apdev)
4847 finally:
4848 dev[0].request("WPS_ER_STOP")
4849
4850def _test_ap_wps_er_url_parse(dev, apdev):
4851 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4852 sock.settimeout(1)
4853 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4854 sock.bind(("239.255.255.250", 1900))
4855 dev[0].request("WPS_ER_START ifname=lo")
4856 (msg,addr) = sock.recvfrom(1000)
4857 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4858 if "M-SEARCH" not in msg:
4859 raise Exception("Not an M-SEARCH")
4860 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)
4861 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4862 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)
4863 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4864 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)
4865 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4866
4867 sock.close()
4868
4869def test_ap_wps_er_link_update(dev, apdev):
4870 """WPS ER and link update special cases"""
4871 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4872 def handle_upnp_info(self):
4873 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4874 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4875
4876 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4877 def handle_others(self, data):
4878 if "GET / " in data:
4879 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4880 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4881 location_url='http://127.0.0.1:12345')
4882
4883def test_ap_wps_er_http_client(dev, apdev):
4884 """WPS ER and HTTP client special cases"""
4885 with alloc_fail(dev[0], 1, "http_link_update"):
4886 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4887
4888 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4889 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4890
4891 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4892 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4893
4894 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4895 def handle_upnp_info(self):
4896 self.wfile.write("GET / HTTP/1.1\r\n\r\n")
4897 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4898 no_event_url=True)
4899
4900def test_ap_wps_init_oom(dev, apdev):
4901 """wps_init OOM cases"""
4902 ssid = "test-wps"
4903 appin = "12345670"
4904 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4905 "ap_pin": appin }
8b8a1864 4906 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4907 pin = dev[0].wps_read_pin()
4908
4909 with alloc_fail(hapd, 1, "wps_init"):
4910 hapd.request("WPS_PIN any " + pin)
4911 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4912 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4913 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4914 if ev is None:
4915 raise Exception("No EAP failure reported")
4916 dev[0].request("WPS_CANCEL")
4917
4918 with alloc_fail(dev[0], 2, "wps_init"):
4919 hapd.request("WPS_PIN any " + pin)
4920 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4921 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4922 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4923 if ev is None:
4924 raise Exception("No EAP failure reported")
4925 dev[0].request("WPS_CANCEL")
4926
4927 with alloc_fail(dev[0], 2, "wps_init"):
4928 hapd.request("WPS_PBC")
4929 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4930 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4931 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4932 if ev is None:
4933 raise Exception("No EAP failure reported")
4934 dev[0].request("WPS_CANCEL")
4935
4936 dev[0].dump_monitor()
4937 new_ssid = "wps-new-ssid"
4938 new_passphrase = "1234567890"
4939 with alloc_fail(dev[0], 3, "wps_init"):
4940 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4941 new_passphrase, no_wait=True)
4942 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4943 if ev is None:
4944 raise Exception("No EAP failure reported")
4945
4946 dev[0].flush_scan_cache()
4947
9fd6804d 4948@remote_compatible
24b7f282
JM
4949def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4950 """WPS and invalid IE in Association Request frame"""
4951 ssid = "test-wps"
4952 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4953 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4954 pin = "12345670"
4955 hapd.request("WPS_PIN any " + pin)
4956 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4957 try:
4958 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4959 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4960 for i in range(5):
4961 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4962 if ev and "vendor=14122" in ev:
4963 break
4964 if ev is None or "vendor=14122" not in ev:
4965 raise Exception("EAP-WSC not started")
4966 dev[0].request("WPS_CANCEL")
4967 finally:
4968 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
4969
4970def test_ap_wps_pbc_pin_mismatch(dev, apdev):
4971 """WPS PBC/PIN mismatch"""
4972 ssid = "test-wps"
4973 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 4974 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
4975 hapd.request("SET wps_version_number 0x10")
4976 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4977 hapd.request("WPS_PBC")
4978 pin = dev[0].wps_read_pin()
4979 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4980 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
4981 if ev is None:
4982 raise Exception("Scan did not complete")
4983 dev[0].request("WPS_CANCEL")
4984
4985 hapd.request("WPS_CANCEL")
4986 dev[0].flush_scan_cache()
4987
9fd6804d 4988@remote_compatible
24b7f282
JM
4989def test_ap_wps_ie_invalid(dev, apdev):
4990 """WPS PIN attempt with AP that has invalid WSC IE"""
4991 ssid = "test-wps"
4992 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4993 "vendor_elements": "dd050050f20410" }
8b8a1864 4994 hapd = hostapd.add_ap(apdev[0], params)
24b7f282 4995 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
8b8a1864 4996 hostapd.add_ap(apdev[1], params)
24b7f282
JM
4997 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4998 pin = dev[0].wps_read_pin()
4999 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5000 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5001 if ev is None:
5002 raise Exception("Scan did not complete")
5003 dev[0].request("WPS_CANCEL")
5004
9fd6804d 5005@remote_compatible
24b7f282
JM
5006def test_ap_wps_scan_prio_order(dev, apdev):
5007 """WPS scan priority ordering"""
5008 ssid = "test-wps"
5009 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 5010 hapd = hostapd.add_ap(apdev[0], params)
24b7f282 5011 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
8b8a1864 5012 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5013 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5014 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5015 pin = dev[0].wps_read_pin()
5016 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5017 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5018 if ev is None:
5019 raise Exception("Scan did not complete")
5020 dev[0].request("WPS_CANCEL")
5021
5022def test_ap_wps_probe_req_ie_oom(dev, apdev):
5023 """WPS ProbeReq IE OOM"""
5024 ssid = "test-wps"
5025 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 5026 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5027 pin = dev[0].wps_read_pin()
5028 hapd.request("WPS_PIN any " + pin)
5029 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5030 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
5031 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5032 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5033 if ev is None:
5034 raise Exception("Association not seen")
5035 dev[0].request("WPS_CANCEL")
161c8515 5036 dev[0].wait_disconnected()
24b7f282
JM
5037
5038 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
5039 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5040 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5041 if ev is None:
5042 raise Exception("Association not seen")
5043 dev[0].request("WPS_CANCEL")
161c8515
JM
5044 hapd.disable()
5045 dev[0].request("REMOVE_NETWORK all")
5046 dev[0].wait_disconnected()
5047 time.sleep(0.2)
5048 dev[0].flush_scan_cache()
24b7f282
JM
5049
5050def test_ap_wps_assoc_req_ie_oom(dev, apdev):
5051 """WPS AssocReq IE OOM"""
5052 ssid = "test-wps"
5053 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 5054 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5055 pin = dev[0].wps_read_pin()
5056 hapd.request("WPS_PIN any " + pin)
5057 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5058 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
5059 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5060 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5061 if ev is None:
5062 raise Exception("Association not seen")
5063 dev[0].request("WPS_CANCEL")
5064
5065def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
5066 """WPS AssocResp IE OOM"""
5067 ssid = "test-wps"
5068 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
8b8a1864 5069 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5070 pin = dev[0].wps_read_pin()
5071 hapd.request("WPS_PIN any " + pin)
5072 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5073 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
5074 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5075 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5076 if ev is None:
5077 raise Exception("Association not seen")
5078 dev[0].request("WPS_CANCEL")
5079
9fd6804d 5080@remote_compatible
24b7f282
JM
5081def test_ap_wps_bss_info_errors(dev, apdev):
5082 """WPS BSS info errors"""
5083 params = { "ssid": "1",
5084 "vendor_elements": "dd0e0050f20410440001ff101100010a" }
8b8a1864 5085 hostapd.add_ap(apdev[0], params)
24b7f282 5086 params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
8b8a1864 5087 hostapd.add_ap(apdev[1], params)
24b7f282
JM
5088 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5089 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5090 bss = dev[0].get_bss(apdev[0]['bssid'])
5091 logger.info("BSS: " + str(bss))
5092 if "wps_state" in bss:
5093 raise Exception("Unexpected wps_state in BSS info")
5094 if 'wps_device_name' not in bss:
5095 raise Exception("No wps_device_name in BSS info")
5096 if bss['wps_device_name'] != '_':
5097 raise Exception("Unexpected wps_device_name value")
5098 bss = dev[0].get_bss(apdev[1]['bssid'])
5099 logger.info("BSS: " + str(bss))
5100
5101 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5102 bss = dev[0].get_bss(apdev[0]['bssid'])
5103 logger.info("BSS(OOM): " + str(bss))
5104
5105def wps_run_pbc_fail_ap(apdev, dev, hapd):
5106 hapd.request("WPS_PBC")
5107 dev.scan_for_bss(apdev['bssid'], freq="2412")
5108 dev.request("WPS_PBC " + apdev['bssid'])
5109 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5110 if ev is None:
5111 raise Exception("No EAP failure reported")
5112 dev.request("WPS_CANCEL")
5113 dev.wait_disconnected()
5114 for i in range(5):
5115 try:
5116 dev.flush_scan_cache()
5117 break
5118 except Exception, e:
5119 if str(e).startswith("Failed to trigger scan"):
5120 # Try again
5121 time.sleep(1)
5122 else:
5123 raise
5124
5125def wps_run_pbc_fail(apdev, dev):
5126 hapd = wps_start_ap(apdev)
5127 wps_run_pbc_fail_ap(apdev, dev, hapd)
5128
9fd6804d 5129@remote_compatible
24b7f282
JM
5130def test_ap_wps_pk_oom(dev, apdev):
5131 """WPS and public key OOM"""
5132 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5133 wps_run_pbc_fail(apdev[0], dev[0])
5134
9fd6804d 5135@remote_compatible
24b7f282
JM
5136def test_ap_wps_pk_oom_ap(dev, apdev):
5137 """WPS and public key OOM on AP"""
5138 hapd = wps_start_ap(apdev[0])
5139 with alloc_fail(hapd, 1, "wps_build_public_key"):
5140 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5141
9fd6804d 5142@remote_compatible
24b7f282
JM
5143def test_ap_wps_encr_oom_ap(dev, apdev):
5144 """WPS and encrypted settings decryption OOM on AP"""
5145 hapd = wps_start_ap(apdev[0])
5146 pin = dev[0].wps_read_pin()
5147 hapd.request("WPS_PIN any " + pin)
5148 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5149 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5150 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5151 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5152 if ev is None:
5153 raise Exception("No WPS-FAIL reported")
5154 dev[0].request("WPS_CANCEL")
5155 dev[0].wait_disconnected()
5156
9fd6804d 5157@remote_compatible
24b7f282
JM
5158def test_ap_wps_encr_no_random_ap(dev, apdev):
5159 """WPS and no random data available for encryption on AP"""
5160 hapd = wps_start_ap(apdev[0])
5161 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5162 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5163
9fd6804d 5164@remote_compatible
24b7f282
JM
5165def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5166 """WPS and no random data available for e-hash on STA"""
5167 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5168 wps_run_pbc_fail(apdev[0], dev[0])
5169
9fd6804d 5170@remote_compatible
24b7f282
JM
5171def test_ap_wps_m1_no_random(dev, apdev):
5172 """WPS and no random for M1 on STA"""
5173 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5174 wps_run_pbc_fail(apdev[0], dev[0])
5175
9fd6804d 5176@remote_compatible
24b7f282
JM
5177def test_ap_wps_m1_oom(dev, apdev):
5178 """WPS and OOM for M1 on STA"""
5179 with alloc_fail(dev[0], 1, "wps_build_m1"):
5180 wps_run_pbc_fail(apdev[0], dev[0])
5181
9fd6804d 5182@remote_compatible
24b7f282
JM
5183def test_ap_wps_m3_oom(dev, apdev):
5184 """WPS and OOM for M3 on STA"""
5185 with alloc_fail(dev[0], 1, "wps_build_m3"):
5186 wps_run_pbc_fail(apdev[0], dev[0])
5187
9fd6804d 5188@remote_compatible
24b7f282
JM
5189def test_ap_wps_m5_oom(dev, apdev):
5190 """WPS and OOM for M5 on STA"""
5191 hapd = wps_start_ap(apdev[0])
5192 hapd.request("WPS_PBC")
5193 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5194 for i in range(1, 3):
5195 with alloc_fail(dev[0], i, "wps_build_m5"):
5196 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5197 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5198 if ev is None:
5199 raise Exception("No EAP failure reported")
5200 dev[0].request("WPS_CANCEL")
5201 dev[0].wait_disconnected()
5202 dev[0].flush_scan_cache()
5203
9fd6804d 5204@remote_compatible
24b7f282
JM
5205def test_ap_wps_m5_no_random(dev, apdev):
5206 """WPS and no random for M5 on STA"""
5207 with fail_test(dev[0], 1,
5208 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5209 wps_run_pbc_fail(apdev[0], dev[0])
5210
9fd6804d 5211@remote_compatible
24b7f282
JM
5212def test_ap_wps_m7_oom(dev, apdev):
5213 """WPS and OOM for M7 on STA"""
5214 hapd = wps_start_ap(apdev[0])
5215 hapd.request("WPS_PBC")
5216 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5217 for i in range(1, 3):
5218 with alloc_fail(dev[0], i, "wps_build_m7"):
5219 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5220 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5221 if ev is None:
5222 raise Exception("No EAP failure reported")
5223 dev[0].request("WPS_CANCEL")
5224 dev[0].wait_disconnected()
5225 dev[0].flush_scan_cache()
5226
9fd6804d 5227@remote_compatible
24b7f282
JM
5228def test_ap_wps_m7_no_random(dev, apdev):
5229 """WPS and no random for M7 on STA"""
5230 with fail_test(dev[0], 1,
5231 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5232 wps_run_pbc_fail(apdev[0], dev[0])
5233
9fd6804d 5234@remote_compatible
24b7f282
JM
5235def test_ap_wps_wsc_done_oom(dev, apdev):
5236 """WPS and OOM for WSC_Done on STA"""
5237 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5238 wps_run_pbc_fail(apdev[0], dev[0])
5239
5240def test_ap_wps_random_psk_fail(dev, apdev):
5241 """WPS and no random for PSK on AP"""
5242 ssid = "test-wps"
5243 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5244 appin = "12345670"
5245 try:
5246 os.remove(pskfile)
5247 except:
5248 pass
5249
5250 try:
5251 with open(pskfile, "w") as f:
5252 f.write("# WPA PSKs\n")
5253
5254 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5255 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5256 "rsn_pairwise": "CCMP", "ap_pin": appin,
5257 "wpa_psk_file": pskfile }
8b8a1864 5258 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5259
5260 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5261 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5262 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5263 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5264 if ev is None:
5265 raise Exception("No EAP failure reported")
5266 dev[0].request("WPS_CANCEL")
5267 dev[0].wait_disconnected()
5268
5269 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5270 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5271
5272 with alloc_fail(hapd, 1, "wps_build_cred"):
5273 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5274
5275 with alloc_fail(hapd, 2, "wps_build_cred"):
5276 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5277 finally:
5278 os.remove(pskfile)
5279
5280def wps_ext_eap_identity_req(dev, hapd, bssid):
5281 logger.debug("EAP-Identity/Request")
5282 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5283 if ev is None:
5284 raise Exception("Timeout on EAPOL-TX from hostapd")
5285 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5286 if "OK" not in res:
5287 raise Exception("EAPOL_RX to wpa_supplicant failed")
5288
5289def wps_ext_eap_identity_resp(hapd, dev, addr):
5290 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5291 if ev is None:
5292 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5293 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5294 if "OK" not in res:
5295 raise Exception("EAPOL_RX to hostapd failed")
5296
5297def wps_ext_eap_wsc(dst, src, src_addr, msg):
5298 logger.debug(msg)
5299 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5300 if ev is None:
5301 raise Exception("Timeout on EAPOL-TX")
5302 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5303 if "OK" not in res:
5304 raise Exception("EAPOL_RX failed")
5305
7511ead0 5306def wps_start_ext(apdev, dev, pbc=False, pin=None):
24b7f282
JM
5307 addr = dev.own_addr()
5308 bssid = apdev['bssid']
5309 ssid = "test-wps-conf"
5310 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5311 "wpa_passphrase": "12345678", "wpa": "2",
5312 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
afc26df2 5313 hapd = hostapd.add_ap(apdev, params)
24b7f282 5314
d1883671
JM
5315 if pbc:
5316 hapd.request("WPS_PBC")
5317 else:
7511ead0
JM
5318 if pin is None:
5319 pin = dev.wps_read_pin()
d1883671 5320 hapd.request("WPS_PIN any " + pin)
24b7f282
JM
5321 dev.scan_for_bss(bssid, freq="2412")
5322 hapd.request("SET ext_eapol_frame_io 1")
5323 dev.request("SET ext_eapol_frame_io 1")
5324
d1883671
JM
5325 if pbc:
5326 dev.request("WPS_PBC " + bssid)
5327 else:
5328 dev.request("WPS_PIN " + bssid + " " + pin)
24b7f282
JM
5329 return addr,bssid,hapd
5330
5331def wps_auth_corrupt(dst, src, addr):
5332 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5333 if ev is None:
5334 raise Exception("Timeout on EAPOL-TX")
5335 src.request("SET ext_eapol_frame_io 0")
5336 dst.request("SET ext_eapol_frame_io 0")
5337 msg = ev.split(' ')[2]
5338 if msg[-24:-16] != '10050008':
5339 raise Exception("Could not find Authenticator attribute")
5340 # Corrupt Authenticator value
5341 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5342 res = dst.request("EAPOL_RX " + addr + " " + msg)
5343 if "OK" not in res:
5344 raise Exception("EAPOL_RX failed")
5345
5346def wps_fail_finish(hapd, dev, fail_str):
5347 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5348 if ev is None:
5349 raise Exception("WPS-FAIL not indicated")
5350 if fail_str not in ev:
5351 raise Exception("Unexpected WPS-FAIL value: " + ev)
5352 dev.request("WPS_CANCEL")
5353 dev.wait_disconnected()
5354
5355def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5356 wps_auth_corrupt(dev, hapd, bssid)
5357 wps_fail_finish(hapd, dev, fail_str)
5358
5359def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5360 wps_auth_corrupt(hapd, dev, addr)
5361 wps_fail_finish(hapd, dev, fail_str)
5362
5363def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5364 """WPS and Authenticator attribute mismatch in M2"""
5365 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5366 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5367 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5368 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5369 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5370 logger.debug("M2")
5371 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5372
5373def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5374 """WPS and Authenticator attribute mismatch in M3"""
5375 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5376 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5377 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5378 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5379 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5380 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5381 logger.debug("M3")
5382 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5383
5384def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5385 """WPS and Authenticator attribute mismatch in M4"""
5386 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5387 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5388 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5389 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5390 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5391 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5392 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5393 logger.debug("M4")
5394 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5395
5396def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5397 """WPS and Authenticator attribute mismatch in M5"""
5398 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5399 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5400 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5401 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5402 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5403 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5404 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5405 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5406 logger.debug("M5")
5407 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5408
5409def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5410 """WPS and Authenticator attribute mismatch in M6"""
5411 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5412 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5413 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5414 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5415 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5416 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5417 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5418 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5419 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5420 logger.debug("M6")
5421 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5422
5423def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5424 """WPS and Authenticator attribute mismatch in M7"""
5425 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5426 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5427 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5428 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5429 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5430 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5431 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5432 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5433 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5434 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5435 logger.debug("M7")
5436 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5437
5438def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5439 """WPS and Authenticator attribute mismatch in M8"""
5440 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5441 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5442 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5443 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5444 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5445 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5446 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5447 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5448 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5449 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5450 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5451 logger.debug("M8")
5452 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5453
5454def test_ap_wps_authenticator_missing_m2(dev, apdev):
5455 """WPS and Authenticator attribute missing from M2"""
5456 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5457 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5458 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5459 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5460 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5461 logger.debug("M2")
5462 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5463 if ev is None:
5464 raise Exception("Timeout on EAPOL-TX")
5465 hapd.request("SET ext_eapol_frame_io 0")
5466 dev[0].request("SET ext_eapol_frame_io 0")
5467 msg = ev.split(' ')[2]
5468 if msg[-24:-16] != '10050008':
5469 raise Exception("Could not find Authenticator attribute")
5470 # Remove Authenticator value
5471 msg = msg[:-24]
5472 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5473 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5474 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5475 if "OK" not in res:
5476 raise Exception("EAPOL_RX failed")
5477 wps_fail_finish(hapd, dev[0], "msg=5")
5478
d1883671
JM
5479def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5480 """WPS and M2 with different Device Password ID (P2P)"""
5481 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5482 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5483 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5484 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5485 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5486 logger.debug("M2")
5487 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5488 if ev is None:
5489 raise Exception("Timeout on EAPOL-TX")
5490 hapd.request("SET ext_eapol_frame_io 0")
5491 dev[0].request("SET ext_eapol_frame_io 0")
5492 msg = ev.split(' ')[2]
5493 if msg[722:730] != '10120002':
5494 raise Exception("Could not find Device Password ID attribute")
5495 # Replace Device Password ID value. This will fail Authenticator check, but
5496 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5497 # log.
5498 msg = msg[0:730] + "0005" + msg[734:]
5499 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5500 if "OK" not in res:
5501 raise Exception("EAPOL_RX failed")
5502 wps_fail_finish(hapd, dev[0], "msg=5")
5503
5504def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5505 """WPS and M2 with different Device Password ID (PIN to PBC)"""
5506 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5507 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5508 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5509 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5510 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5511 logger.debug("M2")
5512 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5513 if ev is None:
5514 raise Exception("Timeout on EAPOL-TX")
5515 hapd.request("SET ext_eapol_frame_io 0")
5516 dev[0].request("SET ext_eapol_frame_io 0")
5517 msg = ev.split(' ')[2]
5518 if msg[722:730] != '10120002':
5519 raise Exception("Could not find Device Password ID attribute")
5520 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5521 msg = msg[0:730] + "0004" + msg[734:]
5522 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5523 if "OK" not in res:
5524 raise Exception("EAPOL_RX failed")
5525 wps_fail_finish(hapd, dev[0], "msg=5")
5526
5527def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5528 """WPS and M2 with different Device Password ID (PBC to PIN)"""
5529 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5530 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5531 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5532 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5533 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5534 logger.debug("M2")
5535 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5536 if ev is None:
5537 raise Exception("Timeout on EAPOL-TX")
5538 hapd.request("SET ext_eapol_frame_io 0")
5539 dev[0].request("SET ext_eapol_frame_io 0")
5540 msg = ev.split(' ')[2]
5541 if msg[722:730] != '10120002':
5542 raise Exception("Could not find Device Password ID attribute")
5543 # Replace Device Password ID value. This will fail Authenticator check, but
5544 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5545 # log.
5546 msg = msg[0:730] + "0000" + msg[734:]
5547 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5548 if "OK" not in res:
5549 raise Exception("EAPOL_RX failed")
5550 wps_fail_finish(hapd, dev[0], "msg=5")
5551 dev[0].flush_scan_cache()
5552
5553def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5554 """WPS and M2 without Device Password ID"""
5555 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5556 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5557 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5558 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5559 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5560 logger.debug("M2")
5561 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5562 if ev is None:
5563 raise Exception("Timeout on EAPOL-TX")
5564 hapd.request("SET ext_eapol_frame_io 0")
5565 dev[0].request("SET ext_eapol_frame_io 0")
5566 msg = ev.split(' ')[2]
5567 if msg[722:730] != '10120002':
5568 raise Exception("Could not find Device Password ID attribute")
5569 # Remove Device Password ID value. This will fail Authenticator check, but
5570 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5571 # log.
5572 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5573 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5574 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5575 if "OK" not in res:
5576 raise Exception("EAPOL_RX failed")
5577 wps_fail_finish(hapd, dev[0], "msg=5")
5578
5579def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5580 """WPS and M2 without Registrar Nonce"""
5581 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5582 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5583 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5584 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5585 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5586 logger.debug("M2")
5587 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5588 if ev is None:
5589 raise Exception("Timeout on EAPOL-TX")
5590 hapd.request("SET ext_eapol_frame_io 0")
5591 dev[0].request("SET ext_eapol_frame_io 0")
5592 msg = ev.split(' ')[2]
5593 if msg[96:104] != '10390010':
5594 raise Exception("Could not find Registrar Nonce attribute")
5595 # Remove Registrar Nonce. This will fail Authenticator check, but
5596 # allows the code path in wps_process_registrar_nonce() to be checked from
5597 # the debug log.
5598 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5599 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5600 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5601 if "OK" not in res:
5602 raise Exception("EAPOL_RX failed")
5603 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5604 if ev is None:
5605 raise Exception("Disconnect event not seen")
5606 dev[0].request("WPS_CANCEL")
5607 dev[0].flush_scan_cache()
5608
5609def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5610 """WPS and M2 without Enrollee Nonce"""
5611 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5612 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5613 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5614 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5615 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5616 logger.debug("M2")
5617 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5618 if ev is None:
5619 raise Exception("Timeout on EAPOL-TX")
5620 hapd.request("SET ext_eapol_frame_io 0")
5621 dev[0].request("SET ext_eapol_frame_io 0")
5622 msg = ev.split(' ')[2]
5623 if msg[56:64] != '101a0010':
5624 raise Exception("Could not find enrollee Nonce attribute")
5625 # Remove Enrollee Nonce. This will fail Authenticator check, but
5626 # allows the code path in wps_process_enrollee_nonce() to be checked from
5627 # the debug log.
5628 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5629 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5630 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5631 if "OK" not in res:
5632 raise Exception("EAPOL_RX failed")
5633 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5634 if ev is None:
5635 raise Exception("Disconnect event not seen")
5636 dev[0].request("WPS_CANCEL")
5637 dev[0].flush_scan_cache()
5638
5639def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5640 """WPS and M2 without UUID-R"""
5641 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5642 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5643 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5644 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5645 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5646 logger.debug("M2")
5647 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5648 if ev is None:
5649 raise Exception("Timeout on EAPOL-TX")
5650 hapd.request("SET ext_eapol_frame_io 0")
5651 dev[0].request("SET ext_eapol_frame_io 0")
5652 msg = ev.split(' ')[2]
5653 if msg[136:144] != '10480010':
5654 raise Exception("Could not find enrollee Nonce attribute")
5655 # Remove UUID-R. This will fail Authenticator check, but allows the code
5656 # path in wps_process_uuid_r() to be checked from the debug log.
5657 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5658 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5659 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5660 if "OK" not in res:
5661 raise Exception("EAPOL_RX failed")
5662 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5663 if ev is None:
5664 raise Exception("Disconnect event not seen")
5665 dev[0].request("WPS_CANCEL")
5666 dev[0].flush_scan_cache()
5667
5668def test_ap_wps_m2_invalid(dev, apdev):
5669 """WPS and M2 parsing failure"""
5670 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5671 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5672 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5673 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5674 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5675 logger.debug("M2")
5676 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5677 if ev is None:
5678 raise Exception("Timeout on EAPOL-TX")
5679 hapd.request("SET ext_eapol_frame_io 0")
5680 dev[0].request("SET ext_eapol_frame_io 0")
5681 msg = ev.split(' ')[2]
5682 if msg[136:144] != '10480010':
5683 raise Exception("Could not find enrollee Nonce attribute")
5684 # Remove UUID-R. This will fail Authenticator check, but allows the code
5685 # path in wps_process_uuid_r() to be checked from the debug log.
5686 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5687 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5688 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5689 if "OK" not in res:
5690 raise Exception("EAPOL_RX failed")
5691 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5692 if ev is None:
5693 raise Exception("Disconnect event not seen")
5694 dev[0].request("WPS_CANCEL")
5695 dev[0].flush_scan_cache()
5696
5697def test_ap_wps_m2_missing_msg_type(dev, apdev):
5698 """WPS and M2 without Message Type"""
5699 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5700 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5701 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5702 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5703 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5704 logger.debug("M2")
5705 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5706 if ev is None:
5707 raise Exception("Timeout on EAPOL-TX")
5708 hapd.request("SET ext_eapol_frame_io 0")
5709 dev[0].request("SET ext_eapol_frame_io 0")
5710 msg = ev.split(' ')[2]
5711 if msg[46:54] != '10220001':
5712 raise Exception("Could not find Message Type attribute")
5713 # Remove Message Type. This will fail Authenticator check, but allows the
5714 # code path in wps_process_wsc_msg() to be checked from the debug log.
5715 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5716 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5717 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5718 if "OK" not in res:
5719 raise Exception("EAPOL_RX failed")
5720 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5721 if ev is None:
5722 raise Exception("Disconnect event not seen")
5723 dev[0].request("WPS_CANCEL")
5724 dev[0].flush_scan_cache()
5725
5726def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5727 """WPS and M2 but unknown Message Type"""
5728 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5729 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5730 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5731 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5732 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5733 logger.debug("M2")
5734 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5735 if ev is None:
5736 raise Exception("Timeout on EAPOL-TX")
5737 hapd.request("SET ext_eapol_frame_io 0")
5738 dev[0].request("SET ext_eapol_frame_io 0")
5739 msg = ev.split(' ')[2]
5740 if msg[46:54] != '10220001':
5741 raise Exception("Could not find Message Type attribute")
5742 # Replace Message Type value. This will be rejected.
5743 msg = msg[0:54] + "00" + msg[56:]
5744 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5745 if "OK" not in res:
5746 raise Exception("EAPOL_RX failed")
5747 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5748 if ev is None:
5749 raise Exception("Disconnect event not seen")
5750 dev[0].request("WPS_CANCEL")
5751 dev[0].flush_scan_cache()
5752
5753def test_ap_wps_m2_unknown_opcode(dev, apdev):
5754 """WPS and M2 but unknown opcode"""
5755 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5756 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5757 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5758 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5759 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5760 logger.debug("M2")
5761 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5762 if ev is None:
5763 raise Exception("Timeout on EAPOL-TX")
5764 hapd.request("SET ext_eapol_frame_io 0")
5765 dev[0].request("SET ext_eapol_frame_io 0")
5766 msg = ev.split(' ')[2]
5767 # Replace opcode. This will be discarded in EAP-WSC processing.
5768 msg = msg[0:32] + "00" + msg[34:]
5769 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5770 if "OK" not in res:
5771 raise Exception("EAPOL_RX failed")
5772 dev[0].request("WPS_CANCEL")
5773 dev[0].wait_disconnected()
5774 dev[0].flush_scan_cache()
5775
5776def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5777 """WPS and M2 but unknown opcode (WSC_Start)"""
5778 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5779 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5780 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5781 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5782 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5783 logger.debug("M2")
5784 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5785 if ev is None:
5786 raise Exception("Timeout on EAPOL-TX")
5787 hapd.request("SET ext_eapol_frame_io 0")
5788 dev[0].request("SET ext_eapol_frame_io 0")
5789 msg = ev.split(' ')[2]
5790 # Replace opcode. This will be discarded in EAP-WSC processing.
5791 msg = msg[0:32] + "01" + msg[34:]
5792 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5793 if "OK" not in res:
5794 raise Exception("EAPOL_RX failed")
5795 dev[0].request("WPS_CANCEL")
5796 dev[0].wait_disconnected()
5797 dev[0].flush_scan_cache()
5798
5799def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5800 """WPS and M2 but unknown opcode (WSC_Done)"""
5801 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5802 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5803 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5804 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5805 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5806 logger.debug("M2")
5807 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5808 if ev is None:
5809 raise Exception("Timeout on EAPOL-TX")
5810 hapd.request("SET ext_eapol_frame_io 0")
5811 dev[0].request("SET ext_eapol_frame_io 0")
5812 msg = ev.split(' ')[2]
5813 # Replace opcode. This will be discarded in WPS Enrollee processing.
5814 msg = msg[0:32] + "05" + msg[34:]
5815 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5816 if "OK" not in res:
5817 raise Exception("EAPOL_RX failed")
5818 dev[0].request("WPS_CANCEL")
5819 dev[0].wait_disconnected()
5820 dev[0].flush_scan_cache()
5821
5822def wps_m2_but_other(dev, apdev, title, msgtype):
5823 addr,bssid,hapd = wps_start_ext(apdev, dev)
5824 wps_ext_eap_identity_req(dev, hapd, bssid)
5825 wps_ext_eap_identity_resp(hapd, dev, addr)
5826 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5827 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5828 logger.debug(title)
5829 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5830 if ev is None:
5831 raise Exception("Timeout on EAPOL-TX")
5832 hapd.request("SET ext_eapol_frame_io 0")
5833 dev.request("SET ext_eapol_frame_io 0")
5834 msg = ev.split(' ')[2]
5835 if msg[46:54] != '10220001':
5836 raise Exception("Could not find Message Type attribute")
5837 # Replace Message Type value. This will be rejected.
5838 msg = msg[0:54] + msgtype + msg[56:]
5839 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5840 if "OK" not in res:
5841 raise Exception("EAPOL_RX failed")
5842 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5843 if ev is None:
5844 raise Exception("WPS-FAIL event not seen")
5845 dev.request("WPS_CANCEL")
5846 dev.wait_disconnected()
5847
5848def wps_m4_but_other(dev, apdev, title, msgtype):
5849 addr,bssid,hapd = wps_start_ext(apdev, dev)
5850 wps_ext_eap_identity_req(dev, hapd, bssid)
5851 wps_ext_eap_identity_resp(hapd, dev, addr)
5852 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5853 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5854 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5855 wps_ext_eap_wsc(hapd, dev, addr, "M3")
5856 logger.debug(title)
5857 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5858 if ev is None:
5859 raise Exception("Timeout on EAPOL-TX")
5860 hapd.request("SET ext_eapol_frame_io 0")
5861 dev.request("SET ext_eapol_frame_io 0")
5862 msg = ev.split(' ')[2]
5863 if msg[46:54] != '10220001':
5864 raise Exception("Could not find Message Type attribute")
5865 # Replace Message Type value. This will be rejected.
5866 msg = msg[0:54] + msgtype + msg[56:]
5867 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5868 if "OK" not in res:
5869 raise Exception("EAPOL_RX failed")
5870 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5871 if ev is None:
5872 raise Exception("WPS-FAIL event not seen")
5873 dev.request("WPS_CANCEL")
5874 dev.wait_disconnected()
5875
5876def test_ap_wps_m2_msg_type_m4(dev, apdev):
5877 """WPS and M2 but Message Type M4"""
5878 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5879
5880def test_ap_wps_m2_msg_type_m6(dev, apdev):
5881 """WPS and M2 but Message Type M6"""
5882 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5883
5884def test_ap_wps_m2_msg_type_m8(dev, apdev):
5885 """WPS and M2 but Message Type M8"""
5886 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5887
5888def test_ap_wps_m4_msg_type_m2(dev, apdev):
5889 """WPS and M4 but Message Type M2"""
5890 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5891
5892def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5893 """WPS and M4 but Message Type M2D"""
5894 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5895
9fd6804d 5896@remote_compatible
24b7f282
JM
5897def test_ap_wps_config_methods(dev, apdev):
5898 """WPS configuration method parsing"""
5899 ssid = "test-wps-conf"
5900 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5901 "wpa_passphrase": "12345678", "wpa": "2",
5902 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5903 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
8b8a1864 5904 hapd = hostapd.add_ap(apdev[0], params)
24b7f282
JM
5905 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5906 "wpa_passphrase": "12345678", "wpa": "2",
5907 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5908 "config_methods": "display push_button" }
8b8a1864 5909 hapd2 = hostapd.add_ap(apdev[1], params)
476daa05
JM
5910
5911def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5912 """WPS UPnP SetSelectedRegistrar protocol testing"""
5913 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 5914 hapd = add_ssdp_ap(apdev[0], ap_uuid)
476daa05
JM
5915
5916 location = ssdp_get_location(ap_uuid)
5917 urls = upnp_get_urls(location)
5918 eventurl = urlparse.urlparse(urls['event_sub_url'])
5919 ctrlurl = urlparse.urlparse(urls['control_url'])
5920 url = urlparse.urlparse(location)
5921 conn = httplib.HTTPConnection(url.netloc)
5922
5923 class WPSERHTTPServer(SocketServer.StreamRequestHandler):
5924 def handle(self):
5925 data = self.rfile.readline().strip()
5926 logger.debug(data)
5927 self.wfile.write(gen_wps_event())
5928
5929 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5930 server.timeout = 1
5931
5932 headers = { "callback": '<http://127.0.0.1:12345/event>',
5933 "NT": "upnp:event",
5934 "timeout": "Second-1234" }
5935 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5936 resp = conn.getresponse()
5937 if resp.status != 200:
5938 raise Exception("Unexpected HTTP response: %d" % resp.status)
5939 sid = resp.getheader("sid")
5940 logger.debug("Subscription SID " + sid)
5941 server.handle_request()
5942
5943 tests = [ (500, "10"),
5944 (200, "104a000110" + "1041000101" + "101200020000" +
5945 "105300023148" +
5946 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5947 "10480010362db47ba53a519188fb5458b986b2e4"),
5948 (200, "104a000110" + "1041000100" + "101200020000" +
5949 "105300020000"),
5950 (200, "104a000110" + "1041000100"),
5951 (200, "104a000110") ]
5952 for status,test in tests:
5953 tlvs = binascii.unhexlify(test)
5954 newmsg = base64.b64encode(tlvs)
5955 msg = '<?xml version="1.0"?>\n'
5956 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5957 msg += '<s:Body>'
5958 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5959 msg += '<NewMessage>'
5960 msg += newmsg
5961 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
5962 headers = { "Content-type": 'text/xml; charset="utf-8"' }
5963 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
5964 conn.request("POST", ctrlurl.path, msg, headers)
5965 resp = conn.getresponse()
5966 if resp.status != status:
5967 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
96038a5f
JM
5968
5969def test_ap_wps_adv_oom(dev, apdev):
5970 """WPS AP and advertisement OOM"""
5971 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 5972 hapd = add_ssdp_ap(apdev[0], ap_uuid)
96038a5f
JM
5973
5974 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
5975 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5976 no_recv=True)
5977 time.sleep(0.2)
5978
5979 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
5980 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
5981 no_recv=True)
5982 time.sleep(0.2)
5983
5984 with alloc_fail(hapd, 1,
5985 "next_advertisement;advertisement_state_machine_stop"):
5986 hapd.disable()
5987
5988 with alloc_fail(hapd, 1, "ssdp_listener_start"):
5989 if "FAIL" not in hapd.request("ENABLE"):
5990 raise Exception("ENABLE succeeded during OOM")
926404a6
JM
5991
5992def test_wps_config_methods(dev):
5993 """WPS config method update"""
5994 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
5995 wpas.interface_add("wlan5")
5996 if "OK" not in wpas.request("SET config_methods display label"):
5997 raise Exception("Failed to set config_methods")
5998 if wpas.request("GET config_methods").strip() != "display label":
5999 raise Exception("config_methods were not updated")
6000 if "OK" not in wpas.request("SET config_methods "):
6001 raise Exception("Failed to clear config_methods")
6002 if wpas.request("GET config_methods").strip() != "":
6003 raise Exception("config_methods were not cleared")
7511ead0
JM
6004
6005WPS_VENDOR_ID_WFA = 14122
6006WPS_VENDOR_TYPE = 1
6007
6008# EAP-WSC Op-Code values
6009WSC_Start = 0x01
6010WSC_ACK = 0x02
6011WSC_NACK = 0x03
6012WSC_MSG = 0x04
6013WSC_Done = 0x05
6014WSC_FRAG_ACK = 0x06
6015
6016ATTR_AP_CHANNEL = 0x1001
6017ATTR_ASSOC_STATE = 0x1002
6018ATTR_AUTH_TYPE = 0x1003
6019ATTR_AUTH_TYPE_FLAGS = 0x1004
6020ATTR_AUTHENTICATOR = 0x1005
6021ATTR_CONFIG_METHODS = 0x1008
6022ATTR_CONFIG_ERROR = 0x1009
6023ATTR_CONFIRM_URL4 = 0x100a
6024ATTR_CONFIRM_URL6 = 0x100b
6025ATTR_CONN_TYPE = 0x100c
6026ATTR_CONN_TYPE_FLAGS = 0x100d
6027ATTR_CRED = 0x100e
6028ATTR_ENCR_TYPE = 0x100f
6029ATTR_ENCR_TYPE_FLAGS = 0x1010
6030ATTR_DEV_NAME = 0x1011
6031ATTR_DEV_PASSWORD_ID = 0x1012
6032ATTR_E_HASH1 = 0x1014
6033ATTR_E_HASH2 = 0x1015
6034ATTR_E_SNONCE1 = 0x1016
6035ATTR_E_SNONCE2 = 0x1017
6036ATTR_ENCR_SETTINGS = 0x1018
6037ATTR_ENROLLEE_NONCE = 0x101a
6038ATTR_FEATURE_ID = 0x101b
6039ATTR_IDENTITY = 0x101c
6040ATTR_IDENTITY_PROOF = 0x101d
6041ATTR_KEY_WRAP_AUTH = 0x101e
6042ATTR_KEY_ID = 0x101f
6043ATTR_MAC_ADDR = 0x1020
6044ATTR_MANUFACTURER = 0x1021
6045ATTR_MSG_TYPE = 0x1022
6046ATTR_MODEL_NAME = 0x1023
6047ATTR_MODEL_NUMBER = 0x1024
6048ATTR_NETWORK_INDEX = 0x1026
6049ATTR_NETWORK_KEY = 0x1027
6050ATTR_NETWORK_KEY_INDEX = 0x1028
6051ATTR_NEW_DEVICE_NAME = 0x1029
6052ATTR_NEW_PASSWORD = 0x102a
6053ATTR_OOB_DEVICE_PASSWORD = 0x102c
6054ATTR_OS_VERSION = 0x102d
6055ATTR_POWER_LEVEL = 0x102f
6056ATTR_PSK_CURRENT = 0x1030
6057ATTR_PSK_MAX = 0x1031
6058ATTR_PUBLIC_KEY = 0x1032
6059ATTR_RADIO_ENABLE = 0x1033
6060ATTR_REBOOT = 0x1034
6061ATTR_REGISTRAR_CURRENT = 0x1035
6062ATTR_REGISTRAR_ESTABLISHED = 0x1036
6063ATTR_REGISTRAR_LIST = 0x1037
6064ATTR_REGISTRAR_MAX = 0x1038
6065ATTR_REGISTRAR_NONCE = 0x1039
6066ATTR_REQUEST_TYPE = 0x103a
6067ATTR_RESPONSE_TYPE = 0x103b
6068ATTR_RF_BANDS = 0x103c
6069ATTR_R_HASH1 = 0x103d
6070ATTR_R_HASH2 = 0x103e
6071ATTR_R_SNONCE1 = 0x103f
6072ATTR_R_SNONCE2 = 0x1040
6073ATTR_SELECTED_REGISTRAR = 0x1041
6074ATTR_SERIAL_NUMBER = 0x1042
6075ATTR_WPS_STATE = 0x1044
6076ATTR_SSID = 0x1045
6077ATTR_TOTAL_NETWORKS = 0x1046
6078ATTR_UUID_E = 0x1047
6079ATTR_UUID_R = 0x1048
6080ATTR_VENDOR_EXT = 0x1049
6081ATTR_VERSION = 0x104a
6082ATTR_X509_CERT_REQ = 0x104b
6083ATTR_X509_CERT = 0x104c
6084ATTR_EAP_IDENTITY = 0x104d
6085ATTR_MSG_COUNTER = 0x104e
6086ATTR_PUBKEY_HASH = 0x104f
6087ATTR_REKEY_KEY = 0x1050
6088ATTR_KEY_LIFETIME = 0x1051
6089ATTR_PERMITTED_CFG_METHODS = 0x1052
6090ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
6091ATTR_PRIMARY_DEV_TYPE = 0x1054
6092ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
6093ATTR_PORTABLE_DEV = 0x1056
6094ATTR_AP_SETUP_LOCKED = 0x1057
6095ATTR_APPLICATION_EXT = 0x1058
6096ATTR_EAP_TYPE = 0x1059
6097ATTR_IV = 0x1060
6098ATTR_KEY_PROVIDED_AUTO = 0x1061
6099ATTR_802_1X_ENABLED = 0x1062
6100ATTR_APPSESSIONKEY = 0x1063
6101ATTR_WEPTRANSMITKEY = 0x1064
6102ATTR_REQUESTED_DEV_TYPE = 0x106a
6103
6104# Message Type
6105WPS_Beacon = 0x01
6106WPS_ProbeRequest = 0x02
6107WPS_ProbeResponse = 0x03
6108WPS_M1 = 0x04
6109WPS_M2 = 0x05
6110WPS_M2D = 0x06
6111WPS_M3 = 0x07
6112WPS_M4 = 0x08
6113WPS_M5 = 0x09
6114WPS_M6 = 0x0a
6115WPS_M7 = 0x0b
6116WPS_M8 = 0x0c
6117WPS_WSC_ACK = 0x0d
6118WPS_WSC_NACK = 0x0e
6119WPS_WSC_DONE = 0x0f
6120
6121def get_wsc_msg(dev):
6122 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6123 if ev is None:
6124 raise Exception("Timeout on EAPOL-TX")
6125 data = binascii.unhexlify(ev.split(' ')[2])
6126 msg = {}
6127
6128 # Parse EAPOL header
6129 if len(data) < 4:
6130 raise Exception("No room for EAPOL header")
6131 version,type,length = struct.unpack('>BBH', data[0:4])
6132 msg['eapol_version'] = version
6133 msg['eapol_type'] = type
6134 msg['eapol_length'] = length
6135 data = data[4:]
6136 if length != len(data):
6137 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6138 if type != 0:
6139 raise Exception("Unexpected EAPOL header type: %d" % type)
6140
6141 # Parse EAP header
6142 if len(data) < 4:
6143 raise Exception("No room for EAP header")
6144 code,identifier,length = struct.unpack('>BBH', data[0:4])
6145 msg['eap_code'] = code
6146 msg['eap_identifier'] = identifier
6147 msg['eap_length'] = length
6148 data = data[4:]
6149 if msg['eapol_length'] != msg['eap_length']:
6150 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6151
6152 # Parse EAP expanded header
6153 if len(data) < 1:
6154 raise Exception("No EAP type included")
6155 msg['eap_type'], = struct.unpack('B', data[0])
6156 data = data[1:]
6157
6158 if msg['eap_type'] == 254:
6159 if len(data) < 3 + 4:
6160 raise Exception("Truncated EAP expanded header")
6161 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', '\0' + data[0:7])
6162 data = data[7:]
6163 else:
6164 raise Exception("Unexpected EAP type")
6165
6166 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6167 raise Exception("Unexpected Vendor-Id")
6168 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6169 raise Exception("Unexpected Vendor-Type")
6170
6171 # Parse EAP-WSC header
6172 if len(data) < 2:
6173 raise Exception("Truncated EAP-WSC header")
6174 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6175 data = data[2:]
6176
6177 # Parse WSC attributes
6178 msg['raw_attrs'] = data
6179 attrs = {}
6180 while len(data) > 0:
6181 if len(data) < 4:
6182 raise Exception("Truncated attribute header")
6183 attr,length = struct.unpack('>HH', data[0:4])
6184 data = data[4:]
6185 if length > len(data):
6186 raise Exception("Truncated attribute 0x%04x" % attr)
6187 attrs[attr] = data[0:length]
6188 data = data[length:]
6189 msg['wsc_attrs'] = attrs
6190
6191 if ATTR_MSG_TYPE in attrs:
6192 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6193
6194 return msg
6195
6196def recv_wsc_msg(dev, opcode, msg_type):
6197 msg = get_wsc_msg(dev)
6198 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6199 raise Exception("Unexpected Op-Code/MsgType")
6200 return msg, msg['wsc_attrs'], msg['raw_attrs']
6201
6202def build_wsc_attr(attr, payload):
6203 return struct.pack('>HH', attr, len(payload)) + payload
6204
6205def build_attr_msg_type(msg_type):
6206 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6207
6208def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6209 length = 4 + 8 + 2 + len(payload)
6210 # EAPOL header
6211 msg = struct.pack('>BBH', 2, 0, length)
6212 # EAP header
6213 msg += struct.pack('>BBH', eap_code, eap_id, length)
6214 # EAP expanded header for EAP-WSC
6215 msg += struct.pack('B', 254)
6216 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6217 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6218 # EAP-WSC header
6219 msg += struct.pack('BB', opcode, 0)
6220 # WSC attributes
6221 msg += payload
6222 return msg
6223
6224def build_eap_success(eap_id):
6225 length = 4
6226 # EAPOL header
6227 msg = struct.pack('>BBH', 2, 0, length)
6228 # EAP header
6229 msg += struct.pack('>BBH', 3, eap_id, length)
6230 return msg
6231
6232def build_eap_failure(eap_id):
6233 length = 4
6234 # EAPOL header
6235 msg = struct.pack('>BBH', 2, 0, length)
6236 # EAP header
6237 msg += struct.pack('>BBH', 4, eap_id, length)
6238 return msg
6239
6240def send_wsc_msg(dev, src, msg):
6241 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg))
6242 if "OK" not in res:
6243 raise Exception("EAPOL_RX failed")
6244
6245group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6246group_5_generator = 2
6247
6248def wsc_kdf(key, label, bits):
6249 result = ''
6250 i = 1
6251 while len(result) * 8 < bits:
6252 data = struct.pack('>L', i) + label + struct.pack('>L', bits)
6253 m = hmac.new(key, data, hashlib.sha256)
6254 result += m.digest()
6255 i += 1
6256 return result[0:bits / 8]
6257
6258def wsc_keys(kdk):
6259 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6260 authkey = keys[0:32]
6261 keywrapkey = keys[32:48]
6262 emsk = keys[48:80]
6263 return authkey,keywrapkey,emsk
6264
6265def wsc_dev_pw_half_psk(authkey, dev_pw):
6266 m = hmac.new(authkey, dev_pw, hashlib.sha256)
6267 return m.digest()[0:16]
6268
6269def wsc_dev_pw_psk(authkey, dev_pw):
6270 dev_pw_1 = dev_pw[0:len(dev_pw) / 2]
6271 dev_pw_2 = dev_pw[len(dev_pw) / 2:]
6272 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6273 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6274 return psk1,psk2
6275
6276def build_attr_authenticator(authkey, prev_msg, curr_msg):
6277 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6278 auth = m.digest()[0:8]
6279 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6280
6281def build_attr_encr_settings(authkey, keywrapkey, data):
6282 m = hmac.new(authkey, data, hashlib.sha256)
6283 kwa = m.digest()[0:8]
6284 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6285 iv = 16*'\x99'
6286 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6287 pad_len = 16 - len(data) % 16
6288 ps = pad_len * struct.pack('B', pad_len)
6289 data += ps
6290 wrapped = aes.encrypt(data)
6291 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6292
6293def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6294 if len(data) < 32 or len(data) % 16 != 0:
6295 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6296 iv = data[0:16]
6297 encr = data[16:]
6298 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6299 decrypted = aes.decrypt(encr)
6300 pad_len, = struct.unpack('B', decrypted[-1])
6301 if pad_len > len(decrypted):
6302 raise Exception("Invalid padding in Encrypted Settings")
6303 for i in range(-pad_len, -1):
6304 if decrypted[i] != decrypted[-1]:
6305 raise Exception("Invalid PS value in Encrypted Settings")
db98b587 6306
7511ead0
JM
6307 decrypted = decrypted[0:len(decrypted) - pad_len]
6308 if len(decrypted) < 12:
6309 raise Exception("Truncated Encrypted Settings plaintext")
6310 kwa = decrypted[-12:]
6311 attr,length = struct.unpack(">HH", kwa[0:4])
6312 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6313 raise Exception("Invalid KWA header")
6314 kwa = kwa[4:]
6315 decrypted = decrypted[0:len(decrypted) - 12]
6316
6317 m = hmac.new(authkey, decrypted, hashlib.sha256)
6318 calc_kwa = m.digest()[0:8]
6319 if kwa != calc_kwa:
6320 raise Exception("KWA mismatch")
6321
6322 return decrypted
6323
6324def zeropad_str(val, pad_len):
6325 while len(val) < pad_len * 2:
6326 val = '0' + val
6327 return val
6328
6329def wsc_dh_init():
6330 # For now, use a hardcoded private key. In theory, this is supposed to be
6331 # randomly selected.
6332 own_private = 0x123456789
6333 own_public = pow(group_5_generator, own_private, group_5_prime)
6334 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6335 return own_private, pk
6336
6337def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6338 peer_public = long(binascii.hexlify(peer_pk), 16)
6339 if peer_public < 2 or peer_public >= group_5_prime:
6340 raise Exception("Invalid peer public key")
6341 if pow(peer_public, (group_5_prime - 1) / 2, group_5_prime) != 1:
6342 raise Exception("Unexpected Legendre symbol for peer public key")
6343
6344 shared_secret = pow(peer_public, own_private, group_5_prime)
6345 ss = zeropad_str(format(shared_secret, "02x"), 192)
6346 logger.debug("DH shared secret: " + ss)
6347
6348 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6349 logger.debug("DHKey: " + binascii.hexlify(dhkey))
6350
6351 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6352 kdk = m.digest()
6353 logger.debug("KDK: " + binascii.hexlify(kdk))
6354 authkey,keywrapkey,emsk = wsc_keys(kdk)
6355 logger.debug("AuthKey: " + binascii.hexlify(authkey))
6356 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey))
6357 logger.debug("EMSK: " + binascii.hexlify(emsk))
6358 return authkey,keywrapkey
6359
6360def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6361 psk1,psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6362 logger.debug("PSK1: " + binascii.hexlify(psk1))
6363 logger.debug("PSK2: " + binascii.hexlify(psk2))
6364
6365 # Note: Secret values are supposed to be random, but hardcoded values are
6366 # fine for testing.
6367 s1 = 16*'\x77'
6368 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6369 hash1 = m.digest()
6370 logger.debug("Hash1: " + binascii.hexlify(hash1))
6371
6372 s2 = 16*'\x88'
6373 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6374 hash2 = m.digest()
6375 logger.debug("Hash2: " + binascii.hexlify(hash2))
6376 return s1,s2,hash1,hash2
6377
6378def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6379 manufacturer='', model_name='', config_methods='\x00\x00'):
6380 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6381 attrs += build_attr_msg_type(WPS_M1)
6382 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6383 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6384 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6385 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6386 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6387 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6388 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6389 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6390 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6391 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6392 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6393 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6394 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6395 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6396 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6397 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6398 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6399 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6400 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6401 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6402 m1 = build_eap_wsc(2, eap_id, attrs)
6403 return m1, attrs
6404
6405def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6406 dev_pw_id='\x00\x00', eap_code=1):
6407 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6408 attrs += build_attr_msg_type(WPS_M2)
6409 if e_nonce:
6410 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6411 if r_nonce:
6412 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6413 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6414 if r_pk:
6415 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6416 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6417 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6418 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6419 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6420 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6421 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6422 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6423 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6424 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6425 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6426 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6427 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6428 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6429 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6430 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6431 attrs += build_attr_authenticator(authkey, m1, attrs)
6432 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6433 return m2, attrs
6434
6435def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6436 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6437 attrs += build_attr_msg_type(WPS_M2D)
6438 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6439 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6440 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6441 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6442 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6443 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6444 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6445 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6446 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6447 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6448 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6449 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6450 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6451 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6452 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6453 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6454 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6455 if dev_pw_id:
6456 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6457 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6458 return m2d, attrs
6459
6460def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6461 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6462 if msg_type is not None:
6463 attrs += build_attr_msg_type(msg_type)
6464 if e_nonce:
6465 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6466 if r_nonce:
6467 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6468 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6469 return msg, attrs
6470
6471def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6472 msg_type=WPS_WSC_NACK, eap_code=1):
6473 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6474 if msg_type is not None:
6475 attrs += build_attr_msg_type(msg_type)
6476 if e_nonce:
6477 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6478 if r_nonce:
6479 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6480 if config_error:
6481 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6482 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6483 return msg, attrs
6484
6485def test_wps_ext(dev, apdev):
6486 """WPS against external implementation"""
6487 pin = "12345670"
6488 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6489 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6490 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6491
6492 logger.debug("Receive WSC/Start from AP")
6493 msg = get_wsc_msg(hapd)
6494 if msg['wsc_opcode'] != WSC_Start:
6495 raise Exception("Unexpected Op-Code for WSC/Start")
6496 wsc_start_id = msg['eap_identifier']
6497
6498 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6499 uuid_e = 16*'\x11'
6500 e_nonce = 16*'\x22'
6501 own_private, e_pk = wsc_dh_init()
6502
6503 logger.debug("Send M1 to AP")
6504 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6505 e_nonce, e_pk)
6506 send_wsc_msg(hapd, addr, m1)
6507
6508 logger.debug("Receive M2 from AP")
6509 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6510
6511 authkey,keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6512 mac_addr, e_nonce,
6513 m2_attrs[ATTR_REGISTRAR_NONCE])
6514 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6515 m2_attrs[ATTR_PUBLIC_KEY])
6516
6517 logger.debug("Send M3 to AP")
6518 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6519 attrs += build_attr_msg_type(WPS_M3)
6520 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6521 m2_attrs[ATTR_REGISTRAR_NONCE])
6522 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6523 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6524 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6525 raw_m3_attrs = attrs
6526 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6527 send_wsc_msg(hapd, addr, m3)
6528
6529 logger.debug("Receive M4 from AP")
6530 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6531
6532 logger.debug("Send M5 to AP")
6533 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6534 attrs += build_attr_msg_type(WPS_M5)
6535 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6536 m2_attrs[ATTR_REGISTRAR_NONCE])
6537 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6538 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6539 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6540 raw_m5_attrs = attrs
6541 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6542 send_wsc_msg(hapd, addr, m5)
6543
6544 logger.debug("Receive M6 from AP")
6545 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6546
6547 logger.debug("Send M7 to AP")
6548 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6549 attrs += build_attr_msg_type(WPS_M7)
6550 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6551 m2_attrs[ATTR_REGISTRAR_NONCE])
6552 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6553 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6554 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6555 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6556 raw_m7_attrs = attrs
6557 send_wsc_msg(hapd, addr, m7)
6558
6559 logger.debug("Receive M8 from AP")
6560 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6561 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6562 m8_attrs[ATTR_ENCR_SETTINGS])
6563 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred))
6564
6565 logger.debug("Prepare WSC_Done")
6566 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6567 attrs += build_attr_msg_type(WPS_WSC_DONE)
6568 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6569 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6570 m2_attrs[ATTR_REGISTRAR_NONCE])
6571 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6572 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6573 # AP disconnects.
6574
6575 uuid_r = 16*'\x33'
6576 r_nonce = 16*'\x44'
6577
6578 eap_id = wsc_start_id
6579 logger.debug("Send WSC/Start to STA")
6580 wsc_start = build_eap_wsc(1, eap_id, "", opcode=WSC_Start)
6581 send_wsc_msg(dev[0], bssid, wsc_start)
6582 eap_id = (eap_id + 1) % 256
6583
6584 logger.debug("Receive M1 from STA")
6585 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6586
6587 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6588 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6589 r_nonce)
6590 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6591 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6592
6593 logger.debug("Send M2 to STA")
6594 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6595 m1_attrs[ATTR_ENROLLEE_NONCE],
6596 r_nonce, uuid_r, e_pk)
6597 send_wsc_msg(dev[0], bssid, m2)
6598 eap_id = (eap_id + 1) % 256
6599
6600 logger.debug("Receive M3 from STA")
6601 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6602
6603 logger.debug("Send M4 to STA")
6604 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6605 attrs += build_attr_msg_type(WPS_M4)
6606 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6607 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6608 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6609 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6610 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6611 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6612 raw_m4_attrs = attrs
6613 m4 = build_eap_wsc(1, eap_id, attrs)
6614 send_wsc_msg(dev[0], bssid, m4)
6615 eap_id = (eap_id + 1) % 256
6616
6617 logger.debug("Receive M5 from STA")
6618 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6619
6620 logger.debug("Send M6 to STA")
6621 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6622 attrs += build_attr_msg_type(WPS_M6)
6623 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6624 m1_attrs[ATTR_ENROLLEE_NONCE])
6625 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6626 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6627 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6628 raw_m6_attrs = attrs
6629 m6 = build_eap_wsc(1, eap_id, attrs)
6630 send_wsc_msg(dev[0], bssid, m6)
6631 eap_id = (eap_id + 1) % 256
6632
6633 logger.debug("Receive M7 from STA")
6634 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6635
6636 logger.debug("Send M8 to STA")
6637 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6638 attrs += build_attr_msg_type(WPS_M8)
6639 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6640 m1_attrs[ATTR_ENROLLEE_NONCE])
6641 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6642 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6643 raw_m8_attrs = attrs
6644 m8 = build_eap_wsc(1, eap_id, attrs)
6645 send_wsc_msg(dev[0], bssid, m8)
6646 eap_id = (eap_id + 1) % 256
6647
6648 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6649 if ev is None:
6650 raise Exception("wpa_supplicant did not report credential")
6651
6652 logger.debug("Receive WSC_Done from STA")
6653 msg = get_wsc_msg(dev[0])
6654 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6655 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6656
6657 logger.debug("Send WSC_Done to AP")
6658 hapd.request("SET ext_eapol_frame_io 0")
6659 dev[0].request("SET ext_eapol_frame_io 0")
6660 send_wsc_msg(hapd, addr, wsc_done)
6661
6662 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6663 if ev is None:
6664 raise Exception("hostapd did not report WPS success")
6665
6666 dev[0].wait_connected()
6667
6668def wps_start_kwa(dev, apdev):
6669 pin = "12345670"
6670 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6671 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6672 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6673 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6674
6675 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6676 uuid_r = 16*'\x33'
6677 r_nonce = 16*'\x44'
6678 own_private, e_pk = wsc_dh_init()
6679
6680 logger.debug("Receive M1 from STA")
6681 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6682 eap_id = (msg['eap_identifier'] + 1) % 256
6683
6684 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6685 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6686 r_nonce)
6687 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6688 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6689
6690 logger.debug("Send M2 to STA")
6691 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6692 m1_attrs[ATTR_ENROLLEE_NONCE],
6693 r_nonce, uuid_r, e_pk)
6694 send_wsc_msg(dev[0], bssid, m2)
6695 eap_id = (eap_id + 1) % 256
6696
6697 logger.debug("Receive M3 from STA")
6698 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6699
6700 logger.debug("Send M4 to STA")
6701 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6702 attrs += build_attr_msg_type(WPS_M4)
6703 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6704 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6705 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6706
6707 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6708
6709def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6710 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6711 m4 = build_eap_wsc(1, eap_id, attrs)
6712 send_wsc_msg(dev[0], bssid, m4)
6713 eap_id = (eap_id + 1) % 256
6714
6715 logger.debug("Receive M5 from STA")
6716 msg = get_wsc_msg(dev[0])
6717 if msg['wsc_opcode'] != WSC_NACK:
6718 raise Exception("Unexpected message - expected WSC_Nack")
6719
6720 dev[0].request("WPS_CANCEL")
6721 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6722 dev[0].wait_disconnected()
6723
6724def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6725 """WPS and KWA error: No KWA attribute"""
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 without KWA
6729 iv = 16*'\x99'
6730 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6731 pad_len = 16 - len(data) % 16
6732 ps = pad_len * struct.pack('B', pad_len)
6733 data += ps
6734 wrapped = aes.encrypt(data)
6735 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6736 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6737
6738def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6739 """WPS and KWA error: Data after KWA"""
6740 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6741 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6742 # Encrypted Settings and data after KWA
6743 m = hmac.new(authkey, data, hashlib.sha256)
6744 kwa = m.digest()[0:8]
6745 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6746 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6747 iv = 16*'\x99'
6748 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6749 pad_len = 16 - len(data) % 16
6750 ps = pad_len * struct.pack('B', pad_len)
6751 data += ps
6752 wrapped = aes.encrypt(data)
6753 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6754 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6755
6756def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6757 """WPS and KWA error: KWA mismatch"""
6758 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6759 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6760 # Encrypted Settings and KWA with incorrect value
6761 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6762 iv = 16*'\x99'
6763 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6764 pad_len = 16 - len(data) % 16
6765 ps = pad_len * struct.pack('B', pad_len)
6766 data += ps
6767 wrapped = aes.encrypt(data)
6768 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6769 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6770
6771def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6772 pin = "12345670"
6773 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6774 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6775 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6776 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6777
6778 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6779 uuid_r = 16*'\x33'
6780 r_nonce = 16*'\x44'
6781 own_private, e_pk = wsc_dh_init()
6782
6783 logger.debug("Receive M1 from STA")
6784 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6785 eap_id = (msg['eap_identifier'] + 1) % 256
6786
6787 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6788 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6789 r_nonce)
6790 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6791 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6792
6793 logger.debug("Send M2 to STA")
6794 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6795 m1_attrs[ATTR_ENROLLEE_NONCE],
6796 r_nonce, uuid_r, e_pk)
6797 send_wsc_msg(dev[0], bssid, m2)
6798 eap_id = (eap_id + 1) % 256
6799
6800 logger.debug("Receive M3 from STA")
6801 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6802
6803 logger.debug("Send M4 to STA")
6804 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6805 attrs += build_attr_msg_type(WPS_M4)
6806 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6807 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6808 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6809 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6810 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6811 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6812 raw_m4_attrs = attrs
6813 m4 = build_eap_wsc(1, eap_id, attrs)
6814 send_wsc_msg(dev[0], bssid, m4)
6815 eap_id = (eap_id + 1) % 256
6816
6817 logger.debug("Receive M5 from STA")
6818 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6819
6820 logger.debug("Send M6 to STA")
6821 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6822 attrs += build_attr_msg_type(WPS_M6)
6823 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6824 m1_attrs[ATTR_ENROLLEE_NONCE])
6825 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6826 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6827 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6828 raw_m6_attrs = attrs
6829 m6 = build_eap_wsc(1, eap_id, attrs)
6830 send_wsc_msg(dev[0], bssid, m6)
6831 eap_id = (eap_id + 1) % 256
6832
6833 logger.debug("Receive M7 from STA")
6834 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6835
6836 logger.debug("Send M8 to STA")
6837 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6838 attrs += build_attr_msg_type(WPS_M8)
6839 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6840 m1_attrs[ATTR_ENROLLEE_NONCE])
6841 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6842 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6843 raw_m8_attrs = attrs
6844 m8 = build_eap_wsc(1, eap_id, attrs)
6845 send_wsc_msg(dev[0], bssid, m8)
6846 eap_id = (eap_id + 1) % 256
6847
6848 if no_connect:
6849 logger.debug("Receive WSC_Done from STA")
6850 msg = get_wsc_msg(dev[0])
6851 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6852 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6853
6854 hapd.request("SET ext_eapol_frame_io 0")
6855 dev[0].request("SET ext_eapol_frame_io 0")
6856
6857 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6858
6859 dev[0].wait_disconnected()
6860 dev[0].request("REMOVE_NETWORK all")
6861 elif connect:
6862 logger.debug("Receive WSC_Done from STA")
6863 msg = get_wsc_msg(dev[0])
6864 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6865 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6866
6867 hapd.request("SET ext_eapol_frame_io 0")
6868 dev[0].request("SET ext_eapol_frame_io 0")
6869
6870 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6871
6872 dev[0].wait_connected()
6873 else:
6874 # Verify STA NACK's the credential
6875 msg = get_wsc_msg(dev[0])
6876 if msg['wsc_opcode'] != WSC_NACK:
6877 raise Exception("Unexpected message - expected WSC_Nack")
6878 dev[0].request("WPS_CANCEL")
6879 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6880 dev[0].wait_disconnected()
6881
6882def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6883 encr_type='\x00\x08', nw_key="12345678",
6884 mac_addr='\x00\x00\x00\x00\x00\x00'):
6885 attrs = ''
6886 if nw_idx is not None:
6887 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6888 if ssid is not None:
6889 attrs += build_wsc_attr(ATTR_SSID, ssid)
6890 if auth_type is not None:
6891 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6892 if encr_type is not None:
6893 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6894 if nw_key is not None:
6895 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6896 if mac_addr is not None:
6897 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6898 return build_wsc_attr(ATTR_CRED, attrs)
6899
6900def test_wps_ext_cred_proto_success(dev, apdev):
6901 """WPS and Credential: success"""
6902 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6903 m8_cred = build_cred(mac_addr=mac_addr)
6904 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6905
6906def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6907 """WPS and Credential: MAC Address mismatch"""
6908 m8_cred = build_cred()
6909 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6910
6911def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6912 """WPS and Credential: zeropadded attributes"""
6913 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6914 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6915 nw_key="12345678\x00")
6916 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6917
6918def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6919 """WPS and Credential: SSID missing"""
6920 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6921 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6922 wps_run_cred_proto(dev, apdev, m8_cred)
6923
6924def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6925 """WPS and Credential: Zero-length SSID"""
6926 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6927 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6928 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6929
6930def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6931 """WPS and Credential: Auth Type missing"""
6932 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6933 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6934 wps_run_cred_proto(dev, apdev, m8_cred)
6935
6936def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6937 """WPS and Credential: Encr Type missing"""
6938 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6939 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6940 wps_run_cred_proto(dev, apdev, m8_cred)
6941
6942def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6943 """WPS and Credential: Network Key missing"""
6944 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6945 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6946 wps_run_cred_proto(dev, apdev, m8_cred)
6947
6948def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6949 """WPS and Credential: Network Key missing (open)"""
6950 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6951 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6952 encr_type='\x00\x01', nw_key=None, ssid="foo")
6953 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6954
6955def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6956 """WPS and Credential: MAC Address missing"""
6957 m8_cred = build_cred(mac_addr=None)
6958 wps_run_cred_proto(dev, apdev, m8_cred)
6959
6960def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
6961 """WPS and Credential: Invalid Encr Type"""
6962 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6963 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
6964 wps_run_cred_proto(dev, apdev, m8_cred)
6965
6966def test_wps_ext_cred_proto_missing_cred(dev, apdev):
6967 """WPS and Credential: Missing Credential"""
6968 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6969 m8_cred = ''
6970 wps_run_cred_proto(dev, apdev, m8_cred)
6971
6972def test_wps_ext_proto_m2_no_public_key(dev, apdev):
6973 """WPS and no Public Key in M2"""
6974 pin = "12345670"
6975 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6976 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6977 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6978 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6979
6980 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6981 uuid_r = 16*'\x33'
6982 r_nonce = 16*'\x44'
6983 own_private, e_pk = wsc_dh_init()
6984
6985 logger.debug("Receive M1 from STA")
6986 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6987 eap_id = (msg['eap_identifier'] + 1) % 256
6988
6989 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6990 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6991 r_nonce)
6992 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6993 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6994
6995 logger.debug("Send M2 to STA")
6996 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6997 m1_attrs[ATTR_ENROLLEE_NONCE],
6998 r_nonce, uuid_r, None)
6999 send_wsc_msg(dev[0], bssid, m2)
7000 eap_id = (eap_id + 1) % 256
7001
7002 # Verify STA NACK's the credential
7003 msg = get_wsc_msg(dev[0])
7004 if msg['wsc_opcode'] != WSC_NACK:
7005 raise Exception("Unexpected message - expected WSC_Nack")
7006 dev[0].request("WPS_CANCEL")
7007 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7008 dev[0].wait_disconnected()
7009
7010def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
7011 """WPS and invalid Public Key in M2"""
7012 pin = "12345670"
7013 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7014 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7015 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7016 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7017
7018 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7019 uuid_r = 16*'\x33'
7020 r_nonce = 16*'\x44'
7021 own_private, e_pk = wsc_dh_init()
7022
7023 logger.debug("Receive M1 from STA")
7024 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7025 eap_id = (msg['eap_identifier'] + 1) % 256
7026
7027 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7028 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7029 r_nonce)
7030 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7031 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7032
7033 logger.debug("Send M2 to STA")
7034 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7035 m1_attrs[ATTR_ENROLLEE_NONCE],
7036 r_nonce, uuid_r, 192*'\xff')
7037 send_wsc_msg(dev[0], bssid, m2)
7038 eap_id = (eap_id + 1) % 256
7039
7040 # Verify STA NACK's the credential
7041 msg = get_wsc_msg(dev[0])
7042 if msg['wsc_opcode'] != WSC_NACK:
7043 raise Exception("Unexpected message - expected WSC_Nack")
7044 dev[0].request("WPS_CANCEL")
7045 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7046 dev[0].wait_disconnected()
7047
7048def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7049 """WPS and Public Key OOM in M2"""
7050 pin = "12345670"
7051 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7052 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7053 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7054 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7055
7056 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7057 uuid_r = 16*'\x33'
7058 r_nonce = 16*'\x44'
7059 own_private, e_pk = wsc_dh_init()
7060
7061 logger.debug("Receive M1 from STA")
7062 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7063 eap_id = (msg['eap_identifier'] + 1) % 256
7064
7065 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7066 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7067 r_nonce)
7068 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7069 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7070
7071 logger.debug("Send M2 to STA")
7072 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7073 m1_attrs[ATTR_ENROLLEE_NONCE],
7074 r_nonce, uuid_r, e_pk)
7075 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7076 send_wsc_msg(dev[0], bssid, m2)
7077 eap_id = (eap_id + 1) % 256
7078
7079 # Verify STA NACK's the credential
7080 msg = get_wsc_msg(dev[0])
7081 if msg['wsc_opcode'] != WSC_NACK:
7082 raise Exception("Unexpected message - expected WSC_Nack")
7083 dev[0].request("WPS_CANCEL")
7084 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7085 dev[0].wait_disconnected()
7086
7087def test_wps_ext_proto_nack_m3(dev, apdev):
7088 """WPS and NACK M3"""
7089 pin = "12345670"
7090 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7091 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7092 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7093 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7094
7095 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7096 uuid_r = 16*'\x33'
7097 r_nonce = 16*'\x44'
7098 own_private, e_pk = wsc_dh_init()
7099
7100 logger.debug("Receive M1 from STA")
7101 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7102 eap_id = (msg['eap_identifier'] + 1) % 256
7103
7104 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7105 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7106 r_nonce)
7107 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7108 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7109
7110 logger.debug("Send M2 to STA")
7111 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7112 m1_attrs[ATTR_ENROLLEE_NONCE],
7113 r_nonce, uuid_r, e_pk)
7114 send_wsc_msg(dev[0], bssid, m2)
7115 eap_id = (eap_id + 1) % 256
7116
7117 logger.debug("Receive M3 from STA")
7118 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7119
7120 logger.debug("Send NACK to STA")
7121 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7122 r_nonce, config_error='\x01\x23')
7123 send_wsc_msg(dev[0], bssid, msg)
7124 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7125 if ev is None:
7126 raise Exception("Failure not reported")
7127 if "msg=7 config_error=291" not in ev:
7128 raise Exception("Unexpected failure reason: " + ev)
7129
7130def test_wps_ext_proto_nack_m5(dev, apdev):
7131 """WPS and NACK M5"""
7132 pin = "12345670"
7133 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7134 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7135 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7136 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7137
7138 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7139 uuid_r = 16*'\x33'
7140 r_nonce = 16*'\x44'
7141 own_private, e_pk = wsc_dh_init()
7142
7143 logger.debug("Receive M1 from STA")
7144 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7145 eap_id = (msg['eap_identifier'] + 1) % 256
7146
7147 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7148 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7149 r_nonce)
7150 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7151 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7152
7153 logger.debug("Send M2 to STA")
7154 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7155 m1_attrs[ATTR_ENROLLEE_NONCE],
7156 r_nonce, uuid_r, e_pk)
7157 send_wsc_msg(dev[0], bssid, m2)
7158 eap_id = (eap_id + 1) % 256
7159
7160 logger.debug("Receive M3 from STA")
7161 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7162
7163 logger.debug("Send M4 to STA")
7164 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7165 attrs += build_attr_msg_type(WPS_M4)
7166 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7167 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7168 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7169 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7170 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7171 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7172 raw_m4_attrs = attrs
7173 m4 = build_eap_wsc(1, eap_id, attrs)
7174 send_wsc_msg(dev[0], bssid, m4)
7175 eap_id = (eap_id + 1) % 256
7176
7177 logger.debug("Receive M5 from STA")
7178 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7179
7180 logger.debug("Send NACK to STA")
7181 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7182 r_nonce, config_error='\x01\x24')
7183 send_wsc_msg(dev[0], bssid, msg)
7184 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7185 if ev is None:
7186 raise Exception("Failure not reported")
7187 if "msg=9 config_error=292" not in ev:
7188 raise Exception("Unexpected failure reason: " + ev)
7189
7190def wps_nack_m3(dev, apdev):
7191 pin = "00000000"
7192 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7193 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7194 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7195 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7196
7197 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7198 uuid_r = 16*'\x33'
7199 r_nonce = 16*'\x44'
7200 own_private, e_pk = wsc_dh_init()
7201
7202 logger.debug("Receive M1 from STA")
7203 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7204 eap_id = (msg['eap_identifier'] + 1) % 256
7205
7206 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7207 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7208 r_nonce)
7209 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7210 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7211
7212 logger.debug("Send M2 to STA")
7213 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7214 m1_attrs[ATTR_ENROLLEE_NONCE],
7215 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7216 send_wsc_msg(dev[0], bssid, m2)
7217 eap_id = (eap_id + 1) % 256
7218
7219 logger.debug("Receive M3 from STA")
7220 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7221 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7222
7223def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7224 """WPS and NACK M3 missing Config Error"""
7225 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7226 logger.debug("Send NACK to STA")
7227 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7228 send_wsc_msg(dev[0], bssid, msg)
7229 dev[0].request("WPS_CANCEL")
7230 dev[0].wait_disconnected()
7231 dev[0].flush_scan_cache()
7232
7233def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7234 """WPS and NACK M3 missing E-Nonce"""
7235 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7236 logger.debug("Send NACK to STA")
7237 msg, attrs = build_nack(eap_id, None, r_nonce)
7238 send_wsc_msg(dev[0], bssid, msg)
7239 dev[0].request("WPS_CANCEL")
7240 dev[0].wait_disconnected()
7241 dev[0].flush_scan_cache()
7242
7243def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7244 """WPS and NACK M3 E-Nonce mismatch"""
7245 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7246 logger.debug("Send NACK to STA")
7247 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7248 send_wsc_msg(dev[0], bssid, msg)
7249 dev[0].request("WPS_CANCEL")
7250 dev[0].wait_disconnected()
7251 dev[0].flush_scan_cache()
7252
7253def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7254 """WPS and NACK M3 missing R-Nonce"""
7255 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7256 logger.debug("Send NACK to STA")
7257 msg, attrs = build_nack(eap_id, e_nonce, None)
7258 send_wsc_msg(dev[0], bssid, msg)
7259 dev[0].request("WPS_CANCEL")
7260 dev[0].wait_disconnected()
7261 dev[0].flush_scan_cache()
7262
7263def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7264 """WPS and NACK M3 R-Nonce mismatch"""
7265 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7266 logger.debug("Send NACK to STA")
7267 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7268 send_wsc_msg(dev[0], bssid, msg)
7269 dev[0].request("WPS_CANCEL")
7270 dev[0].wait_disconnected()
7271 dev[0].flush_scan_cache()
7272
7273def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7274 """WPS and NACK M3 no Message Type"""
7275 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7276 logger.debug("Send NACK to STA")
7277 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7278 send_wsc_msg(dev[0], bssid, msg)
7279 dev[0].request("WPS_CANCEL")
7280 dev[0].wait_disconnected()
7281 dev[0].flush_scan_cache()
7282
7283def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7284 """WPS and NACK M3 invalid Message Type"""
7285 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7286 logger.debug("Send NACK to STA")
7287 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7288 send_wsc_msg(dev[0], bssid, msg)
7289 dev[0].request("WPS_CANCEL")
7290 dev[0].wait_disconnected()
7291 dev[0].flush_scan_cache()
7292
7293def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7294 """WPS and NACK M3 invalid attribute"""
7295 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7296 logger.debug("Send NACK to STA")
7297 attrs = '\x10\x10\x00'
7298 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7299 send_wsc_msg(dev[0], bssid, msg)
7300 dev[0].request("WPS_CANCEL")
7301 dev[0].wait_disconnected()
7302 dev[0].flush_scan_cache()
7303
7304def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7305 """WPS and ACK M3 missing E-Nonce"""
7306 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7307 logger.debug("Send NACK to STA")
7308 msg, attrs = build_ack(eap_id, None, r_nonce)
7309 send_wsc_msg(dev[0], bssid, msg)
7310 dev[0].request("WPS_CANCEL")
7311 dev[0].wait_disconnected()
7312 dev[0].flush_scan_cache()
7313
7314def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7315 """WPS and ACK M3 E-Nonce mismatch"""
7316 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7317 logger.debug("Send NACK to STA")
7318 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7319 send_wsc_msg(dev[0], bssid, msg)
7320 dev[0].request("WPS_CANCEL")
7321 dev[0].wait_disconnected()
7322 dev[0].flush_scan_cache()
7323
7324def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7325 """WPS and ACK M3 missing R-Nonce"""
7326 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7327 logger.debug("Send NACK to STA")
7328 msg, attrs = build_ack(eap_id, e_nonce, None)
7329 send_wsc_msg(dev[0], bssid, msg)
7330 dev[0].request("WPS_CANCEL")
7331 dev[0].wait_disconnected()
7332 dev[0].flush_scan_cache()
7333
7334def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7335 """WPS and ACK M3 R-Nonce mismatch"""
7336 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7337 logger.debug("Send NACK to STA")
7338 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7339 send_wsc_msg(dev[0], bssid, msg)
7340 dev[0].request("WPS_CANCEL")
7341 dev[0].wait_disconnected()
7342 dev[0].flush_scan_cache()
7343
7344def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7345 """WPS and ACK M3 no Message Type"""
7346 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7347 logger.debug("Send NACK to STA")
7348 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7349 send_wsc_msg(dev[0], bssid, msg)
7350 dev[0].request("WPS_CANCEL")
7351 dev[0].wait_disconnected()
7352 dev[0].flush_scan_cache()
7353
7354def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7355 """WPS and ACK M3 invalid Message Type"""
7356 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7357 logger.debug("Send NACK to STA")
7358 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7359 send_wsc_msg(dev[0], bssid, msg)
7360 dev[0].request("WPS_CANCEL")
7361 dev[0].wait_disconnected()
7362 dev[0].flush_scan_cache()
7363
7364def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7365 """WPS and ACK M3 invalid attribute"""
7366 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7367 logger.debug("Send ACK to STA")
7368 attrs = '\x10\x10\x00'
7369 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7370 send_wsc_msg(dev[0], bssid, msg)
7371 dev[0].request("WPS_CANCEL")
7372 dev[0].wait_disconnected()
7373 dev[0].flush_scan_cache()
7374
7375def test_wps_ext_proto_ack_m3(dev, apdev):
7376 """WPS and ACK M3"""
7377 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7378 logger.debug("Send ACK to STA")
7379 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7380 send_wsc_msg(dev[0], bssid, msg)
7381 dev[0].request("WPS_CANCEL")
7382 dev[0].wait_disconnected()
7383 dev[0].flush_scan_cache()
7384
7385def wps_to_m3_helper(dev, apdev):
7386 pin = "12345670"
7387 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7388 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7389 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7390 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7391
7392 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7393 uuid_r = 16*'\x33'
7394 r_nonce = 16*'\x44'
7395 own_private, e_pk = wsc_dh_init()
7396
7397 logger.debug("Receive M1 from STA")
7398 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7399 eap_id = (msg['eap_identifier'] + 1) % 256
7400
7401 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7402 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7403 r_nonce)
7404 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7405 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7406
7407 logger.debug("Send M2 to STA")
7408 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7409 m1_attrs[ATTR_ENROLLEE_NONCE],
7410 r_nonce, uuid_r, e_pk)
7411 send_wsc_msg(dev[0], bssid, m2)
7412 eap_id = (eap_id + 1) % 256
7413
7414 logger.debug("Receive M3 from STA")
7415 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7416 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7417
7418def wps_to_m3(dev, apdev):
7419 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)
7420 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7421
7422def wps_to_m5(dev, apdev):
7423 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)
7424
7425 logger.debug("Send M4 to STA")
7426 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7427 attrs += build_attr_msg_type(WPS_M4)
7428 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7429 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7430 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7431 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7432 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7433 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7434 raw_m4_attrs = attrs
7435 m4 = build_eap_wsc(1, eap_id, attrs)
7436 send_wsc_msg(dev[0], bssid, m4)
7437 eap_id = (eap_id + 1) % 256
7438
7439 logger.debug("Receive M5 from STA")
7440 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7441
7442 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7443
7444def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7445 """WPS and no R-Hash1 in M4"""
7446 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7447
7448 logger.debug("Send M4 to STA")
7449 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7450 attrs += build_attr_msg_type(WPS_M4)
7451 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7452 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7453 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7454 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7455 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7456 attrs += build_attr_authenticator(authkey, m3, attrs)
7457 m4 = build_eap_wsc(1, eap_id, attrs)
7458 send_wsc_msg(dev[0], bssid, m4)
7459 eap_id = (eap_id + 1) % 256
7460
7461 logger.debug("Receive M5 (NACK) from STA")
7462 msg = get_wsc_msg(dev[0])
7463 if msg['wsc_opcode'] != WSC_NACK:
7464 raise Exception("Unexpected message - expected WSC_Nack")
7465
7466 dev[0].request("WPS_CANCEL")
7467 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7468 dev[0].wait_disconnected()
7469
7470def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7471 """WPS and no R-Hash2 in M4"""
7472 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7473
7474 logger.debug("Send M4 to STA")
7475 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7476 attrs += build_attr_msg_type(WPS_M4)
7477 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7478 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7479 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7480 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7481 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7482 attrs += build_attr_authenticator(authkey, m3, attrs)
7483 m4 = build_eap_wsc(1, eap_id, attrs)
7484 send_wsc_msg(dev[0], bssid, m4)
7485 eap_id = (eap_id + 1) % 256
7486
7487 logger.debug("Receive M5 (NACK) from STA")
7488 msg = get_wsc_msg(dev[0])
7489 if msg['wsc_opcode'] != WSC_NACK:
7490 raise Exception("Unexpected message - expected WSC_Nack")
7491
7492 dev[0].request("WPS_CANCEL")
7493 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7494 dev[0].wait_disconnected()
7495
7496def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7497 """WPS and no R-SNonce1 in M4"""
7498 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7499
7500 logger.debug("Send M4 to STA")
7501 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7502 attrs += build_attr_msg_type(WPS_M4)
7503 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7504 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7505 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7506 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7507 data = ''
7508 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7509 attrs += build_attr_authenticator(authkey, m3, attrs)
7510 m4 = build_eap_wsc(1, eap_id, attrs)
7511 send_wsc_msg(dev[0], bssid, m4)
7512 eap_id = (eap_id + 1) % 256
7513
7514 logger.debug("Receive M5 (NACK) from STA")
7515 msg = get_wsc_msg(dev[0])
7516 if msg['wsc_opcode'] != WSC_NACK:
7517 raise Exception("Unexpected message - expected WSC_Nack")
7518
7519 dev[0].request("WPS_CANCEL")
7520 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7521 dev[0].wait_disconnected()
7522
7523def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7524 """WPS and invalid pad string in M4"""
7525 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7526
7527 logger.debug("Send M4 to STA")
7528 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7529 attrs += build_attr_msg_type(WPS_M4)
7530 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7531 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7532 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7533 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7534
7535 m = hmac.new(authkey, data, hashlib.sha256)
7536 kwa = m.digest()[0:8]
7537 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7538 iv = 16*'\x99'
7539 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7540 pad_len = 16 - len(data) % 16
7541 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7542 data += ps
7543 wrapped = aes.encrypt(data)
7544 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7545
7546 attrs += build_attr_authenticator(authkey, m3, attrs)
7547 m4 = build_eap_wsc(1, eap_id, attrs)
7548 send_wsc_msg(dev[0], bssid, m4)
7549 eap_id = (eap_id + 1) % 256
7550
7551 logger.debug("Receive M5 (NACK) from STA")
7552 msg = get_wsc_msg(dev[0])
7553 if msg['wsc_opcode'] != WSC_NACK:
7554 raise Exception("Unexpected message - expected WSC_Nack")
7555
7556 dev[0].request("WPS_CANCEL")
7557 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7558 dev[0].wait_disconnected()
7559
7560def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7561 """WPS and invalid pad value in M4"""
7562 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7563
7564 logger.debug("Send M4 to STA")
7565 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7566 attrs += build_attr_msg_type(WPS_M4)
7567 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7568 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7569 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7570 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7571
7572 m = hmac.new(authkey, data, hashlib.sha256)
7573 kwa = m.digest()[0:8]
7574 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7575 iv = 16*'\x99'
7576 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7577 pad_len = 16 - len(data) % 16
7578 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7579 data += ps
7580 wrapped = aes.encrypt(data)
7581 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7582
7583 attrs += build_attr_authenticator(authkey, m3, attrs)
7584 m4 = build_eap_wsc(1, eap_id, attrs)
7585 send_wsc_msg(dev[0], bssid, m4)
7586 eap_id = (eap_id + 1) % 256
7587
7588 logger.debug("Receive M5 (NACK) from STA")
7589 msg = get_wsc_msg(dev[0])
7590 if msg['wsc_opcode'] != WSC_NACK:
7591 raise Exception("Unexpected message - expected WSC_Nack")
7592
7593 dev[0].request("WPS_CANCEL")
7594 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7595 dev[0].wait_disconnected()
7596
7597def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7598 """WPS and no Encr Settings in M4"""
7599 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7600
7601 logger.debug("Send M4 to STA")
7602 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7603 attrs += build_attr_msg_type(WPS_M4)
7604 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7605 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7606 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7607 attrs += build_attr_authenticator(authkey, m3, attrs)
7608 m4 = build_eap_wsc(1, eap_id, attrs)
7609 send_wsc_msg(dev[0], bssid, m4)
7610 eap_id = (eap_id + 1) % 256
7611
7612 logger.debug("Receive M5 (NACK) from STA")
7613 msg = get_wsc_msg(dev[0])
7614 if msg['wsc_opcode'] != WSC_NACK:
7615 raise Exception("Unexpected message - expected WSC_Nack")
7616
7617 dev[0].request("WPS_CANCEL")
7618 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7619 dev[0].wait_disconnected()
7620
7621def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7622 """WPS and no R-SNonce2 in M6"""
7623 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7624
7625 logger.debug("Send M6 to STA")
7626 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7627 attrs += build_attr_msg_type(WPS_M6)
7628 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7629 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7630 data = ''
7631 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7632 attrs += build_attr_authenticator(authkey, m5, attrs)
7633 m6 = build_eap_wsc(1, eap_id, attrs)
7634 send_wsc_msg(dev[0], bssid, m6)
7635 eap_id = (eap_id + 1) % 256
7636
7637 logger.debug("Receive M7 (NACK) from STA")
7638 msg = get_wsc_msg(dev[0])
7639 if msg['wsc_opcode'] != WSC_NACK:
7640 raise Exception("Unexpected message - expected WSC_Nack")
7641
7642 dev[0].request("WPS_CANCEL")
7643 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7644 dev[0].wait_disconnected()
7645
7646def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7647 """WPS and no Encr Settings in M6"""
7648 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7649
7650 logger.debug("Send M6 to STA")
7651 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7652 attrs += build_attr_msg_type(WPS_M6)
7653 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7654 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7655 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7656 attrs += build_attr_authenticator(authkey, m5, attrs)
7657 m6 = build_eap_wsc(1, eap_id, attrs)
7658 send_wsc_msg(dev[0], bssid, m6)
7659 eap_id = (eap_id + 1) % 256
7660
7661 logger.debug("Receive M7 (NACK) from STA")
7662 msg = get_wsc_msg(dev[0])
7663 if msg['wsc_opcode'] != WSC_NACK:
7664 raise Exception("Unexpected message - expected WSC_Nack")
7665
7666 dev[0].request("WPS_CANCEL")
7667 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7668 dev[0].wait_disconnected()
7669
7670def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7671 """WPS and no Encr Settings in M6"""
7672 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7673
7674 logger.debug("Send M6 to STA")
7675 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7676 attrs += build_attr_msg_type(WPS_M6)
7677 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7678 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7679 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7680 attrs += build_attr_authenticator(authkey, m5, attrs)
7681 raw_m6_attrs = attrs
7682 m6 = build_eap_wsc(1, eap_id, attrs)
7683 send_wsc_msg(dev[0], bssid, m6)
7684 eap_id = (eap_id + 1) % 256
7685
7686 logger.debug("Receive M7 from STA")
7687 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7688
7689 logger.debug("Send M8 to STA")
7690 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7691 attrs += build_attr_msg_type(WPS_M8)
7692 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7693 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7694 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7695 raw_m8_attrs = attrs
7696 m8 = build_eap_wsc(1, eap_id, attrs)
7697 send_wsc_msg(dev[0], bssid, m8)
7698
7699 logger.debug("Receive WSC_Done (NACK) from STA")
7700 msg = get_wsc_msg(dev[0])
7701 if msg['wsc_opcode'] != WSC_NACK:
7702 raise Exception("Unexpected message - expected WSC_Nack")
7703
7704 dev[0].request("WPS_CANCEL")
7705 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7706 dev[0].wait_disconnected()
7707
7708def wps_start_ext_reg(apdev, dev):
7709 addr = dev.own_addr()
7710 bssid = apdev['bssid']
7711 ssid = "test-wps-conf"
7712 appin = "12345670"
7713 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
7714 "wpa_passphrase": "12345678", "wpa": "2",
7715 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7716 "ap_pin": appin }
afc26df2 7717 hapd = hostapd.add_ap(apdev, params)
7511ead0
JM
7718
7719 dev.scan_for_bss(bssid, freq="2412")
7720 hapd.request("SET ext_eapol_frame_io 1")
7721 dev.request("SET ext_eapol_frame_io 1")
7722
7723 dev.request("WPS_REG " + bssid + " " + appin)
7724
7725 return addr,bssid,hapd
7726
7727def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7728 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7729 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7730 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7731
7732 logger.debug("Receive M1 from AP")
7733 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7734 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7735 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7736 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7737
7738 appin = '12345670'
7739 uuid_r = 16*'\x33'
7740 r_nonce = 16*'\x44'
7741 own_private, r_pk = wsc_dh_init()
7742 authkey,keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7743 r_nonce)
7744 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7745
7746 logger.debug("Send M2 to AP")
7747 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7748 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7749 send_wsc_msg(hapd, addr, m2)
7750
7751 logger.debug("Receive M3 from AP")
7752 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7753
7754 logger.debug("Send M4 to AP")
7755 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7756 attrs += build_attr_msg_type(WPS_M4)
7757 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7758 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7759 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7760 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7761 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7762 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7763 raw_m4_attrs = attrs
7764 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7765 send_wsc_msg(hapd, addr, m4)
7766
7767 logger.debug("Receive M5 from AP")
7768 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7769
7770 logger.debug("Send M6 to STA")
7771 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7772 attrs += build_attr_msg_type(WPS_M6)
7773 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7774 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7775 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7776 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7777 raw_m6_attrs = attrs
7778 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7779 send_wsc_msg(hapd, addr, m6)
7780
7781 logger.debug("Receive M7 from AP")
7782 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7783
7784 logger.debug("Send M8 to STA")
7785 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7786 attrs += build_attr_msg_type(WPS_M8)
7787 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7788 if ap_settings:
7789 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7790 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7791 raw_m8_attrs = attrs
7792 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7793 send_wsc_msg(hapd, addr, m8)
7794
7795 if success:
7796 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7797 if ev is None:
7798 raise Exception("New AP settings not reported")
7799 logger.debug("Receive WSC_Done from AP")
7800 msg = get_wsc_msg(hapd)
7801 if msg['wsc_opcode'] != WSC_Done:
7802 raise Exception("Unexpected message - expected WSC_Done")
7803
7804 logger.debug("Send WSC_ACK to AP")
7805 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7806 eap_code=2)
7807 send_wsc_msg(hapd, addr, ack)
7808 dev[0].wait_disconnected()
7809 else:
7810 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7811 if ev is None:
7812 raise Exception("WPS failure not reported")
7813 logger.debug("Receive WSC_NACK from AP")
7814 msg = get_wsc_msg(hapd)
7815 if msg['wsc_opcode'] != WSC_NACK:
7816 raise Exception("Unexpected message - expected WSC_NACK")
7817
7818 logger.debug("Send WSC_NACK to AP")
7819 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7820 eap_code=2)
7821 send_wsc_msg(hapd, addr, nack)
7822 dev[0].wait_disconnected()
7823
7824def test_wps_ext_ap_settings_success(dev, apdev):
7825 """WPS and AP Settings: success"""
7826 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7827 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7828 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7829 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7830 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7831 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7832 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7833
9fd6804d 7834@remote_compatible
7511ead0
JM
7835def test_wps_ext_ap_settings_missing(dev, apdev):
7836 """WPS and AP Settings: missing"""
7837 wps_run_ap_settings_proto(dev, apdev, None, False)
7838
9fd6804d 7839@remote_compatible
7511ead0
JM
7840def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7841 """WPS and AP Settings: MAC Address mismatch"""
7842 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7843 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7844 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7845 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7846 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7847 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7848 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7849
9fd6804d 7850@remote_compatible
7511ead0
JM
7851def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7852 """WPS and AP Settings: missing MAC Address"""
7853 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7854 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7855 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7856 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7857 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7858 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7859
9fd6804d 7860@remote_compatible
7511ead0
JM
7861def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7862 """WPS and AP Settings: reject Encr Type"""
7863 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7864 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7865 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7866 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7867 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7868 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7869 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7870
9fd6804d 7871@remote_compatible
7511ead0
JM
7872def test_wps_ext_ap_settings_m2d(dev, apdev):
7873 """WPS and AP Settings: M2D"""
7874 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7875 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7876 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7877
7878 logger.debug("Receive M1 from AP")
7879 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7880 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7881
7882 r_nonce = 16*'\x44'
7883 uuid_r = 16*'\x33'
7884
7885 logger.debug("Send M2D to AP")
7886 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7887 e_nonce, r_nonce, uuid_r,
7888 dev_pw_id='\x00\x00', eap_code=2)
7889 send_wsc_msg(hapd, addr, m2d)
7890
7891 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7892 if ev is None:
7893 raise Exception("M2D not reported")
7894
7895 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7896
7897def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7898 logger.debug("Receive WSC_NACK from AP")
7899 msg = get_wsc_msg(hapd)
7900 if msg['wsc_opcode'] != WSC_NACK:
7901 raise Exception("Unexpected message - expected WSC_NACK")
7902
7903 logger.debug("Send WSC_NACK to AP")
7904 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7905 eap_code=2)
7906 send_wsc_msg(hapd, dev.own_addr(), nack)
7907 dev.wait_disconnected()
7908
9fd6804d 7909@remote_compatible
7511ead0
JM
7910def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7911 """WPS proto: M3 missing E-Hash1"""
7912 pin = "12345670"
7913 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7914 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7915 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7916
7917 logger.debug("Receive WSC/Start from AP")
7918 msg = get_wsc_msg(hapd)
7919 if msg['wsc_opcode'] != WSC_Start:
7920 raise Exception("Unexpected Op-Code for WSC/Start")
7921
7922 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7923 uuid_e = 16*'\x11'
7924 e_nonce = 16*'\x22'
7925 own_private, e_pk = wsc_dh_init()
7926
7927 logger.debug("Send M1 to AP")
7928 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7929 e_nonce, e_pk)
7930 send_wsc_msg(hapd, addr, m1)
7931
7932 logger.debug("Receive M2 from AP")
7933 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7934 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7935 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7936
7937 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7938 r_nonce)
7939 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7940
7941 logger.debug("Send M3 to AP")
7942 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7943 attrs += build_attr_msg_type(WPS_M3)
7944 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7945 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7946 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7947 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7948 raw_m3_attrs = attrs
7949 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7950 send_wsc_msg(hapd, addr, m3)
7951
7952 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7953
9fd6804d 7954@remote_compatible
7511ead0
JM
7955def test_wps_ext_m3_missing_e_hash2(dev, apdev):
7956 """WPS proto: M3 missing E-Hash2"""
7957 pin = "12345670"
7958 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7959 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7960 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7961
7962 logger.debug("Receive WSC/Start from AP")
7963 msg = get_wsc_msg(hapd)
7964 if msg['wsc_opcode'] != WSC_Start:
7965 raise Exception("Unexpected Op-Code for WSC/Start")
7966
7967 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7968 uuid_e = 16*'\x11'
7969 e_nonce = 16*'\x22'
7970 own_private, e_pk = wsc_dh_init()
7971
7972 logger.debug("Send M1 to AP")
7973 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7974 e_nonce, e_pk)
7975 send_wsc_msg(hapd, addr, m1)
7976
7977 logger.debug("Receive M2 from AP")
7978 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7979 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7980 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7981
7982 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7983 r_nonce)
7984 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7985
7986 logger.debug("Send M3 to AP")
7987 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7988 attrs += build_attr_msg_type(WPS_M3)
7989 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7990 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7991 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7992 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7993 raw_m3_attrs = attrs
7994 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7995 send_wsc_msg(hapd, addr, m3)
7996
7997 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7998
9fd6804d 7999@remote_compatible
7511ead0
JM
8000def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
8001 """WPS proto: M5 missing E-SNonce1"""
8002 pin = "12345670"
8003 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8004 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8005 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8006
8007 logger.debug("Receive WSC/Start from AP")
8008 msg = get_wsc_msg(hapd)
8009 if msg['wsc_opcode'] != WSC_Start:
8010 raise Exception("Unexpected Op-Code for WSC/Start")
8011
8012 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8013 uuid_e = 16*'\x11'
8014 e_nonce = 16*'\x22'
8015 own_private, e_pk = wsc_dh_init()
8016
8017 logger.debug("Send M1 to AP")
8018 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8019 e_nonce, e_pk)
8020 send_wsc_msg(hapd, addr, m1)
8021
8022 logger.debug("Receive M2 from AP")
8023 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8024 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8025 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8026
8027 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8028 r_nonce)
8029 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8030
8031 logger.debug("Send M3 to AP")
8032 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8033 attrs += build_attr_msg_type(WPS_M3)
8034 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8035 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8036 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8037 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8038 raw_m3_attrs = attrs
8039 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8040 send_wsc_msg(hapd, addr, m3)
8041
8042 logger.debug("Receive M4 from AP")
8043 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8044
8045 logger.debug("Send M5 to AP")
8046 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8047 attrs += build_attr_msg_type(WPS_M5)
8048 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8049 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8050 data = ''
8051 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8052 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8053 raw_m5_attrs = attrs
8054 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8055 send_wsc_msg(hapd, addr, m5)
8056
8057 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8058
9fd6804d 8059@remote_compatible
7511ead0
JM
8060def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8061 """WPS proto: M5 E-SNonce1 mismatch"""
8062 pin = "12345670"
8063 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8064 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8065 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8066
8067 logger.debug("Receive WSC/Start from AP")
8068 msg = get_wsc_msg(hapd)
8069 if msg['wsc_opcode'] != WSC_Start:
8070 raise Exception("Unexpected Op-Code for WSC/Start")
8071
8072 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8073 uuid_e = 16*'\x11'
8074 e_nonce = 16*'\x22'
8075 own_private, e_pk = wsc_dh_init()
8076
8077 logger.debug("Send M1 to AP")
8078 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8079 e_nonce, e_pk)
8080 send_wsc_msg(hapd, addr, m1)
8081
8082 logger.debug("Receive M2 from AP")
8083 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8084 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8085 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8086
8087 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8088 r_nonce)
8089 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8090
8091 logger.debug("Send M3 to AP")
8092 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8093 attrs += build_attr_msg_type(WPS_M3)
8094 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8095 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8096 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8097 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8098 raw_m3_attrs = attrs
8099 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8100 send_wsc_msg(hapd, addr, m3)
8101
8102 logger.debug("Receive M4 from AP")
8103 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8104
8105 logger.debug("Send M5 to AP")
8106 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8107 attrs += build_attr_msg_type(WPS_M5)
8108 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8109 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8110 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8111 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8112 raw_m5_attrs = attrs
8113 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8114 send_wsc_msg(hapd, addr, m5)
8115
8116 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8117
8118def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8119 """WPS proto: M7 missing E-SNonce2"""
8120 pin = "12345670"
8121 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8122 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8123 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8124
8125 logger.debug("Receive WSC/Start from AP")
8126 msg = get_wsc_msg(hapd)
8127 if msg['wsc_opcode'] != WSC_Start:
8128 raise Exception("Unexpected Op-Code for WSC/Start")
8129
8130 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8131 uuid_e = 16*'\x11'
8132 e_nonce = 16*'\x22'
8133 own_private, e_pk = wsc_dh_init()
8134
8135 logger.debug("Send M1 to AP")
8136 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8137 e_nonce, e_pk)
8138 send_wsc_msg(hapd, addr, m1)
8139
8140 logger.debug("Receive M2 from AP")
8141 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8142 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8143 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8144
8145 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8146 r_nonce)
8147 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8148
8149 logger.debug("Send M3 to AP")
8150 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8151 attrs += build_attr_msg_type(WPS_M3)
8152 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8153 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8154 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8155 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8156 raw_m3_attrs = attrs
8157 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8158 send_wsc_msg(hapd, addr, m3)
8159
8160 logger.debug("Receive M4 from AP")
8161 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8162
8163 logger.debug("Send M5 to AP")
8164 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8165 attrs += build_attr_msg_type(WPS_M5)
8166 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8167 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8168 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8169 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8170 raw_m5_attrs = attrs
8171 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8172 send_wsc_msg(hapd, addr, m5)
8173
8174 logger.debug("Receive M6 from AP")
8175 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8176
8177 logger.debug("Send M7 to AP")
8178 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8179 attrs += build_attr_msg_type(WPS_M7)
8180 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8181 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8182 data = ''
8183 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8184 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8185 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8186 raw_m7_attrs = attrs
8187 send_wsc_msg(hapd, addr, m7)
8188
8189 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8190
9fd6804d 8191@remote_compatible
7511ead0
JM
8192def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8193 """WPS proto: M7 E-SNonce2 mismatch"""
8194 pin = "12345670"
8195 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8196 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8197 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8198
8199 logger.debug("Receive WSC/Start from AP")
8200 msg = get_wsc_msg(hapd)
8201 if msg['wsc_opcode'] != WSC_Start:
8202 raise Exception("Unexpected Op-Code for WSC/Start")
8203
8204 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8205 uuid_e = 16*'\x11'
8206 e_nonce = 16*'\x22'
8207 own_private, e_pk = wsc_dh_init()
8208
8209 logger.debug("Send M1 to AP")
8210 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8211 e_nonce, e_pk)
8212 send_wsc_msg(hapd, addr, m1)
8213
8214 logger.debug("Receive M2 from AP")
8215 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8216 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8217 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8218
8219 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8220 r_nonce)
8221 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8222
8223 logger.debug("Send M3 to AP")
8224 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8225 attrs += build_attr_msg_type(WPS_M3)
8226 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8227 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8228 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8229 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8230 raw_m3_attrs = attrs
8231 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8232 send_wsc_msg(hapd, addr, m3)
8233
8234 logger.debug("Receive M4 from AP")
8235 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8236
8237 logger.debug("Send M5 to AP")
8238 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8239 attrs += build_attr_msg_type(WPS_M5)
8240 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8241 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8242 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8243 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8244 raw_m5_attrs = attrs
8245 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8246 send_wsc_msg(hapd, addr, m5)
8247
8248 logger.debug("Receive M6 from AP")
8249 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8250
8251 logger.debug("Send M7 to AP")
8252 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8253 attrs += build_attr_msg_type(WPS_M7)
8254 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8255 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8256 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8257 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8258 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8259 raw_m7_attrs = attrs
8260 send_wsc_msg(hapd, addr, m7)
8261
8262 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8263
9fd6804d 8264@remote_compatible
7511ead0
JM
8265def test_wps_ext_m1_pubkey_oom(dev, apdev):
8266 """WPS proto: M1 PubKey OOM"""
8267 pin = "12345670"
8268 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8269 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8270 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8271
8272 logger.debug("Receive WSC/Start from AP")
8273 msg = get_wsc_msg(hapd)
8274 if msg['wsc_opcode'] != WSC_Start:
8275 raise Exception("Unexpected Op-Code for WSC/Start")
8276
8277 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8278 uuid_e = 16*'\x11'
8279 e_nonce = 16*'\x22'
8280 own_private, e_pk = wsc_dh_init()
8281
8282 logger.debug("Send M1 to AP")
8283 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8284 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8285 e_nonce, e_pk)
8286 send_wsc_msg(hapd, addr, m1)
8287 wps_wait_eap_failure(hapd, dev[0])
8288
8289def wps_wait_eap_failure(hapd, dev):
8290 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8291 if ev is None:
8292 raise Exception("EAP-Failure not reported")
8293 dev.wait_disconnected()
8294
9fd6804d 8295@remote_compatible
7511ead0
JM
8296def test_wps_ext_m3_m1(dev, apdev):
8297 """WPS proto: M3 replaced with M1"""
8298 pin = "12345670"
8299 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8300 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8301 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8302
8303 logger.debug("Receive WSC/Start from AP")
8304 msg = get_wsc_msg(hapd)
8305 if msg['wsc_opcode'] != WSC_Start:
8306 raise Exception("Unexpected Op-Code for WSC/Start")
8307
8308 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8309 uuid_e = 16*'\x11'
8310 e_nonce = 16*'\x22'
8311 own_private, e_pk = wsc_dh_init()
8312
8313 logger.debug("Send M1 to AP")
8314 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8315 e_nonce, e_pk)
8316 send_wsc_msg(hapd, addr, m1)
8317
8318 logger.debug("Receive M2 from AP")
8319 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8320 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8321 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8322
8323 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8324 r_nonce)
8325 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8326
8327 logger.debug("Send M3(M1) to AP")
8328 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8329 attrs += build_attr_msg_type(WPS_M1)
8330 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8331 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8332 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8333 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8334 raw_m3_attrs = attrs
8335 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8336 send_wsc_msg(hapd, addr, m3)
8337
8338 wps_wait_eap_failure(hapd, dev[0])
8339
9fd6804d 8340@remote_compatible
7511ead0
JM
8341def test_wps_ext_m5_m3(dev, apdev):
8342 """WPS proto: M5 replaced with M3"""
8343 pin = "12345670"
8344 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8345 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8346 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8347
8348 logger.debug("Receive WSC/Start from AP")
8349 msg = get_wsc_msg(hapd)
8350 if msg['wsc_opcode'] != WSC_Start:
8351 raise Exception("Unexpected Op-Code for WSC/Start")
8352
8353 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8354 uuid_e = 16*'\x11'
8355 e_nonce = 16*'\x22'
8356 own_private, e_pk = wsc_dh_init()
8357
8358 logger.debug("Send M1 to AP")
8359 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8360 e_nonce, e_pk)
8361 send_wsc_msg(hapd, addr, m1)
8362
8363 logger.debug("Receive M2 from AP")
8364 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8365 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8366 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8367
8368 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8369 r_nonce)
8370 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8371
8372 logger.debug("Send M3 to AP")
8373 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8374 attrs += build_attr_msg_type(WPS_M3)
8375 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8376 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8377 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8378 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8379 raw_m3_attrs = attrs
8380 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8381 send_wsc_msg(hapd, addr, m3)
8382
8383 logger.debug("Receive M4 from AP")
8384 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8385
8386 logger.debug("Send M5(M3) to AP")
8387 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8388 attrs += build_attr_msg_type(WPS_M3)
8389 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8390 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8391 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8392 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8393 raw_m5_attrs = attrs
8394 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8395 send_wsc_msg(hapd, addr, m5)
8396
8397 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8398
9fd6804d 8399@remote_compatible
7511ead0
JM
8400def test_wps_ext_m3_m2(dev, apdev):
8401 """WPS proto: M3 replaced with M2"""
8402 pin = "12345670"
8403 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8404 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8405 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8406
8407 logger.debug("Receive WSC/Start from AP")
8408 msg = get_wsc_msg(hapd)
8409 if msg['wsc_opcode'] != WSC_Start:
8410 raise Exception("Unexpected Op-Code for WSC/Start")
8411
8412 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8413 uuid_e = 16*'\x11'
8414 e_nonce = 16*'\x22'
8415 own_private, e_pk = wsc_dh_init()
8416
8417 logger.debug("Send M1 to AP")
8418 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8419 e_nonce, e_pk)
8420 send_wsc_msg(hapd, addr, m1)
8421
8422 logger.debug("Receive M2 from AP")
8423 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8424 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8425 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8426
8427 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8428 r_nonce)
8429 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8430
8431 logger.debug("Send M3(M2) to AP")
8432 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8433 attrs += build_attr_msg_type(WPS_M2)
8434 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8435 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8436 raw_m3_attrs = attrs
8437 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8438 send_wsc_msg(hapd, addr, m3)
8439
8440 wps_wait_eap_failure(hapd, dev[0])
8441
9fd6804d 8442@remote_compatible
7511ead0
JM
8443def test_wps_ext_m3_m5(dev, apdev):
8444 """WPS proto: M3 replaced with M5"""
8445 pin = "12345670"
8446 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8447 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8448 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8449
8450 logger.debug("Receive WSC/Start from AP")
8451 msg = get_wsc_msg(hapd)
8452 if msg['wsc_opcode'] != WSC_Start:
8453 raise Exception("Unexpected Op-Code for WSC/Start")
8454
8455 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8456 uuid_e = 16*'\x11'
8457 e_nonce = 16*'\x22'
8458 own_private, e_pk = wsc_dh_init()
8459
8460 logger.debug("Send M1 to AP")
8461 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8462 e_nonce, e_pk)
8463 send_wsc_msg(hapd, addr, m1)
8464
8465 logger.debug("Receive M2 from AP")
8466 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8467 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8468 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8469
8470 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8471 r_nonce)
8472 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8473
8474 logger.debug("Send M3(M5) to AP")
8475 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8476 attrs += build_attr_msg_type(WPS_M5)
8477 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8478 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8479 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8480 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8481 raw_m3_attrs = attrs
8482 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8483 send_wsc_msg(hapd, addr, m3)
8484
8485 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8486
9fd6804d 8487@remote_compatible
7511ead0
JM
8488def test_wps_ext_m3_m7(dev, apdev):
8489 """WPS proto: M3 replaced with M7"""
8490 pin = "12345670"
8491 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8492 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8493 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8494
8495 logger.debug("Receive WSC/Start from AP")
8496 msg = get_wsc_msg(hapd)
8497 if msg['wsc_opcode'] != WSC_Start:
8498 raise Exception("Unexpected Op-Code for WSC/Start")
8499
8500 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8501 uuid_e = 16*'\x11'
8502 e_nonce = 16*'\x22'
8503 own_private, e_pk = wsc_dh_init()
8504
8505 logger.debug("Send M1 to AP")
8506 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8507 e_nonce, e_pk)
8508 send_wsc_msg(hapd, addr, m1)
8509
8510 logger.debug("Receive M2 from AP")
8511 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8512 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8513 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8514
8515 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8516 r_nonce)
8517 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8518
8519 logger.debug("Send M3(M7) to AP")
8520 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8521 attrs += build_attr_msg_type(WPS_M7)
8522 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8523 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8524 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8525 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8526 raw_m3_attrs = attrs
8527 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8528 send_wsc_msg(hapd, addr, m3)
8529
8530 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8531
9fd6804d 8532@remote_compatible
7511ead0
JM
8533def test_wps_ext_m3_done(dev, apdev):
8534 """WPS proto: M3 replaced with WSC_Done"""
8535 pin = "12345670"
8536 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8537 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8538 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8539
8540 logger.debug("Receive WSC/Start from AP")
8541 msg = get_wsc_msg(hapd)
8542 if msg['wsc_opcode'] != WSC_Start:
8543 raise Exception("Unexpected Op-Code for WSC/Start")
8544
8545 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8546 uuid_e = 16*'\x11'
8547 e_nonce = 16*'\x22'
8548 own_private, e_pk = wsc_dh_init()
8549
8550 logger.debug("Send M1 to AP")
8551 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8552 e_nonce, e_pk)
8553 send_wsc_msg(hapd, addr, m1)
8554
8555 logger.debug("Receive M2 from AP")
8556 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8557 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8558 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8559
8560 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8561 r_nonce)
8562 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8563
8564 logger.debug("Send M3(WSC_Done) to AP")
8565 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8566 attrs += build_attr_msg_type(WPS_WSC_DONE)
8567 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8568 raw_m3_attrs = attrs
8569 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8570 send_wsc_msg(hapd, addr, m3)
8571
8572 wps_wait_eap_failure(hapd, dev[0])
8573
9fd6804d 8574@remote_compatible
7511ead0
JM
8575def test_wps_ext_m2_nack_invalid(dev, apdev):
8576 """WPS proto: M2 followed by invalid NACK"""
8577 pin = "12345670"
8578 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8579 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8580 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8581
8582 logger.debug("Receive WSC/Start from AP")
8583 msg = get_wsc_msg(hapd)
8584 if msg['wsc_opcode'] != WSC_Start:
8585 raise Exception("Unexpected Op-Code for WSC/Start")
8586
8587 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8588 uuid_e = 16*'\x11'
8589 e_nonce = 16*'\x22'
8590 own_private, e_pk = wsc_dh_init()
8591
8592 logger.debug("Send M1 to AP")
8593 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8594 e_nonce, e_pk)
8595 send_wsc_msg(hapd, addr, m1)
8596
8597 logger.debug("Receive M2 from AP")
8598 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8599 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8600 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8601
8602 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8603 r_nonce)
8604 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8605
8606 logger.debug("Send WSC_NACK to AP")
8607 attrs = '\x10\x00\x00'
8608 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8609 send_wsc_msg(hapd, addr, nack)
8610
8611 wps_wait_eap_failure(hapd, dev[0])
8612
9fd6804d 8613@remote_compatible
7511ead0
JM
8614def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8615 """WPS proto: M2 followed by NACK without Msg Type"""
8616 pin = "12345670"
8617 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8618 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8619 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8620
8621 logger.debug("Receive WSC/Start from AP")
8622 msg = get_wsc_msg(hapd)
8623 if msg['wsc_opcode'] != WSC_Start:
8624 raise Exception("Unexpected Op-Code for WSC/Start")
8625
8626 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8627 uuid_e = 16*'\x11'
8628 e_nonce = 16*'\x22'
8629 own_private, e_pk = wsc_dh_init()
8630
8631 logger.debug("Send M1 to AP")
8632 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8633 e_nonce, e_pk)
8634 send_wsc_msg(hapd, addr, m1)
8635
8636 logger.debug("Receive M2 from AP")
8637 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8638 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8639 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8640
8641 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8642 r_nonce)
8643 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8644
8645 logger.debug("Send WSC_NACK to AP")
8646 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8647 msg_type=None, eap_code=2)
8648 send_wsc_msg(hapd, addr, nack)
8649
8650 wps_wait_eap_failure(hapd, dev[0])
8651
9fd6804d 8652@remote_compatible
7511ead0
JM
8653def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8654 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8655 pin = "12345670"
8656 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8657 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8658 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8659
8660 logger.debug("Receive WSC/Start from AP")
8661 msg = get_wsc_msg(hapd)
8662 if msg['wsc_opcode'] != WSC_Start:
8663 raise Exception("Unexpected Op-Code for WSC/Start")
8664
8665 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8666 uuid_e = 16*'\x11'
8667 e_nonce = 16*'\x22'
8668 own_private, e_pk = wsc_dh_init()
8669
8670 logger.debug("Send M1 to AP")
8671 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8672 e_nonce, e_pk)
8673 send_wsc_msg(hapd, addr, m1)
8674
8675 logger.debug("Receive M2 from AP")
8676 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8677 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8678 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8679
8680 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8681 r_nonce)
8682 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8683
8684 logger.debug("Send WSC_NACK to AP")
8685 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8686 msg_type=WPS_WSC_ACK, eap_code=2)
8687 send_wsc_msg(hapd, addr, nack)
8688
8689 wps_wait_eap_failure(hapd, dev[0])
8690
9fd6804d 8691@remote_compatible
7511ead0
JM
8692def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8693 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8694 pin = "12345670"
8695 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8696 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8697 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8698
8699 logger.debug("Receive WSC/Start from AP")
8700 msg = get_wsc_msg(hapd)
8701 if msg['wsc_opcode'] != WSC_Start:
8702 raise Exception("Unexpected Op-Code for WSC/Start")
8703
8704 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8705 uuid_e = 16*'\x11'
8706 e_nonce = 16*'\x22'
8707 own_private, e_pk = wsc_dh_init()
8708
8709 logger.debug("Send M1 to AP")
8710 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8711 e_nonce, e_pk)
8712 send_wsc_msg(hapd, addr, m1)
8713
8714 logger.debug("Receive M2 from AP")
8715 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8716 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8717 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8718
8719 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8720 r_nonce)
8721 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8722
8723 logger.debug("Send WSC_NACK to AP")
8724 nack,attrs = build_nack(msg['eap_identifier'], 16*'\x00', r_nonce,
8725 eap_code=2)
8726 send_wsc_msg(hapd, addr, nack)
8727
8728 wps_wait_eap_failure(hapd, dev[0])
8729
9fd6804d 8730@remote_compatible
7511ead0
JM
8731def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8732 """WPS proto: M2 followed by NACK without Config Error"""
8733 pin = "12345670"
8734 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8735 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8736 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8737
8738 logger.debug("Receive WSC/Start from AP")
8739 msg = get_wsc_msg(hapd)
8740 if msg['wsc_opcode'] != WSC_Start:
8741 raise Exception("Unexpected Op-Code for WSC/Start")
8742
8743 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8744 uuid_e = 16*'\x11'
8745 e_nonce = 16*'\x22'
8746 own_private, e_pk = wsc_dh_init()
8747
8748 logger.debug("Send M1 to AP")
8749 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8750 e_nonce, e_pk)
8751 send_wsc_msg(hapd, addr, m1)
8752
8753 logger.debug("Receive M2 from AP")
8754 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8755 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8756 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8757
8758 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8759 r_nonce)
8760 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8761
8762 logger.debug("Send WSC_NACK to AP")
8763 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8764 config_error=None, eap_code=2)
8765 send_wsc_msg(hapd, addr, nack)
8766
8767 wps_wait_eap_failure(hapd, dev[0])
8768
9fd6804d 8769@remote_compatible
7511ead0
JM
8770def test_wps_ext_m2_ack_invalid(dev, apdev):
8771 """WPS proto: M2 followed by invalid ACK"""
8772 pin = "12345670"
8773 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8774 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8775 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8776
8777 logger.debug("Receive WSC/Start from AP")
8778 msg = get_wsc_msg(hapd)
8779 if msg['wsc_opcode'] != WSC_Start:
8780 raise Exception("Unexpected Op-Code for WSC/Start")
8781
8782 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8783 uuid_e = 16*'\x11'
8784 e_nonce = 16*'\x22'
8785 own_private, e_pk = wsc_dh_init()
8786
8787 logger.debug("Send M1 to AP")
8788 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8789 e_nonce, e_pk)
8790 send_wsc_msg(hapd, addr, m1)
8791
8792 logger.debug("Receive M2 from AP")
8793 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8794 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8795 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8796
8797 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8798 r_nonce)
8799 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8800
8801 logger.debug("Send WSC_ACK to AP")
8802 attrs = '\x10\x00\x00'
8803 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8804 send_wsc_msg(hapd, addr, ack)
8805
8806 wps_wait_eap_failure(hapd, dev[0])
8807
9fd6804d 8808@remote_compatible
7511ead0
JM
8809def test_wps_ext_m2_ack(dev, apdev):
8810 """WPS proto: M2 followed by ACK"""
8811 pin = "12345670"
8812 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8813 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8814 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8815
8816 logger.debug("Receive WSC/Start from AP")
8817 msg = get_wsc_msg(hapd)
8818 if msg['wsc_opcode'] != WSC_Start:
8819 raise Exception("Unexpected Op-Code for WSC/Start")
8820
8821 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8822 uuid_e = 16*'\x11'
8823 e_nonce = 16*'\x22'
8824 own_private, e_pk = wsc_dh_init()
8825
8826 logger.debug("Send M1 to AP")
8827 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8828 e_nonce, e_pk)
8829 send_wsc_msg(hapd, addr, m1)
8830
8831 logger.debug("Receive M2 from AP")
8832 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8833 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8834 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8835
8836 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8837 r_nonce)
8838 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8839
8840 logger.debug("Send WSC_ACK to AP")
8841 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8842 send_wsc_msg(hapd, addr, ack)
8843
8844 wps_wait_eap_failure(hapd, dev[0])
8845
9fd6804d 8846@remote_compatible
7511ead0
JM
8847def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8848 """WPS proto: M2 followed by ACK missing Msg Type"""
8849 pin = "12345670"
8850 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8851 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8852 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8853
8854 logger.debug("Receive WSC/Start from AP")
8855 msg = get_wsc_msg(hapd)
8856 if msg['wsc_opcode'] != WSC_Start:
8857 raise Exception("Unexpected Op-Code for WSC/Start")
8858
8859 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8860 uuid_e = 16*'\x11'
8861 e_nonce = 16*'\x22'
8862 own_private, e_pk = wsc_dh_init()
8863
8864 logger.debug("Send M1 to AP")
8865 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8866 e_nonce, e_pk)
8867 send_wsc_msg(hapd, addr, m1)
8868
8869 logger.debug("Receive M2 from AP")
8870 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8871 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8872 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8873
8874 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8875 r_nonce)
8876 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8877
8878 logger.debug("Send WSC_ACK to AP")
8879 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8880 msg_type=None, eap_code=2)
8881 send_wsc_msg(hapd, addr, ack)
8882
8883 wps_wait_eap_failure(hapd, dev[0])
8884
9fd6804d 8885@remote_compatible
7511ead0
JM
8886def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8887 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8888 pin = "12345670"
8889 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8890 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8891 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8892
8893 logger.debug("Receive WSC/Start from AP")
8894 msg = get_wsc_msg(hapd)
8895 if msg['wsc_opcode'] != WSC_Start:
8896 raise Exception("Unexpected Op-Code for WSC/Start")
8897
8898 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8899 uuid_e = 16*'\x11'
8900 e_nonce = 16*'\x22'
8901 own_private, e_pk = wsc_dh_init()
8902
8903 logger.debug("Send M1 to AP")
8904 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8905 e_nonce, e_pk)
8906 send_wsc_msg(hapd, addr, m1)
8907
8908 logger.debug("Receive M2 from AP")
8909 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8910 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8911 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8912
8913 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8914 r_nonce)
8915 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8916
8917 logger.debug("Send WSC_ACK to AP")
8918 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8919 msg_type=WPS_WSC_NACK, eap_code=2)
8920 send_wsc_msg(hapd, addr, ack)
8921
8922 wps_wait_eap_failure(hapd, dev[0])
8923
9fd6804d 8924@remote_compatible
7511ead0
JM
8925def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8926 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8927 pin = "12345670"
8928 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8929 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8930 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8931
8932 logger.debug("Receive WSC/Start from AP")
8933 msg = get_wsc_msg(hapd)
8934 if msg['wsc_opcode'] != WSC_Start:
8935 raise Exception("Unexpected Op-Code for WSC/Start")
8936
8937 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8938 uuid_e = 16*'\x11'
8939 e_nonce = 16*'\x22'
8940 own_private, e_pk = wsc_dh_init()
8941
8942 logger.debug("Send M1 to AP")
8943 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8944 e_nonce, e_pk)
8945 send_wsc_msg(hapd, addr, m1)
8946
8947 logger.debug("Receive M2 from AP")
8948 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8949 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8950 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8951
8952 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8953 r_nonce)
8954 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8955
8956 logger.debug("Send WSC_ACK to AP")
8957 ack,attrs = build_ack(msg['eap_identifier'], 16*'\x00', r_nonce,
8958 eap_code=2)
8959 send_wsc_msg(hapd, addr, ack)
8960
8961 wps_wait_eap_failure(hapd, dev[0])
8962
9fd6804d 8963@remote_compatible
7511ead0
JM
8964def test_wps_ext_m1_invalid(dev, apdev):
8965 """WPS proto: M1 failing parsing"""
8966 pin = "12345670"
8967 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8968 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8969 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8970
8971 logger.debug("Receive WSC/Start from AP")
8972 msg = get_wsc_msg(hapd)
8973 if msg['wsc_opcode'] != WSC_Start:
8974 raise Exception("Unexpected Op-Code for WSC/Start")
8975
8976 logger.debug("Send M1 to AP")
8977 attrs = '\x10\x00\x00'
8978 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8979 send_wsc_msg(hapd, addr, m1)
8980
8981 wps_wait_eap_failure(hapd, dev[0])
8982
8983def test_wps_ext_m1_missing_msg_type(dev, apdev):
8984 """WPS proto: M1 missing Msg Type"""
8985 pin = "12345670"
8986 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8987 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8988 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8989
8990 logger.debug("Receive WSC/Start from AP")
8991 msg = get_wsc_msg(hapd)
8992 if msg['wsc_opcode'] != WSC_Start:
8993 raise Exception("Unexpected Op-Code for WSC/Start")
8994
8995 logger.debug("Send M1 to AP")
8996 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8997 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8998 send_wsc_msg(hapd, addr, m1)
8999
9000 wps_wait_ap_nack(hapd, dev[0], 16*'\x00', 16*'\x00')
9001
9002def wps_ext_wsc_done(dev, apdev):
9003 pin = "12345670"
9004 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9005 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9006 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9007
9008 logger.debug("Receive WSC/Start from AP")
9009 msg = get_wsc_msg(hapd)
9010 if msg['wsc_opcode'] != WSC_Start:
9011 raise Exception("Unexpected Op-Code for WSC/Start")
9012
9013 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9014 uuid_e = 16*'\x11'
9015 e_nonce = 16*'\x22'
9016 own_private, e_pk = wsc_dh_init()
9017
9018 logger.debug("Send M1 to AP")
9019 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9020 e_nonce, e_pk)
9021 send_wsc_msg(hapd, addr, m1)
9022
9023 logger.debug("Receive M2 from AP")
9024 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9025 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9026 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9027
9028 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9029 r_nonce)
9030 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9031
9032 logger.debug("Send M3 to AP")
9033 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9034 attrs += build_attr_msg_type(WPS_M3)
9035 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9036 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9037 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9038 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9039 raw_m3_attrs = attrs
9040 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9041 send_wsc_msg(hapd, addr, m3)
9042
9043 logger.debug("Receive M4 from AP")
9044 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9045
9046 logger.debug("Send M5 to AP")
9047 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9048 attrs += build_attr_msg_type(WPS_M5)
9049 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9050 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9051 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9052 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9053 raw_m5_attrs = attrs
9054 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9055 send_wsc_msg(hapd, addr, m5)
9056
9057 logger.debug("Receive M6 from AP")
9058 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9059
9060 logger.debug("Send M7 to AP")
9061 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9062 attrs += build_attr_msg_type(WPS_M7)
9063 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9064 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9065 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9066 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9067 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9068 raw_m7_attrs = attrs
9069 send_wsc_msg(hapd, addr, m7)
9070
9071 logger.debug("Receive M8 from AP")
9072 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9073 return hapd, msg, e_nonce, r_nonce
9074
9fd6804d 9075@remote_compatible
7511ead0
JM
9076def test_wps_ext_wsc_done_invalid(dev, apdev):
9077 """WPS proto: invalid WSC_Done"""
9078 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9079
9080 logger.debug("Send WSC_Done to AP")
9081 attrs = '\x10\x00\x00'
9082 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9083 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9084
9085 wps_wait_eap_failure(hapd, dev[0])
9086
9fd6804d 9087@remote_compatible
7511ead0
JM
9088def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9089 """WPS proto: invalid WSC_Done"""
9090 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9091
9092 logger.debug("Send WSC_Done to AP")
9093 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9094 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9095 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9096 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9097 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9098 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9099
9100 wps_wait_eap_failure(hapd, dev[0])
9101
9fd6804d 9102@remote_compatible
7511ead0
JM
9103def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9104 """WPS proto: WSC_Done with wrong Msg Type"""
9105 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9106
9107 logger.debug("Send WSC_Done to AP")
9108 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9109 attrs += build_attr_msg_type(WPS_WSC_ACK)
9110 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9111 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9112 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9113 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9114
9115 wps_wait_eap_failure(hapd, dev[0])
9116
9fd6804d 9117@remote_compatible
7511ead0
JM
9118def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9119 """WPS proto: WSC_Done without e_nonce"""
9120 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9121
9122 logger.debug("Send WSC_Done to AP")
9123 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9124 attrs += build_attr_msg_type(WPS_WSC_DONE)
9125 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9126 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9127 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9128 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9129
9130 wps_wait_eap_failure(hapd, dev[0])
9131
9132def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9133 """WPS proto: WSC_Done without r_nonce"""
9134 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9135
9136 logger.debug("Send WSC_Done to AP")
9137 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9138 attrs += build_attr_msg_type(WPS_WSC_DONE)
9139 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9140 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9141 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9142 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9143
9144 wps_wait_eap_failure(hapd, dev[0])
9145
9fd6804d 9146@remote_compatible
7511ead0
JM
9147def test_wps_ext_m7_no_encr_settings(dev, apdev):
9148 """WPS proto: M7 without Encr Settings"""
9149 pin = "12345670"
9150 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9151 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9152 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9153
9154 logger.debug("Receive WSC/Start from AP")
9155 msg = get_wsc_msg(hapd)
9156 if msg['wsc_opcode'] != WSC_Start:
9157 raise Exception("Unexpected Op-Code for WSC/Start")
9158
9159 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9160 uuid_e = 16*'\x11'
9161 e_nonce = 16*'\x22'
9162 own_private, e_pk = wsc_dh_init()
9163
9164 logger.debug("Send M1 to AP")
9165 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9166 e_nonce, e_pk)
9167 send_wsc_msg(hapd, addr, m1)
9168
9169 logger.debug("Receive M2 from AP")
9170 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9171 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9172 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9173
9174 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9175 r_nonce)
9176 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9177
9178 logger.debug("Send M3 to AP")
9179 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9180 attrs += build_attr_msg_type(WPS_M3)
9181 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9182 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9183 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9184 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9185 raw_m3_attrs = attrs
9186 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9187 send_wsc_msg(hapd, addr, m3)
9188
9189 logger.debug("Receive M4 from AP")
9190 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9191
9192 logger.debug("Send M5 to AP")
9193 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9194 attrs += build_attr_msg_type(WPS_M5)
9195 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9196 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9197 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9198 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9199 raw_m5_attrs = attrs
9200 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9201 send_wsc_msg(hapd, addr, m5)
9202
9203 logger.debug("Receive M6 from AP")
9204 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9205
9206 logger.debug("Send M7 to AP")
9207 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9208 attrs += build_attr_msg_type(WPS_M7)
9209 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9210 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9211 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9212 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9213 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9214 raw_m7_attrs = attrs
9215 send_wsc_msg(hapd, addr, m7)
9216
9217 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9218
9fd6804d 9219@remote_compatible
7511ead0
JM
9220def test_wps_ext_m1_workaround(dev, apdev):
9221 """WPS proto: M1 Manufacturer/Model workaround"""
9222 pin = "12345670"
9223 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9224 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9225 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9226
9227 logger.debug("Receive WSC/Start from AP")
9228 msg = get_wsc_msg(hapd)
9229 if msg['wsc_opcode'] != WSC_Start:
9230 raise Exception("Unexpected Op-Code for WSC/Start")
9231
9232 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9233 uuid_e = 16*'\x11'
9234 e_nonce = 16*'\x22'
9235 own_private, e_pk = wsc_dh_init()
9236
9237 logger.debug("Send M1 to AP")
9238 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9239 e_nonce, e_pk, manufacturer='Apple TEST',
9240 model_name='AirPort', config_methods='\xff\xff')
9241 send_wsc_msg(hapd, addr, m1)
9242
9243 logger.debug("Receive M2 from AP")
9244 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
53bd8653 9245
9fd6804d 9246@remote_compatible
53bd8653
JM
9247def test_ap_wps_disable_enable(dev, apdev):
9248 """WPS and DISABLE/ENABLE AP"""
9249 hapd = wps_start_ap(apdev[0])
9250 hapd.disable()
9251 hapd.enable()
9252 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
dd124ee8
JM
9253
9254def test_ap_wps_upnp_web_oom(dev, apdev, params):
9255 """hostapd WPS UPnP web OOM"""
9256 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
21aa8b7e 9257 hapd = add_ssdp_ap(apdev[0], ap_uuid)
dd124ee8
JM
9258
9259 location = ssdp_get_location(ap_uuid)
9260 url = urlparse.urlparse(location)
9261 urls = upnp_get_urls(location)
9262 eventurl = urlparse.urlparse(urls['event_sub_url'])
9263 ctrlurl = urlparse.urlparse(urls['control_url'])
9264
9265 conn = httplib.HTTPConnection(url.netloc)
9266 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9267 conn.request("GET", "/wps_device.xml")
9268 try:
9269 resp = conn.getresponse()
9270 except:
9271 pass
9272
9273 conn = httplib.HTTPConnection(url.netloc)
9274 conn.request("GET", "/unknown")
9275 resp = conn.getresponse()
9276 if resp.status != 404:
9277 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9278
9279 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9280 conn.request("GET", "/unknown")
9281 try:
9282 resp = conn.getresponse()
9283 print resp.status
9284 except:
9285 pass
9286
9287 conn = httplib.HTTPConnection(url.netloc)
9288 conn.request("GET", "/wps_device.xml")
9289 resp = conn.getresponse()
9290 if resp.status != 200:
9291 raise Exception("GET /wps_device.xml failed")
9292
9293 conn = httplib.HTTPConnection(url.netloc)
9294 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9295 if resp.status != 200:
9296 raise Exception("GetDeviceInfo failed")
9297
9298 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9299 conn = httplib.HTTPConnection(url.netloc)
9300 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9301 if resp.status != 500:
9302 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9303
9304 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9305 conn = httplib.HTTPConnection(url.netloc)
9306 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9307 if resp.status != 500:
9308 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9309
9310 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9311 conn = httplib.HTTPConnection(url.netloc)
9312 try:
9313 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9314 except:
9315 pass
9316
9317 conn = httplib.HTTPConnection(url.netloc)
9318 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9319 if resp.status != 200:
9320 raise Exception("GetDeviceInfo failed")
9321
9322 # No NewWLANEventType in PutWLANResponse NewMessage
9323 conn = httplib.HTTPConnection(url.netloc)
9324 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9325 if resp.status != 600:
9326 raise Exception("Unexpected HTTP response: %d" % resp.status)
9327
9328 # No NewWLANEventMAC in PutWLANResponse NewMessage
9329 conn = httplib.HTTPConnection(url.netloc)
9330 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9331 newmsg="foo", neweventtype="1")
9332 if resp.status != 600:
9333 raise Exception("Unexpected HTTP response: %d" % resp.status)
9334
9335 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9336 conn = httplib.HTTPConnection(url.netloc)
9337 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9338 newmsg="foo", neweventtype="1",
9339 neweventmac="foo")
9340 if resp.status != 600:
9341 raise Exception("Unexpected HTTP response: %d" % resp.status)
9342
9343 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9344 # Ignored unexpected PutWLANResponse WLANEventType 1
9345 conn = httplib.HTTPConnection(url.netloc)
9346 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9347 newmsg="foo", neweventtype="1",
9348 neweventmac="00.11.22.33.44.55")
9349 if resp.status != 500:
9350 raise Exception("Unexpected HTTP response: %d" % resp.status)
9351
9352 # PutWLANResponse NewMessage with invalid EAP message
9353 conn = httplib.HTTPConnection(url.netloc)
9354 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9355 newmsg="foo", neweventtype="2",
9356 neweventmac="00:11:22:33:44:55")
9357 if resp.status != 200:
9358 raise Exception("Unexpected HTTP response: %d" % resp.status)
9359
9360 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9361 conn = httplib.HTTPConnection(url.netloc)
9362 headers = { "callback": '<http://127.0.0.1:12345/event>',
9363 "NT": "upnp:event",
9364 "timeout": "Second-1234" }
9365 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9366 try:
9367 resp = conn.getresponse()
9368 except:
9369 pass
9370
9371 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9372 conn = httplib.HTTPConnection(url.netloc)
9373 headers = { "callback": '<http://127.0.0.1:12345/event>',
9374 "NT": "upnp:event",
9375 "timeout": "Second-1234" }
9376 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9377 resp = conn.getresponse()
9378 if resp.status != 500:
9379 raise Exception("Unexpected HTTP response: %d" % resp.status)
9380
9381 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9382 conn = httplib.HTTPConnection(url.netloc)
9383 headers = { "callback": '<http://127.0.0.1:12345/event>',
9384 "NT": "upnp:event",
9385 "timeout": "Second-1234" }
9386 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9387 try:
9388 resp = conn.getresponse()
9389 except:
9390 pass
9391
9392 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9393 conn = httplib.HTTPConnection(url.netloc)
9394 conn.request("HEAD", "/wps_device.xml")
9395 try:
9396 resp = conn.getresponse()
9397 except:
9398 pass
d1341917
JM
9399
9400def test_ap_wps_frag_ack_oom(dev, apdev):
9401 """WPS and fragment ack OOM"""
9402 dev[0].request("SET wps_fragment_size 50")
9403 hapd = wps_start_ap(apdev[0])
9404 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9405 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
1e35aa15
JM
9406
9407def wait_scan_stopped(dev):
9408 dev.request("ABORT_SCAN")
9409 for i in range(50):
9410 res = dev.get_driver_status_field("scan_state")
9411 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9412 break
9413 logger.debug("Waiting for scan to complete")
9414 time.sleep(0.1)
9415
9fd6804d 9416@remote_compatible
1e35aa15
JM
9417def test_ap_wps_eap_wsc_errors(dev, apdev):
9418 """WPS and EAP-WSC error cases"""
9419 ssid = "test-wps-conf-pin"
9420 appin = "12345670"
9421 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9422 "wpa_passphrase": "12345678", "wpa": "2",
9423 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9424 "fragment_size": "300", "ap_pin": appin }
8b8a1864 9425 hapd = hostapd.add_ap(apdev[0], params)
1e35aa15
JM
9426 bssid = apdev[0]['bssid']
9427
9428 pin = dev[0].wps_read_pin()
9429 hapd.request("WPS_PIN any " + pin)
9430 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9431 dev[0].dump_monitor()
9432
9433 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9434 "new passphrase", no_wait=True)
9435 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9436 if ev is None:
9437 raise Exception("WPS-FAIL not reported")
9438 dev[0].request("WPS_CANCEL")
9439 dev[0].wait_disconnected()
9440 wait_scan_stopped(dev[0])
9441 dev[0].dump_monitor()
9442
9443 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9444 "new passphrase", no_wait=True)
9445 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9446 if ev is None:
9447 raise Exception("WPS-FAIL not reported")
9448 dev[0].request("WPS_CANCEL")
9449 dev[0].wait_disconnected()
9450 wait_scan_stopped(dev[0])
9451 dev[0].dump_monitor()
9452
9453 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9454 "new passphrase", no_wait=True)
9455 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9456 if ev is None:
9457 raise Exception("WPS-FAIL not reported")
9458 dev[0].request("WPS_CANCEL")
9459 dev[0].wait_disconnected()
9460 wait_scan_stopped(dev[0])
9461 dev[0].dump_monitor()
9462
9463 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9464 "new passphrase", no_wait=True)
9465 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9466 if ev is None:
9467 raise Exception("WPS-FAIL not reported")
9468 dev[0].request("WPS_CANCEL")
9469 dev[0].wait_disconnected()
9470 wait_scan_stopped(dev[0])
9471 dev[0].dump_monitor()
9472
9473 tests = [ "eap_wsc_init",
9474 "eap_msg_alloc;eap_wsc_build_msg",
9475 "wpabuf_alloc;eap_wsc_process_fragment" ]
9476 for func in tests:
9477 with alloc_fail(dev[0], 1, func):
9478 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9479 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9480 dev[0].request("WPS_CANCEL")
9481 dev[0].wait_disconnected()
9482 wait_scan_stopped(dev[0])
9483 dev[0].dump_monitor()
d8e5a55f 9484
bd3948c0
JM
9485 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9486 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9487 "CCMP", "new passphrase", no_wait=True)
9488 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9489 dev[0].request("WPS_CANCEL")
9490 dev[0].wait_disconnected()
9491 wait_scan_stopped(dev[0])
9492 dev[0].dump_monitor()
9493
d8e5a55f
JM
9494def test_ap_wps_eap_wsc(dev, apdev):
9495 """WPS and EAP-WSC in network profile"""
9496 params = int_eap_server_params()
9497 params["wps_state"] = "2"
8b8a1864 9498 hapd = hostapd.add_ap(apdev[0], params)
d8e5a55f
JM
9499 bssid = apdev[0]['bssid']
9500
9501 logger.info("Unexpected identity")
9502 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9503 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9504 wait_connect=False)
9505 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9506 if ev is None:
9507 raise Exception("No EAP-Failure seen")
9508 dev[0].request("REMOVE_NETWORK all")
9509 dev[0].wait_disconnected()
9510
9511 logger.info("No phase1 parameter")
9512 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9513 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9514 wait_connect=False)
9515 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9516 if ev is None:
9517 raise Exception("Timeout on EAP method start")
9518 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9519 if ev is None:
9520 raise Exception("No EAP-Failure seen")
9521 dev[0].request("REMOVE_NETWORK all")
9522 dev[0].wait_disconnected()
9523
9524 logger.info("No PIN/PBC in phase1")
9525 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9526 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9527 phase1="foo", wait_connect=False)
9528 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9529 if ev is None:
9530 raise Exception("Timeout on EAP method start")
9531 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9532 if ev is None:
9533 raise Exception("No EAP-Failure seen")
9534 dev[0].request("REMOVE_NETWORK all")
9535 dev[0].wait_disconnected()
9536
9537 logger.info("Invalid pkhash in phase1")
9538 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9539 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9540 phase1="foo pkhash=q pbc=1", wait_connect=False)
9541 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9542 if ev is None:
9543 raise Exception("Timeout on EAP method start")
9544 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9545 if ev is None:
9546 raise Exception("No EAP-Failure seen")
9547 dev[0].request("REMOVE_NETWORK all")
9548 dev[0].wait_disconnected()
9549
9550 logger.info("Zero fragment_size")
9551 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9552 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9553 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9554 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9555 if ev is None:
9556 raise Exception("Timeout on EAP method start")
9557 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9558 if ev is None:
9559 raise Exception("No M2D seen")
9560 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9561 if ev is None:
9562 raise Exception("No EAP-Failure seen")
9563 dev[0].request("REMOVE_NETWORK all")
9564 dev[0].wait_disconnected()
9565
9566 logger.info("Missing new_auth")
9567 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9568 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9569 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9570 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9571 if ev is None:
9572 raise Exception("Timeout on EAP method start")
9573 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9574 if ev is None:
9575 raise Exception("No EAP-Failure seen")
9576 dev[0].request("REMOVE_NETWORK all")
9577 dev[0].wait_disconnected()
9578
9579 logger.info("Missing new_encr")
9580 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9581 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9582 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9583 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9584 if ev is None:
9585 raise Exception("Timeout on EAP method start")
9586 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9587 if ev is None:
9588 raise Exception("No EAP-Failure seen")
9589 dev[0].request("REMOVE_NETWORK all")
9590 dev[0].wait_disconnected()
9591
9592 logger.info("Missing new_key")
9593 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9594 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9595 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9596 wait_connect=False)
9597 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9598 if ev is None:
9599 raise Exception("Timeout on EAP method start")
9600 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9601 if ev is None:
9602 raise Exception("No EAP-Failure seen")
9603 dev[0].request("REMOVE_NETWORK all")
9604 dev[0].wait_disconnected()
4425b1ed
JM
9605
9606def test_ap_wps_and_bss_limit(dev, apdev):
9607 """WPS and wpa_supplicant BSS entry limit"""
9608 try:
9609 _test_ap_wps_and_bss_limit(dev, apdev)
9610 finally:
9611 dev[0].request("SET bss_max_count 200")
9612 pass
9613
9614def _test_ap_wps_and_bss_limit(dev, apdev):
9615 params = { "ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9616 "wpa_passphrase": "12345678", "wpa": "2",
9617 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
9618 hapd = hostapd.add_ap(apdev[0], params)
9619
9620 params = { "ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9621 "wpa_passphrase": "1234567890", "wpa": "2",
9622 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
9623 hapd2 = hostapd.add_ap(apdev[1], params)
9624
9625 id = dev[1].add_network()
9626 dev[1].set_network(id, "mode", "2")
9627 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9628 dev[1].set_network_quoted(id, "psk", "12345678")
9629 dev[1].set_network(id, "frequency", "2462")
9630 dev[1].set_network(id, "scan_freq", "2462")
9631 dev[1].set_network(id, "wps_disabled", "1")
9632 dev[1].select_network(id)
9633
9634 id = dev[2].add_network()
9635 dev[2].set_network(id, "mode", "2")
9636 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9637 dev[2].set_network_quoted(id, "psk", "12345678")
9638 dev[2].set_network(id, "frequency", "2437")
9639 dev[2].set_network(id, "scan_freq", "2437")
9640 dev[2].select_network(id)
9641
9642 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9643 wpas.interface_add("wlan5")
9644 id = wpas.add_network()
9645 wpas.set_network(id, "mode", "2")
9646 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9647 wpas.set_network_quoted(id, "psk", "12345678")
9648 wpas.set_network(id, "frequency", "2437")
9649 wpas.set_network(id, "scan_freq", "2437")
9650 wpas.select_network(id)
9651
9652 dev[1].wait_connected()
9653 dev[2].wait_connected()
9654 wpas.wait_connected()
9655 wpas.request("WPS_PIN any 12345670")
9656
9657 hapd.request("WPS_PBC")
9658 hapd2.request("WPS_PBC")
9659
9660 dev[0].request("SET bss_max_count 1")
9661
9662 id = dev[0].add_network()
9663 dev[0].set_network_quoted(id, "ssid", "testing")
9664
9665 id = dev[0].add_network()
9666 dev[0].set_network_quoted(id, "ssid", "testing")
9667 dev[0].set_network(id, "key_mgmt", "WPS")
9668
9669 dev[0].request("WPS_PBC")
9670 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9671 dev[0].request("WPS_CANCEL")
9672
9673 id = dev[0].add_network()
9674 dev[0].set_network_quoted(id, "ssid", "testing")
9675 dev[0].set_network(id, "key_mgmt", "WPS")
9676
9677 dev[0].scan(freq="2412")
74b23faf
JM
9678
9679def test_ap_wps_pbc_2ap(dev, apdev):
9680 """WPS PBC with two APs advertising same SSID"""
9681 params = { "ssid": "wps", "eap_server": "1", "wps_state": "2",
9682 "wpa_passphrase": "12345678", "wpa": "2",
9683 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9684 "wps_independent": "1"}
9685 hapd = hostapd.add_ap(apdev[0], params)
9686 params = { "ssid": "wps", "eap_server": "1", "wps_state": "2",
9687 "wpa_passphrase": "123456789", "wpa": "2",
9688 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9689 "wps_independent": "1"}
9690 hapd2 = hostapd.add_ap(apdev[1], params)
9691 hapd.request("WPS_PBC")
9692
9693 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9694 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9695 wpas.dump_monitor()
9696
9697 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9698 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9699 wpas.request("WPS_PBC")
9700 wpas.wait_connected()
9701 wpas.request("DISCONNECT")
9702 hapd.request("DISABLE")
9703 hapd2.request("DISABLE")
9704 wpas.flush_scan_cache()
aed9e23a
JM
9705
9706def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9707 """WPS ER enrolling a new device to a configured AP"""
9708 try:
9709 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9710 finally:
9711 dev[0].request("WPS_ER_STOP")
9712
9713def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9714 ssid = "wps-er-enrollee-to-conf-ap"
9715 ap_pin = "12345670"
9716 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9717 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9718 "wpa_passphrase": "12345678", "wpa": "2",
9719 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9720 "device_name": "Wireless AP", "manufacturer": "Company",
9721 "model_name": "WAP", "model_number": "123",
9722 "serial_number": "12345", "device_type": "6-0050F204-1",
9723 "os_version": "01020300",
9724 "config_methods": "label push_button",
9725 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9726 hapd = hostapd.add_ap(apdev[0], params)
9727 bssid = hapd.own_addr()
9728
9729 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9730 dev[0].dump_monitor()
9731
9732 dev[0].request("WPS_ER_START ifname=lo")
9733 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9734 if ev is None:
9735 raise Exception("AP discovery timed out")
9736 if ap_uuid not in ev:
9737 raise Exception("Expected AP UUID not found")
9738
9739 pin = dev[2].wps_read_pin()
9740 addr2 = dev[2].own_addr()
9741 dev[0].dump_monitor()
9742 dev[2].scan_for_bss(bssid, freq=2412)
9743 dev[2].dump_monitor()
9744 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9745
9746 for i in range(3):
9747 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9748 if ev is None:
9749 raise Exception("Enrollee not seen")
9750 if addr2 in ev:
9751 break
9752 if addr2 not in ev:
9753 raise Exception("Unexpected Enrollee MAC address")
9754 dev[0].dump_monitor()
9755
9756 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9757 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9758 dev[2].wait_connected(timeout=30)
9759 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9760 if ev is None:
9761 raise Exception("WPS ER did not report success")
9762
9763def test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9764 """WPS ER enrolling a new device to a configured AP (2)"""
9765 try:
9766 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9767 finally:
9768 dev[0].request("WPS_ER_STOP")
9769
9770def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9771 ssid = "wps-er-enrollee-to-conf-ap"
9772 ap_pin = "12345670"
9773 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9774 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9775 "wpa_passphrase": "12345678", "wpa": "2",
9776 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9777 "device_name": "Wireless AP", "manufacturer": "Company",
9778 "model_name": "WAP", "model_number": "123",
9779 "serial_number": "12345", "device_type": "6-0050F204-1",
9780 "os_version": "01020300",
9781 "config_methods": "label push_button",
9782 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9783 hapd = hostapd.add_ap(apdev[0], params)
9784 bssid = hapd.own_addr()
9785
9786 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9787 dev[0].dump_monitor()
9788
9789 dev[0].request("WPS_ER_START ifname=lo")
9790 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9791 if ev is None:
9792 raise Exception("AP discovery timed out")
9793 if ap_uuid not in ev:
9794 raise Exception("Expected AP UUID not found")
9795
9796 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
9797 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
9798 if ev is None:
9799 raise Exception("AP learn timed out")
9800 if ap_uuid not in ev:
9801 raise Exception("Expected AP UUID not in settings")
9802 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
9803 if ev is None:
9804 raise Exception("WPS-FAIL after AP learn timed out")
9805 time.sleep(0.1)
9806
9807 pin = dev[1].wps_read_pin()
9808 addr1 = dev[1].own_addr()
9809 dev[0].dump_monitor()
9810 dev[0].request("WPS_ER_PIN any " + pin)
9811 time.sleep(0.1)
9812 dev[1].scan_for_bss(bssid, freq=2412)
9813 dev[1].request("WPS_PIN any %s" % pin)
9814 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
9815 if ev is None:
9816 raise Exception("Enrollee did not report success")
9817 dev[1].wait_connected(timeout=15)
9818 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9819 if ev is None:
9820 raise Exception("WPS ER did not report success")
5026406d
JM
9821
9822def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
9823 """WPS AP trying to ignore broadcast SSID"""
9824 ssid = "test-wps"
9825 hapd = hostapd.add_ap(apdev[0],
9826 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9827 "ignore_broadcast_ssid": "1" })
9828 if "FAIL" not in hapd.request("WPS_PBC"):
9829 raise Exception("WPS unexpectedly enabled")
9830
9831def test_ap_wps_wep(dev, apdev):
9832 """WPS AP trying to enable WEP"""
9833 ssid = "test-wps"
9834 hapd = hostapd.add_ap(apdev[0],
9835 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9836 "ieee80211n": "0", "wep_key0": '"hello"' })
9837 if "FAIL" not in hapd.request("WPS_PBC"):
9838 raise Exception("WPS unexpectedly enabled")
9839
9840def test_ap_wps_tkip(dev, apdev):
9841 """WPS AP trying to enable TKIP"""
9842 ssid = "test-wps"
9843 hapd = hostapd.add_ap(apdev[0],
9844 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9845 "ieee80211n": "0", "wpa": '1',
9846 "wpa_key_mgmt": "WPA-PSK",
9847 "wpa_passphrase": "12345678" })
9848 if "FAIL" not in hapd.request("WPS_PBC"):
9849 raise Exception("WPS unexpectedly enabled")
454b66d2
JM
9850
9851def test_ap_wps_conf_dummy_cred(dev, apdev):
9852 """WPS PIN provisioning with configured AP using dummy cred"""
9853 ssid = "test-wps-conf"
9854 hapd = hostapd.add_ap(apdev[0],
9855 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9856 "wpa_passphrase": "12345678", "wpa": "2",
9857 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9858 hapd.request("WPS_PIN any 12345670")
9859 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9860 dev[0].dump_monitor()
9861 try:
9862 hapd.set("wps_testing_dummy_cred", "1")
9863 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
9864 for i in range(1, 3):
9865 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
9866 if ev is None:
9867 raise Exception("WPS credential %d not received" % i)
9868 dev[0].wait_connected(timeout=30)
9869 finally:
9870 hapd.set("wps_testing_dummy_cred", "0")
cde2143c
JM
9871
9872def test_ap_wps_rf_bands(dev, apdev):
9873 """WPS and wps_rf_bands configuration"""
9874 ssid = "test-wps-conf"
9875 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9876 "wpa_passphrase": "12345678", "wpa": "2",
9877 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9878 "wps_rf_bands": "ag" }
9879
9880 hapd = hostapd.add_ap(apdev[0], params)
9881 bssid = hapd.own_addr()
9882 hapd.request("WPS_PBC")
9883 dev[0].scan_for_bss(bssid, freq="2412")
9884 dev[0].dump_monitor()
9885 dev[0].request("WPS_PBC " + bssid)
9886 dev[0].wait_connected(timeout=30)
9887 bss = dev[0].get_bss(bssid)
9888 logger.info("BSS: " + str(bss))
9889 if "103c000103" not in bss['ie']:
9890 raise Exception("RF Bands attribute with expected values not found")
9891 dev[0].request("DISCONNECT")
9892 dev[0].wait_disconnected()
9893 hapd.set("wps_rf_bands", "ad")
9894 hapd.set("wps_rf_bands", "a")
9895 hapd.set("wps_rf_bands", "g")
9896 hapd.set("wps_rf_bands", "b")
9897 hapd.set("wps_rf_bands", "ga")
9898 hapd.disable()
9899 dev[0].dump_monitor()
9900 dev[0].flush_scan_cache()
93b85d44
JM
9901
9902def test_ap_wps_pbc_in_m1(dev, apdev):
9903 """WPS and pbc_in_m1"""
9904 ssid = "test-wps-conf"
9905 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9906 "wpa_passphrase": "12345678", "wpa": "2",
9907 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9908 "config_methods": "virtual_push_button virtual_display",
9909 "pbc_in_m1": "1" }
9910
9911 hapd = hostapd.add_ap(apdev[0], params)
9912 bssid = hapd.own_addr()
9913 hapd.request("WPS_PBC")
9914 dev[0].scan_for_bss(bssid, freq="2412")
9915 dev[0].dump_monitor()
9916 dev[0].request("WPS_PBC " + bssid)
9917 dev[0].wait_connected(timeout=30)
9918 dev[0].request("DISCONNECT")
9919 dev[0].wait_disconnected()
9920 hapd.disable()
9921 dev[0].dump_monitor()
9922 dev[0].flush_scan_cache()
35320d7a
JM
9923
9924def test_ap_wps_pin_start_failure(dev, apdev):
9925 """WPS_PIN start failure"""
9926 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
9927 if "FAIL" not in dev[0].request("WPS_PIN any 12345670"):
9928 raise Exception("WPS_PIN not rejected during OOM")
9929 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
9930 if "FAIL" not in dev[0].request("WPS_PIN any"):
9931 raise Exception("WPS_PIN not rejected during OOM")
cc5bf65f
JM
9932
9933def test_ap_wps_ap_pin_failure(dev, apdev):
9934 """WPS_AP_PIN failure"""
9935 id = dev[0].add_network()
9936 dev[0].set_network(id, "mode", "2")
9937 dev[0].set_network_quoted(id, "ssid", "wpas-ap-wps")
9938 dev[0].set_network_quoted(id, "psk", "1234567890")
9939 dev[0].set_network(id, "frequency", "2412")
9940 dev[0].set_network(id, "scan_freq", "2412")
9941 dev[0].select_network(id)
9942 dev[0].wait_connected()
9943
9944 with fail_test(dev[0], 1,
9945 "os_get_random;wpa_supplicant_ctrl_iface_wps_ap_pin"):
9946 if "FAIL" not in dev[0].request("WPS_AP_PIN random"):
9947 raise Exception("WPS_AP_PIN random accepted")
9948 with alloc_fail(dev[0], 1, "wpas_wps_ap_pin_set"):
9949 if "FAIL" not in dev[0].request("WPS_AP_PIN set 12345670"):
9950 raise Exception("WPS_AP_PIN set accepted")
9951
9952 dev[0].request("DISCONNECT")
9953 dev[0].wait_disconnected()
2087feb6
JM
9954
9955def test_ap_wps_random_uuid(dev, apdev, params):
9956 """WPS and random UUID on Enrollee"""
9957 ssid = "test-wps-conf"
9958 hapd = hostapd.add_ap(apdev[0],
9959 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9960 "wpa_passphrase": "12345678", "wpa": "2",
9961 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9962
9963 config = os.path.join(params['logdir'], 'ap_wps_random_uuid.conf')
9964 with open(config, "w") as f:
9965 f.write("auto_uuid=1\n")
9966
9967 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9968
9969 uuid = []
9970 for i in range(3):
9971 wpas.interface_add("wlan5", config=config)
9972
9973 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
9974 wpas.dump_monitor()
9975 wpas.request("WPS_PBC " + apdev[0]['bssid'])
9976
9977 ev = hapd.wait_event(["WPS-ENROLLEE-SEEN"], timeout=10)
9978 if ev is None:
9979 raise Exception("Enrollee not seen")
9980 uuid.append(ev.split(' ')[2])
9981 wpas.request("WPS_CANCEL")
9982 wpas.dump_monitor()
9983
9984 wpas.interface_remove("wlan5")
9985
9986 hapd.dump_monitor()
9987
9988 logger.info("Seen UUIDs: " + str(uuid))
9989 if uuid[0] == uuid[1] or uuid[0] == uuid[2] or uuid[1] == uuid[2]:
9990 raise Exception("Same UUID used multiple times")