]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/test_ap_wps.py
tests: Extend build_wsc_attr() to accept both bytes and str objects
[thirdparty/hostap.git] / tests / hwsim / test_ap_wps.py
1 # WPS tests
2 # Copyright (c) 2013-2017, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 from remotehost import remote_compatible
8 import base64
9 import binascii
10 from Crypto.Cipher import AES
11 import hashlib
12 import hmac
13 import os
14 import time
15 import stat
16 import subprocess
17 import logging
18 logger = logging.getLogger()
19 import re
20 import socket
21 import struct
22 try:
23 from http.client import HTTPConnection
24 from urllib.request import urlopen
25 from urllib.parse import urlparse, urljoin
26 from urllib.error import HTTPError
27 from io import StringIO
28 from socketserver import StreamRequestHandler, TCPServer
29 except ImportError:
30 from httplib import HTTPConnection
31 from urllib import urlopen
32 from urlparse import urlparse, urljoin
33 from urllib2 import build_opener, ProxyHandler, HTTPError
34 from StringIO import StringIO
35 from SocketServer import StreamRequestHandler, TCPServer
36 import urllib
37 import xml.etree.ElementTree as ET
38
39 import hwsim_utils
40 import hostapd
41 from wpasupplicant import WpaSupplicant
42 from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
43 from utils import wait_fail_trigger
44 from test_ap_eap import int_eap_server_params
45
46 def wps_start_ap(apdev, ssid="test-wps-conf"):
47 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
48 "wpa_passphrase": "12345678", "wpa": "2",
49 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
50 return hostapd.add_ap(apdev, params)
51
52 @remote_compatible
53 def test_ap_wps_init(dev, apdev):
54 """Initial AP configuration with first WPS Enrollee"""
55 ssid = "test-wps"
56 hapd = hostapd.add_ap(apdev[0],
57 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
58 logger.info("WPS provisioning step")
59 hapd.request("WPS_PBC")
60 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
61 raise Exception("PBC status not shown correctly")
62
63 id = dev[0].add_network()
64 dev[0].set_network_quoted(id, "ssid", "home")
65 dev[0].set_network_quoted(id, "psk", "12345678")
66 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
67
68 id = dev[0].add_network()
69 dev[0].set_network_quoted(id, "ssid", "home2")
70 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
71 dev[0].set_network(id, "key_mgmt", "NONE")
72 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
73
74 dev[0].request("WPS_PBC")
75 dev[0].wait_connected(timeout=30)
76 status = dev[0].get_status()
77 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
78 raise Exception("Not fully connected")
79 if status['ssid'] != ssid:
80 raise Exception("Unexpected SSID")
81 if status['pairwise_cipher'] != 'CCMP':
82 raise Exception("Unexpected encryption configuration")
83 if status['key_mgmt'] != 'WPA2-PSK':
84 raise Exception("Unexpected key_mgmt")
85
86 status = hapd.request("WPS_GET_STATUS")
87 if "PBC Status: Disabled" not in status:
88 raise Exception("PBC status not shown correctly")
89 if "Last WPS result: Success" not in status:
90 raise Exception("Last WPS result not shown correctly")
91 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
92 raise Exception("Peer address not shown correctly")
93 conf = hapd.request("GET_CONFIG")
94 if "wps_state=configured" not in conf:
95 raise Exception("AP not in WPS configured state")
96 if "wpa=3" not in conf:
97 raise Exception("AP not in WPA+WPA2 configuration")
98 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
99 raise Exception("Unexpected rsn_pairwise_cipher")
100 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
101 raise Exception("Unexpected wpa_pairwise_cipher")
102 if "group_cipher=TKIP" not in conf:
103 raise Exception("Unexpected group_cipher")
104
105 if len(dev[0].list_networks()) != 3:
106 raise Exception("Unexpected number of network blocks")
107
108 def test_ap_wps_init_2ap_pbc(dev, apdev):
109 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
110 ssid = "test-wps"
111 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
112 hapd = hostapd.add_ap(apdev[0], params)
113 hostapd.add_ap(apdev[1], params)
114 logger.info("WPS provisioning step")
115 hapd.request("WPS_PBC")
116 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
117 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
118 bss = dev[0].get_bss(apdev[0]['bssid'])
119 if "[WPS-PBC]" not in bss['flags']:
120 raise Exception("WPS-PBC flag missing from AP1")
121 bss = dev[0].get_bss(apdev[1]['bssid'])
122 if "[WPS-PBC]" not in bss['flags']:
123 raise Exception("WPS-PBC flag missing from AP2")
124 dev[0].dump_monitor()
125 dev[0].request("SET wps_cred_processing 2")
126 dev[0].request("WPS_PBC")
127 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
128 dev[0].request("SET wps_cred_processing 0")
129 if ev is None:
130 raise Exception("WPS cred event not seen")
131 if "100e" not in ev:
132 raise Exception("WPS attributes not included in the cred event")
133 dev[0].wait_connected(timeout=30)
134
135 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
136 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
137 bss = dev[1].get_bss(apdev[0]['bssid'])
138 if "[WPS-PBC]" in bss['flags']:
139 raise Exception("WPS-PBC flag not cleared from AP1")
140 bss = dev[1].get_bss(apdev[1]['bssid'])
141 if "[WPS-PBC]" in bss['flags']:
142 raise Exception("WPS-PBC flag not cleared from AP2")
143
144 def test_ap_wps_init_2ap_pin(dev, apdev):
145 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
146 ssid = "test-wps"
147 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
148 hapd = hostapd.add_ap(apdev[0], params)
149 hostapd.add_ap(apdev[1], params)
150 logger.info("WPS provisioning step")
151 pin = dev[0].wps_read_pin()
152 hapd.request("WPS_PIN any " + pin)
153 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
154 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
155 bss = dev[0].get_bss(apdev[0]['bssid'])
156 if "[WPS-AUTH]" not in bss['flags']:
157 raise Exception("WPS-AUTH flag missing from AP1")
158 bss = dev[0].get_bss(apdev[1]['bssid'])
159 if "[WPS-AUTH]" not in bss['flags']:
160 raise Exception("WPS-AUTH flag missing from AP2")
161 dev[0].dump_monitor()
162 dev[0].request("WPS_PIN any " + pin)
163 dev[0].wait_connected(timeout=30)
164
165 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
166 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
167 bss = dev[1].get_bss(apdev[0]['bssid'])
168 if "[WPS-AUTH]" in bss['flags']:
169 raise Exception("WPS-AUTH flag not cleared from AP1")
170 bss = dev[1].get_bss(apdev[1]['bssid'])
171 if "[WPS-AUTH]" in bss['flags']:
172 raise Exception("WPS-AUTH flag not cleared from AP2")
173
174 @remote_compatible
175 def test_ap_wps_init_through_wps_config(dev, apdev):
176 """Initial AP configuration using wps_config command"""
177 ssid = "test-wps-init-config"
178 hapd = hostapd.add_ap(apdev[0],
179 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
180 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
181 raise Exception("WPS_CONFIG command failed")
182 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
183 if ev is None:
184 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
185 # It takes some time for the AP to update Beacon and Probe Response frames,
186 # so wait here before requesting the scan to be started to avoid adding
187 # extra five second wait to the test due to fetching obsolete scan results.
188 hapd.ping()
189 time.sleep(0.2)
190 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
191 pairwise="CCMP", group="CCMP")
192
193 if "FAIL" not in hapd.request("WPS_CONFIG foo"):
194 raise Exception("Invalid WPS_CONFIG accepted")
195
196 @remote_compatible
197 def test_ap_wps_init_through_wps_config_2(dev, apdev):
198 """AP configuration using wps_config and wps_cred_processing=2"""
199 ssid = "test-wps-init-config"
200 hapd = hostapd.add_ap(apdev[0],
201 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
202 "wps_cred_processing": "2" })
203 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
204 raise Exception("WPS_CONFIG command failed")
205 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
206 if ev is None:
207 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
208 if "100e" not in ev:
209 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
210
211 @remote_compatible
212 def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
213 """AP configuration using wps_config command with invalid passphrase"""
214 ssid = "test-wps-init-config"
215 hapd = hostapd.add_ap(apdev[0],
216 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
217 if "FAIL" not in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"1234567").decode()):
218 raise Exception("Invalid WPS_CONFIG command accepted")
219
220 def test_ap_wps_conf(dev, apdev):
221 """WPS PBC provisioning with configured AP"""
222 ssid = "test-wps-conf"
223 hapd = hostapd.add_ap(apdev[0],
224 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
225 "wpa_passphrase": "12345678", "wpa": "2",
226 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
227 logger.info("WPS provisioning step")
228 hapd.request("WPS_PBC")
229 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
230 dev[0].dump_monitor()
231 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
232 dev[0].wait_connected(timeout=30)
233 status = dev[0].get_status()
234 if status['wpa_state'] != 'COMPLETED':
235 raise Exception("Not fully connected")
236 if status['bssid'] != apdev[0]['bssid']:
237 raise Exception("Unexpected BSSID")
238 if status['ssid'] != ssid:
239 raise Exception("Unexpected SSID")
240 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
241 raise Exception("Unexpected encryption configuration")
242 if status['key_mgmt'] != 'WPA2-PSK':
243 raise Exception("Unexpected key_mgmt")
244
245 sta = hapd.get_sta(dev[0].p2p_interface_addr())
246 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
247 raise Exception("Device name not available in STA command")
248
249 def test_ap_wps_conf_5ghz(dev, apdev):
250 """WPS PBC provisioning with configured AP on 5 GHz band"""
251 try:
252 hapd = None
253 ssid = "test-wps-conf"
254 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
255 "wpa_passphrase": "12345678", "wpa": "2",
256 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
257 "country_code": "FI", "hw_mode": "a", "channel": "36" }
258 hapd = hostapd.add_ap(apdev[0], params)
259 logger.info("WPS provisioning step")
260 hapd.request("WPS_PBC")
261 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
262 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
263 dev[0].wait_connected(timeout=30)
264
265 sta = hapd.get_sta(dev[0].p2p_interface_addr())
266 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
267 raise Exception("Device name not available in STA command")
268 finally:
269 dev[0].request("DISCONNECT")
270 if hapd:
271 hapd.request("DISABLE")
272 subprocess.call(['iw', 'reg', 'set', '00'])
273 dev[0].flush_scan_cache()
274
275 def test_ap_wps_conf_chan14(dev, apdev):
276 """WPS PBC provisioning with configured AP on channel 14"""
277 try:
278 hapd = None
279 ssid = "test-wps-conf"
280 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
281 "wpa_passphrase": "12345678", "wpa": "2",
282 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
283 "country_code": "JP", "hw_mode": "b", "channel": "14" }
284 hapd = hostapd.add_ap(apdev[0], params)
285 logger.info("WPS provisioning step")
286 hapd.request("WPS_PBC")
287 dev[0].request("WPS_PBC")
288 dev[0].wait_connected(timeout=30)
289
290 sta = hapd.get_sta(dev[0].p2p_interface_addr())
291 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
292 raise Exception("Device name not available in STA command")
293 finally:
294 dev[0].request("DISCONNECT")
295 if hapd:
296 hapd.request("DISABLE")
297 subprocess.call(['iw', 'reg', 'set', '00'])
298 dev[0].flush_scan_cache()
299
300 @remote_compatible
301 def test_ap_wps_twice(dev, apdev):
302 """WPS provisioning with twice to change passphrase"""
303 ssid = "test-wps-twice"
304 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
305 "wpa_passphrase": "12345678", "wpa": "2",
306 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
307 hapd = hostapd.add_ap(apdev[0], params)
308 logger.info("WPS provisioning step")
309 hapd.request("WPS_PBC")
310 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
311 dev[0].dump_monitor()
312 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
313 dev[0].wait_connected(timeout=30)
314 dev[0].request("DISCONNECT")
315
316 logger.info("Restart AP with different passphrase and re-run WPS")
317 hostapd.remove_bss(apdev[0])
318 params['wpa_passphrase'] = 'another passphrase'
319 hapd = hostapd.add_ap(apdev[0], params)
320 logger.info("WPS provisioning step")
321 hapd.request("WPS_PBC")
322 dev[0].dump_monitor()
323 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
324 dev[0].wait_connected(timeout=30)
325 networks = dev[0].list_networks()
326 if len(networks) > 1:
327 raise Exception("Unexpected duplicated network block present")
328
329 @remote_compatible
330 def test_ap_wps_incorrect_pin(dev, apdev):
331 """WPS PIN provisioning with incorrect PIN"""
332 ssid = "test-wps-incorrect-pin"
333 hapd = hostapd.add_ap(apdev[0],
334 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
335 "wpa_passphrase": "12345678", "wpa": "2",
336 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
337
338 logger.info("WPS provisioning attempt 1")
339 hapd.request("WPS_PIN any 12345670")
340 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
341 dev[0].dump_monitor()
342 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
343 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
344 if ev is None:
345 raise Exception("WPS operation timed out")
346 if "config_error=18" not in ev:
347 raise Exception("Incorrect config_error reported")
348 if "msg=8" not in ev:
349 raise Exception("PIN error detected on incorrect message")
350 dev[0].wait_disconnected(timeout=10)
351 dev[0].request("WPS_CANCEL")
352 # if a scan was in progress, wait for it to complete before trying WPS again
353 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
354
355 status = hapd.request("WPS_GET_STATUS")
356 if "Last WPS result: Failed" not in status:
357 raise Exception("WPS failure result not shown correctly")
358
359 logger.info("WPS provisioning attempt 2")
360 hapd.request("WPS_PIN any 12345670")
361 dev[0].dump_monitor()
362 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
363 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
364 if ev is None:
365 raise Exception("WPS operation timed out")
366 if "config_error=18" not in ev:
367 raise Exception("Incorrect config_error reported")
368 if "msg=10" not in ev:
369 raise Exception("PIN error detected on incorrect message")
370 dev[0].wait_disconnected(timeout=10)
371
372 @remote_compatible
373 def test_ap_wps_conf_pin(dev, apdev):
374 """WPS PIN provisioning with configured AP"""
375 ssid = "test-wps-conf-pin"
376 hapd = hostapd.add_ap(apdev[0],
377 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
378 "wpa_passphrase": "12345678", "wpa": "2",
379 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
380 logger.info("WPS provisioning step")
381 pin = dev[0].wps_read_pin()
382 hapd.request("WPS_PIN any " + pin)
383 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
384 dev[0].dump_monitor()
385 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
386 dev[0].wait_connected(timeout=30)
387 status = dev[0].get_status()
388 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
389 raise Exception("Not fully connected")
390 if status['ssid'] != ssid:
391 raise Exception("Unexpected SSID")
392 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
393 raise Exception("Unexpected encryption configuration")
394 if status['key_mgmt'] != 'WPA2-PSK':
395 raise Exception("Unexpected key_mgmt")
396
397 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
398 bss = dev[1].get_bss(apdev[0]['bssid'])
399 if "[WPS-AUTH]" in bss['flags']:
400 raise Exception("WPS-AUTH flag not cleared")
401 logger.info("Try to connect from another station using the same PIN")
402 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
403 ev = dev[1].wait_event(["WPS-M2D","CTRL-EVENT-CONNECTED"], timeout=30)
404 if ev is None:
405 raise Exception("Operation timed out")
406 if "WPS-M2D" not in ev:
407 raise Exception("Unexpected WPS operation started")
408 hapd.request("WPS_PIN any " + pin)
409 dev[1].wait_connected(timeout=30)
410
411 def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
412 """WPS PIN provisioning with configured AP (WPA+WPA2)"""
413 ssid = "test-wps-conf-pin-mixed"
414 hapd = hostapd.add_ap(apdev[0],
415 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
416 "wpa_passphrase": "12345678", "wpa": "3",
417 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
418 "wpa_pairwise": "TKIP" })
419
420 logger.info("WPS provisioning step")
421 pin = dev[0].wps_read_pin()
422 hapd.request("WPS_PIN any " + pin)
423 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
424 dev[0].dump_monitor()
425 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
426 dev[0].wait_connected(timeout=30)
427 status = dev[0].get_status()
428 dev[0].request("REMOVE_NETWORK all")
429 dev[0].wait_disconnected()
430 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
431 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
432
433 logger.info("WPS provisioning step (auth_types=0x1b)")
434 if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
435 raise Exception("Failed to set wps_force_auth_types 0x1b")
436 pin = dev[0].wps_read_pin()
437 hapd.request("WPS_PIN any " + pin)
438 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
439 dev[0].dump_monitor()
440 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
441 dev[0].wait_connected(timeout=30)
442 status = dev[0].get_status()
443 dev[0].request("REMOVE_NETWORK all")
444 dev[0].wait_disconnected()
445 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
446 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
447
448 logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
449 if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
450 raise Exception("Failed to set wps_force_auth_types 0")
451 if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
452 raise Exception("Failed to set wps_force_encr_types 0")
453 pin = dev[0].wps_read_pin()
454 hapd.request("WPS_PIN any " + pin)
455 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
456 dev[0].dump_monitor()
457 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
458 dev[0].wait_connected(timeout=30)
459 status = dev[0].get_status()
460 dev[0].request("REMOVE_NETWORK all")
461 dev[0].wait_disconnected()
462 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
463 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
464
465 dev[0].request("SET wps_force_auth_types ")
466 dev[0].request("SET wps_force_encr_types ")
467
468 @remote_compatible
469 def test_ap_wps_conf_pin_v1(dev, apdev):
470 """WPS PIN provisioning with configured WPS v1.0 AP"""
471 ssid = "test-wps-conf-pin-v1"
472 hapd = hostapd.add_ap(apdev[0],
473 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
474 "wpa_passphrase": "12345678", "wpa": "2",
475 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
476 logger.info("WPS provisioning step")
477 pin = dev[0].wps_read_pin()
478 hapd.request("SET wps_version_number 0x10")
479 hapd.request("WPS_PIN any " + pin)
480 found = False
481 for i in range(0, 10):
482 dev[0].scan(freq="2412")
483 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
484 found = True
485 break
486 if not found:
487 hapd.request("SET wps_version_number 0x20")
488 raise Exception("WPS-PIN flag not seen in scan results")
489 dev[0].dump_monitor()
490 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
491 dev[0].wait_connected(timeout=30)
492 hapd.request("SET wps_version_number 0x20")
493
494 @remote_compatible
495 def test_ap_wps_conf_pin_2sta(dev, apdev):
496 """Two stations trying to use WPS PIN at the same time"""
497 ssid = "test-wps-conf-pin2"
498 hapd = hostapd.add_ap(apdev[0],
499 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
500 "wpa_passphrase": "12345678", "wpa": "2",
501 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
502 logger.info("WPS provisioning step")
503 pin = "12345670"
504 pin2 = "55554444"
505 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
506 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
507 dev[0].dump_monitor()
508 dev[1].dump_monitor()
509 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
510 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
511 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
512 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
513 dev[0].wait_connected(timeout=30)
514 dev[1].wait_connected(timeout=30)
515
516 @remote_compatible
517 def test_ap_wps_conf_pin_timeout(dev, apdev):
518 """WPS PIN provisioning with configured AP timing out PIN"""
519 ssid = "test-wps-conf-pin"
520 hapd = hostapd.add_ap(apdev[0],
521 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
522 "wpa_passphrase": "12345678", "wpa": "2",
523 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
524 addr = dev[0].p2p_interface_addr()
525 pin = dev[0].wps_read_pin()
526 if "FAIL" not in hapd.request("WPS_PIN "):
527 raise Exception("Unexpected success on invalid WPS_PIN")
528 hapd.request("WPS_PIN any " + pin + " 1")
529 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
530 time.sleep(1.1)
531 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
532 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
533 if ev is None:
534 raise Exception("WPS-PIN-NEEDED event timed out")
535 ev = dev[0].wait_event(["WPS-M2D"])
536 if ev is None:
537 raise Exception("M2D not reported")
538 dev[0].request("WPS_CANCEL")
539
540 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
541 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
542 dev[0].wait_connected(timeout=30)
543
544 def test_ap_wps_reg_connect(dev, apdev):
545 """WPS registrar using AP PIN to connect"""
546 ssid = "test-wps-reg-ap-pin"
547 appin = "12345670"
548 hostapd.add_ap(apdev[0],
549 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
550 "wpa_passphrase": "12345678", "wpa": "2",
551 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
552 "ap_pin": appin})
553 logger.info("WPS provisioning step")
554 dev[0].dump_monitor()
555 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
556 dev[0].wps_reg(apdev[0]['bssid'], appin)
557 status = dev[0].get_status()
558 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
559 raise Exception("Not fully connected")
560 if status['ssid'] != ssid:
561 raise Exception("Unexpected SSID")
562 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
563 raise Exception("Unexpected encryption configuration")
564 if status['key_mgmt'] != 'WPA2-PSK':
565 raise Exception("Unexpected key_mgmt")
566
567 def test_ap_wps_reg_connect_zero_len_ap_pin(dev, apdev):
568 """hostapd with zero length ap_pin parameter"""
569 ssid = "test-wps-reg-ap-pin"
570 appin = ""
571 hostapd.add_ap(apdev[0],
572 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
573 "wpa_passphrase": "12345678", "wpa": "2",
574 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
575 "ap_pin": appin})
576 logger.info("WPS provisioning step")
577 dev[0].dump_monitor()
578 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
579 dev[0].wps_reg(apdev[0]['bssid'], appin, no_wait=True)
580 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
581 if ev is None:
582 raise Exception("No WPS-FAIL reported")
583 if "msg=5 config_error=15" not in ev:
584 raise Exception("Unexpected WPS-FAIL: " + ev)
585
586 def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
587 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
588 ssid = "test-wps-reg-ap-pin"
589 appin = "12345670"
590 hostapd.add_ap(apdev[0],
591 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
592 "wpa_passphrase": "12345678", "wpa": "3",
593 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
594 "wpa_pairwise": "TKIP", "ap_pin": appin})
595 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
596 dev[0].wps_reg(apdev[0]['bssid'], appin)
597 status = dev[0].get_status()
598 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
599 raise Exception("Not fully connected")
600 if status['ssid'] != ssid:
601 raise Exception("Unexpected SSID")
602 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
603 raise Exception("Unexpected encryption configuration")
604 if status['key_mgmt'] != 'WPA2-PSK':
605 raise Exception("Unexpected key_mgmt")
606
607 def test_ap_wps_reg_override_ap_settings(dev, apdev):
608 """WPS registrar and ap_settings override"""
609 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
610 try:
611 os.remove(ap_settings)
612 except:
613 pass
614 # Override AP Settings with values that point to another AP
615 data = build_wsc_attr(ATTR_NETWORK_INDEX, b'\x01')
616 data += build_wsc_attr(ATTR_SSID, b"test")
617 data += build_wsc_attr(ATTR_AUTH_TYPE, b'\x00\x01')
618 data += build_wsc_attr(ATTR_ENCR_TYPE, b'\x00\x01')
619 data += build_wsc_attr(ATTR_NETWORK_KEY, b'')
620 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
621 with open(ap_settings, "w") as f:
622 f.write(data)
623 ssid = "test-wps-reg-ap-pin"
624 appin = "12345670"
625 hostapd.add_ap(apdev[0],
626 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
627 "wpa_passphrase": "12345678", "wpa": "2",
628 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
629 "ap_pin": appin, "ap_settings": ap_settings })
630 hapd2 = hostapd.add_ap(apdev[1], { "ssid": "test" })
631 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
632 dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
633 dev[0].wps_reg(apdev[0]['bssid'], appin)
634 ev = hapd2.wait_event(['AP-STA-CONNECTED'], timeout=10)
635 os.remove(ap_settings)
636 if ev is None:
637 raise Exception("No connection with the other AP")
638
639 def check_wps_reg_failure(dev, ap, appin):
640 dev.request("WPS_REG " + ap['bssid'] + " " + appin)
641 ev = dev.wait_event(["WPS-SUCCESS", "WPS-FAIL"], timeout=15)
642 if ev is None:
643 raise Exception("WPS operation timed out")
644 if "WPS-SUCCESS" in ev:
645 raise Exception("WPS operation succeeded unexpectedly")
646 if "config_error=15" not in ev:
647 raise Exception("WPS setup locked state was not reported correctly")
648
649 def test_ap_wps_random_ap_pin(dev, apdev):
650 """WPS registrar using random AP PIN"""
651 ssid = "test-wps-reg-random-ap-pin"
652 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
653 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
654 "wpa_passphrase": "12345678", "wpa": "2",
655 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
656 "device_name": "Wireless AP", "manufacturer": "Company",
657 "model_name": "WAP", "model_number": "123",
658 "serial_number": "12345", "device_type": "6-0050F204-1",
659 "os_version": "01020300",
660 "config_methods": "label push_button",
661 "uuid": ap_uuid, "upnp_iface": "lo" }
662 hapd = hostapd.add_ap(apdev[0], params)
663 appin = hapd.request("WPS_AP_PIN random")
664 if "FAIL" in appin:
665 raise Exception("Could not generate random AP PIN")
666 if appin not in hapd.request("WPS_AP_PIN get"):
667 raise Exception("Could not fetch current AP PIN")
668 logger.info("WPS provisioning step")
669 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
670 dev[0].wps_reg(apdev[0]['bssid'], appin)
671
672 hapd.request("WPS_AP_PIN disable")
673 logger.info("WPS provisioning step with AP PIN disabled")
674 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
675 check_wps_reg_failure(dev[1], apdev[0], appin)
676
677 logger.info("WPS provisioning step with AP PIN reset")
678 appin = "12345670"
679 hapd.request("WPS_AP_PIN set " + appin)
680 dev[1].wps_reg(apdev[0]['bssid'], appin)
681 dev[0].request("REMOVE_NETWORK all")
682 dev[1].request("REMOVE_NETWORK all")
683 dev[0].wait_disconnected(timeout=10)
684 dev[1].wait_disconnected(timeout=10)
685
686 logger.info("WPS provisioning step after AP PIN timeout")
687 hapd.request("WPS_AP_PIN disable")
688 appin = hapd.request("WPS_AP_PIN random 1")
689 time.sleep(1.1)
690 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
691 raise Exception("AP PIN unexpectedly still enabled")
692 check_wps_reg_failure(dev[0], apdev[0], appin)
693
694 logger.info("WPS provisioning step after AP PIN timeout(2)")
695 hapd.request("WPS_AP_PIN disable")
696 appin = "12345670"
697 hapd.request("WPS_AP_PIN set " + appin + " 1")
698 time.sleep(1.1)
699 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
700 raise Exception("AP PIN unexpectedly still enabled")
701 check_wps_reg_failure(dev[1], apdev[0], appin)
702
703 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
704 hapd.request("WPS_AP_PIN random 1")
705 hapd.request("WPS_AP_PIN disable")
706
707 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
708 hapd.request("WPS_AP_PIN set 12345670")
709 hapd.request("WPS_AP_PIN disable")
710
711 if "FAIL" not in hapd.request("WPS_AP_PIN set"):
712 raise Exception("Invalid WPS_AP_PIN accepted")
713 if "FAIL" not in hapd.request("WPS_AP_PIN foo"):
714 raise Exception("Invalid WPS_AP_PIN accepted")
715
716 def test_ap_wps_reg_config(dev, apdev):
717 """WPS registrar configuring an AP using AP PIN"""
718 ssid = "test-wps-init-ap-pin"
719 appin = "12345670"
720 hostapd.add_ap(apdev[0],
721 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
722 "ap_pin": appin})
723 logger.info("WPS configuration step")
724 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
725 dev[0].dump_monitor()
726 new_ssid = "wps-new-ssid"
727 new_passphrase = "1234567890"
728 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
729 new_passphrase)
730 status = dev[0].get_status()
731 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
732 raise Exception("Not fully connected")
733 if status['ssid'] != new_ssid:
734 raise Exception("Unexpected SSID")
735 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
736 raise Exception("Unexpected encryption configuration")
737 if status['key_mgmt'] != 'WPA2-PSK':
738 raise Exception("Unexpected key_mgmt")
739
740 logger.info("Re-configure back to open")
741 dev[0].request("REMOVE_NETWORK all")
742 dev[0].flush_scan_cache()
743 dev[0].dump_monitor()
744 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
745 status = dev[0].get_status()
746 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
747 raise Exception("Not fully connected")
748 if status['ssid'] != "wps-open":
749 raise Exception("Unexpected SSID")
750 if status['key_mgmt'] != 'NONE':
751 raise Exception("Unexpected key_mgmt")
752
753 def test_ap_wps_reg_config_ext_processing(dev, apdev):
754 """WPS registrar configuring an AP with external config processing"""
755 ssid = "test-wps-init-ap-pin"
756 appin = "12345670"
757 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
758 "wps_cred_processing": "1", "ap_pin": appin}
759 hapd = hostapd.add_ap(apdev[0], params)
760 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
761 new_ssid = "wps-new-ssid"
762 new_passphrase = "1234567890"
763 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
764 new_passphrase, no_wait=True)
765 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
766 if ev is None:
767 raise Exception("WPS registrar operation timed out")
768 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
769 if ev is None:
770 raise Exception("WPS configuration timed out")
771 if "1026" not in ev:
772 raise Exception("AP Settings missing from event")
773 hapd.request("SET wps_cred_processing 0")
774 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(new_ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(new_passphrase.encode()).decode()):
775 raise Exception("WPS_CONFIG command failed")
776 dev[0].wait_connected(timeout=15)
777
778 def test_ap_wps_reg_config_tkip(dev, apdev):
779 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
780 skip_with_fips(dev[0])
781 ssid = "test-wps-init-ap"
782 appin = "12345670"
783 hostapd.add_ap(apdev[0],
784 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
785 "ap_pin": appin})
786 logger.info("WPS configuration step")
787 dev[0].request("SET wps_version_number 0x10")
788 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
789 dev[0].dump_monitor()
790 new_ssid = "wps-new-ssid-with-tkip"
791 new_passphrase = "1234567890"
792 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
793 new_passphrase)
794 logger.info("Re-connect to verify WPA2 mixed mode")
795 dev[0].request("DISCONNECT")
796 id = 0
797 dev[0].set_network(id, "pairwise", "CCMP")
798 dev[0].set_network(id, "proto", "RSN")
799 dev[0].connect_network(id)
800 status = dev[0].get_status()
801 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
802 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
803 if status['ssid'] != new_ssid:
804 raise Exception("Unexpected SSID")
805 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
806 raise Exception("Unexpected encryption configuration")
807 if status['key_mgmt'] != 'WPA2-PSK':
808 raise Exception("Unexpected key_mgmt")
809
810 def test_ap_wps_setup_locked(dev, apdev):
811 """WPS registrar locking up AP setup on AP PIN failures"""
812 ssid = "test-wps-incorrect-ap-pin"
813 appin = "12345670"
814 hapd = hostapd.add_ap(apdev[0],
815 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
816 "wpa_passphrase": "12345678", "wpa": "2",
817 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
818 "ap_pin": appin})
819 new_ssid = "wps-new-ssid-test"
820 new_passphrase = "1234567890"
821
822 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
823 ap_setup_locked=False
824 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
825 dev[0].dump_monitor()
826 logger.info("Try incorrect AP PIN - attempt " + pin)
827 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
828 "CCMP", new_passphrase, no_wait=True)
829 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
830 if ev is None:
831 raise Exception("Timeout on receiving WPS operation failure event")
832 if "CTRL-EVENT-CONNECTED" in ev:
833 raise Exception("Unexpected connection")
834 if "config_error=15" in ev:
835 logger.info("AP Setup Locked")
836 ap_setup_locked=True
837 elif "config_error=18" not in ev:
838 raise Exception("config_error=18 not reported")
839 dev[0].wait_disconnected(timeout=10)
840 time.sleep(0.1)
841 if not ap_setup_locked:
842 raise Exception("AP setup was not locked")
843 dev[0].request("WPS_CANCEL")
844 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
845 only_new=True)
846 bss = dev[0].get_bss(apdev[0]['bssid'])
847 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
848 logger.info("BSS: " + str(bss))
849 raise Exception("AP Setup Locked not indicated in scan results")
850
851 status = hapd.request("WPS_GET_STATUS")
852 if "Last WPS result: Failed" not in status:
853 raise Exception("WPS failure result not shown correctly")
854 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
855 raise Exception("Peer address not shown correctly")
856
857 time.sleep(0.5)
858 dev[0].dump_monitor()
859 logger.info("WPS provisioning step")
860 pin = dev[0].wps_read_pin()
861 hapd.request("WPS_PIN any " + pin)
862 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
863 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
864 if ev is None:
865 raise Exception("WPS success was not reported")
866 dev[0].wait_connected(timeout=30)
867
868 appin = hapd.request("WPS_AP_PIN random")
869 if "FAIL" in appin:
870 raise Exception("Could not generate random AP PIN")
871 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
872 if ev is None:
873 raise Exception("Failed to unlock AP PIN")
874
875 def test_ap_wps_setup_locked_timeout(dev, apdev):
876 """WPS re-enabling AP PIN after timeout"""
877 ssid = "test-wps-incorrect-ap-pin"
878 appin = "12345670"
879 hapd = hostapd.add_ap(apdev[0],
880 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
881 "wpa_passphrase": "12345678", "wpa": "2",
882 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
883 "ap_pin": appin})
884 new_ssid = "wps-new-ssid-test"
885 new_passphrase = "1234567890"
886
887 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
888 ap_setup_locked=False
889 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
890 dev[0].dump_monitor()
891 logger.info("Try incorrect AP PIN - attempt " + pin)
892 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
893 "CCMP", new_passphrase, no_wait=True)
894 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
895 if ev is None:
896 raise Exception("Timeout on receiving WPS operation failure event")
897 if "CTRL-EVENT-CONNECTED" in ev:
898 raise Exception("Unexpected connection")
899 if "config_error=15" in ev:
900 logger.info("AP Setup Locked")
901 ap_setup_locked=True
902 break
903 elif "config_error=18" not in ev:
904 raise Exception("config_error=18 not reported")
905 dev[0].wait_disconnected(timeout=10)
906 time.sleep(0.1)
907 if not ap_setup_locked:
908 raise Exception("AP setup was not locked")
909 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
910 if ev is None:
911 raise Exception("AP PIN did not get unlocked on 60 second timeout")
912
913 def test_ap_wps_setup_locked_2(dev, apdev):
914 """WPS AP configured for special ap_setup_locked=2 mode"""
915 ssid = "test-wps-ap-pin"
916 appin = "12345670"
917 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
918 "wpa_passphrase": "12345678", "wpa": "2",
919 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
920 "ap_pin": appin, "ap_setup_locked": "2" }
921 hapd = hostapd.add_ap(apdev[0], params)
922 new_ssid = "wps-new-ssid-test"
923 new_passphrase = "1234567890"
924
925 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
926 dev[0].wps_reg(apdev[0]['bssid'], appin)
927 dev[0].request("REMOVE_NETWORK all")
928 dev[0].wait_disconnected()
929
930 hapd.dump_monitor()
931 dev[0].dump_monitor()
932 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
933 "CCMP", new_passphrase, no_wait=True)
934
935 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
936 if ev is None:
937 raise Exception("hostapd did not report WPS failure")
938 if "msg=12 config_error=15" not in ev:
939 raise Exception("Unexpected failure reason (AP): " + ev)
940
941 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
942 if ev is None:
943 raise Exception("Timeout on receiving WPS operation failure event")
944 if "CTRL-EVENT-CONNECTED" in ev:
945 raise Exception("Unexpected connection")
946 if "config_error=15" not in ev:
947 raise Exception("Unexpected failure reason (STA): " + ev)
948 dev[0].request("WPS_CANCEL")
949 dev[0].wait_disconnected()
950
951 @remote_compatible
952 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
953 """WPS PBC session overlap with two active APs"""
954 params = { "ssid": "wps1", "eap_server": "1", "wps_state": "2",
955 "wpa_passphrase": "12345678", "wpa": "2",
956 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
957 "wps_independent": "1"}
958 hapd = hostapd.add_ap(apdev[0], params)
959 params = { "ssid": "wps2", "eap_server": "1", "wps_state": "2",
960 "wpa_passphrase": "123456789", "wpa": "2",
961 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
962 "wps_independent": "1"}
963 hapd2 = hostapd.add_ap(apdev[1], params)
964 hapd.request("WPS_PBC")
965 hapd2.request("WPS_PBC")
966 logger.info("WPS provisioning step")
967 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
968 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
969 dev[0].request("WPS_PBC")
970 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
971 if ev is None:
972 raise Exception("PBC session overlap not detected")
973 hapd.request("DISABLE")
974 hapd2.request("DISABLE")
975 dev[0].flush_scan_cache()
976
977 @remote_compatible
978 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
979 """WPS PBC session overlap with two active STAs"""
980 ssid = "test-wps-pbc-overlap"
981 hapd = hostapd.add_ap(apdev[0],
982 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
983 "wpa_passphrase": "12345678", "wpa": "2",
984 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
985 logger.info("WPS provisioning step")
986 hapd.request("WPS_PBC")
987 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
988 dev[0].dump_monitor()
989 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
990 dev[1].dump_monitor()
991 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
992 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
993 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
994 if ev is None:
995 raise Exception("PBC session overlap not detected (dev0)")
996 if "config_error=12" not in ev:
997 raise Exception("PBC session overlap not correctly reported (dev0)")
998 dev[0].request("WPS_CANCEL")
999 dev[0].request("DISCONNECT")
1000 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
1001 if ev is None:
1002 raise Exception("PBC session overlap not detected (dev1)")
1003 if "config_error=12" not in ev:
1004 raise Exception("PBC session overlap not correctly reported (dev1)")
1005 dev[1].request("WPS_CANCEL")
1006 dev[1].request("DISCONNECT")
1007 hapd.request("WPS_CANCEL")
1008 ret = hapd.request("WPS_PBC")
1009 if "FAIL" not in ret:
1010 raise Exception("PBC mode allowed to be started while PBC overlap still active")
1011 hapd.request("DISABLE")
1012 dev[0].flush_scan_cache()
1013 dev[1].flush_scan_cache()
1014
1015 @remote_compatible
1016 def test_ap_wps_cancel(dev, apdev):
1017 """WPS AP cancelling enabled config method"""
1018 ssid = "test-wps-ap-cancel"
1019 hapd = hostapd.add_ap(apdev[0],
1020 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1021 "wpa_passphrase": "12345678", "wpa": "2",
1022 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
1023 bssid = apdev[0]['bssid']
1024
1025 logger.info("Verify PBC enable/cancel")
1026 hapd.request("WPS_PBC")
1027 dev[0].scan(freq="2412")
1028 dev[0].scan(freq="2412")
1029 bss = dev[0].get_bss(apdev[0]['bssid'])
1030 if "[WPS-PBC]" not in bss['flags']:
1031 raise Exception("WPS-PBC flag missing")
1032 if "FAIL" in hapd.request("WPS_CANCEL"):
1033 raise Exception("WPS_CANCEL failed")
1034 dev[0].scan(freq="2412")
1035 dev[0].scan(freq="2412")
1036 bss = dev[0].get_bss(apdev[0]['bssid'])
1037 if "[WPS-PBC]" in bss['flags']:
1038 raise Exception("WPS-PBC flag not cleared")
1039
1040 logger.info("Verify PIN enable/cancel")
1041 hapd.request("WPS_PIN any 12345670")
1042 dev[0].scan(freq="2412")
1043 dev[0].scan(freq="2412")
1044 bss = dev[0].get_bss(apdev[0]['bssid'])
1045 if "[WPS-AUTH]" not in bss['flags']:
1046 raise Exception("WPS-AUTH flag missing")
1047 if "FAIL" in hapd.request("WPS_CANCEL"):
1048 raise Exception("WPS_CANCEL failed")
1049 dev[0].scan(freq="2412")
1050 dev[0].scan(freq="2412")
1051 bss = dev[0].get_bss(apdev[0]['bssid'])
1052 if "[WPS-AUTH]" in bss['flags']:
1053 raise Exception("WPS-AUTH flag not cleared")
1054
1055 def test_ap_wps_er_add_enrollee(dev, apdev):
1056 """WPS ER configuring AP and adding a new enrollee using PIN"""
1057 try:
1058 _test_ap_wps_er_add_enrollee(dev, apdev)
1059 finally:
1060 dev[0].request("WPS_ER_STOP")
1061
1062 def _test_ap_wps_er_add_enrollee(dev, apdev):
1063 ssid = "wps-er-add-enrollee"
1064 ap_pin = "12345670"
1065 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1066 hostapd.add_ap(apdev[0],
1067 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
1068 "device_name": "Wireless AP", "manufacturer": "Company",
1069 "model_name": "WAP", "model_number": "123",
1070 "serial_number": "12345", "device_type": "6-0050F204-1",
1071 "os_version": "01020300",
1072 'friendly_name': "WPS AP - <>&'\" - TEST",
1073 "config_methods": "label push_button",
1074 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1075 logger.info("WPS configuration step")
1076 new_passphrase = "1234567890"
1077 dev[0].dump_monitor()
1078 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1079 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1080 new_passphrase)
1081 status = dev[0].get_status()
1082 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1083 raise Exception("Not fully connected")
1084 if status['ssid'] != ssid:
1085 raise Exception("Unexpected SSID")
1086 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1087 raise Exception("Unexpected encryption configuration")
1088 if status['key_mgmt'] != 'WPA2-PSK':
1089 raise Exception("Unexpected key_mgmt")
1090
1091 logger.info("Start ER")
1092 dev[0].request("WPS_ER_START ifname=lo")
1093 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1094 if ev is None:
1095 raise Exception("AP discovery timed out")
1096 if ap_uuid not in ev:
1097 raise Exception("Expected AP UUID not found")
1098 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1099 raise Exception("Expected friendly name not found")
1100
1101 logger.info("Learn AP configuration through UPnP")
1102 dev[0].dump_monitor()
1103 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1104 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1105 if ev is None:
1106 raise Exception("AP learn timed out")
1107 if ap_uuid not in ev:
1108 raise Exception("Expected AP UUID not in settings")
1109 if "ssid=" + ssid not in ev:
1110 raise Exception("Expected SSID not in settings")
1111 if "key=" + new_passphrase not in ev:
1112 raise Exception("Expected passphrase not in settings")
1113 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1114 if ev is None:
1115 raise Exception("WPS-FAIL after AP learn timed out")
1116 time.sleep(0.1)
1117
1118 logger.info("Add Enrollee using ER")
1119 pin = dev[1].wps_read_pin()
1120 dev[0].dump_monitor()
1121 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1122 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1123 dev[1].dump_monitor()
1124 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1125 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1126 if ev is None:
1127 raise Exception("Enrollee did not report success")
1128 dev[1].wait_connected(timeout=15)
1129 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1130 if ev is None:
1131 raise Exception("WPS ER did not report success")
1132 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1133
1134 logger.info("Add a specific Enrollee using ER")
1135 pin = dev[2].wps_read_pin()
1136 addr2 = dev[2].p2p_interface_addr()
1137 dev[0].dump_monitor()
1138 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1139 dev[2].dump_monitor()
1140 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1141 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1142 if ev is None:
1143 raise Exception("Enrollee not seen")
1144 if addr2 not in ev:
1145 raise Exception("Unexpected Enrollee MAC address")
1146 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
1147 dev[2].wait_connected(timeout=30)
1148 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1149 if ev is None:
1150 raise Exception("WPS ER did not report success")
1151
1152 logger.info("Verify registrar selection behavior")
1153 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1154 dev[1].request("DISCONNECT")
1155 dev[1].wait_disconnected(timeout=10)
1156 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1157 dev[1].scan(freq="2412")
1158 bss = dev[1].get_bss(apdev[0]['bssid'])
1159 if "[WPS-AUTH]" not in bss['flags']:
1160 # It is possible for scan to miss an update especially when running
1161 # tests under load with multiple VMs, so allow another attempt.
1162 dev[1].scan(freq="2412")
1163 bss = dev[1].get_bss(apdev[0]['bssid'])
1164 if "[WPS-AUTH]" not in bss['flags']:
1165 raise Exception("WPS-AUTH flag missing")
1166
1167 logger.info("Stop ER")
1168 dev[0].dump_monitor()
1169 dev[0].request("WPS_ER_STOP")
1170 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1171 if ev is None:
1172 raise Exception("WPS ER unsubscription timed out")
1173 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
1174 # a bit before verifying that the scan results have changed.
1175 time.sleep(0.2)
1176
1177 for i in range(0, 10):
1178 dev[1].request("BSS_FLUSH 0")
1179 dev[1].scan(freq="2412", only_new=True)
1180 bss = dev[1].get_bss(apdev[0]['bssid'])
1181 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1182 break
1183 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1184 time.sleep(0.1)
1185 if "[WPS-AUTH]" in bss['flags']:
1186 raise Exception("WPS-AUTH flag not removed")
1187
1188 def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1189 """WPS ER adding a new enrollee identified by UUID"""
1190 try:
1191 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1192 finally:
1193 dev[0].request("WPS_ER_STOP")
1194
1195 def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1196 ssid = "wps-er-add-enrollee"
1197 ap_pin = "12345670"
1198 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1199 hostapd.add_ap(apdev[0],
1200 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1201 "wpa_passphrase": "12345678", "wpa": "2",
1202 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1203 "device_name": "Wireless AP", "manufacturer": "Company",
1204 "model_name": "WAP", "model_number": "123",
1205 "serial_number": "12345", "device_type": "6-0050F204-1",
1206 "os_version": "01020300",
1207 "config_methods": "label push_button",
1208 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1209 logger.info("WPS configuration step")
1210 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1211 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1212
1213 logger.info("Start ER")
1214 dev[0].request("WPS_ER_START ifname=lo")
1215 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1216 if ev is None:
1217 raise Exception("AP discovery timed out")
1218 if ap_uuid not in ev:
1219 raise Exception("Expected AP UUID not found")
1220
1221 logger.info("Learn AP configuration through UPnP")
1222 dev[0].dump_monitor()
1223 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1224 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1225 if ev is None:
1226 raise Exception("AP learn timed out")
1227 if ap_uuid not in ev:
1228 raise Exception("Expected AP UUID not in settings")
1229 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1230 if ev is None:
1231 raise Exception("WPS-FAIL after AP learn timed out")
1232 time.sleep(0.1)
1233
1234 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1235 addr1 = dev[1].p2p_interface_addr()
1236 dev[0].dump_monitor()
1237 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1238 dev[1].dump_monitor()
1239 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1240 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1241 if ev is None:
1242 raise Exception("Enrollee not seen")
1243 if addr1 not in ev:
1244 raise Exception("Unexpected Enrollee MAC address")
1245 uuid = ev.split(' ')[1]
1246 dev[0].request("WPS_ER_PBC " + uuid)
1247 dev[1].wait_connected(timeout=30)
1248 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1249 if ev is None:
1250 raise Exception("WPS ER did not report success")
1251
1252 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1253 pin = dev[2].wps_read_pin()
1254 addr2 = dev[2].p2p_interface_addr()
1255 dev[0].dump_monitor()
1256 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1257 dev[2].dump_monitor()
1258 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1259 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1260 if ev is None:
1261 raise Exception("Enrollee not seen")
1262 if addr2 not in ev:
1263 raise Exception("Unexpected Enrollee MAC address")
1264 uuid = ev.split(' ')[1]
1265 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1266 dev[2].wait_connected(timeout=30)
1267 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1268 if ev is None:
1269 raise Exception("WPS ER did not report success")
1270
1271 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1272 if ev is None:
1273 raise Exception("No Enrollee STA entry timeout seen")
1274
1275 logger.info("Stop ER")
1276 dev[0].dump_monitor()
1277 dev[0].request("WPS_ER_STOP")
1278
1279 def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1280 """Multiple WPS ERs adding a new enrollee using PIN"""
1281 try:
1282 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1283 finally:
1284 for i in range(2):
1285 dev[i].request("WPS_ER_STOP")
1286
1287 def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1288 ssid = "wps-er-add-enrollee"
1289 ap_pin = "12345670"
1290 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1291 hostapd.add_ap(apdev[0],
1292 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1293 "wpa_passphrase": "12345678", "wpa": "2",
1294 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1295 "device_name": "Wireless AP", "manufacturer": "Company",
1296 "model_name": "WAP", "model_number": "123",
1297 "serial_number": "12345", "device_type": "6-0050F204-1",
1298 "os_version": "01020300",
1299 'friendly_name': "WPS AP",
1300 "config_methods": "label push_button",
1301 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1302
1303 for i in range(2):
1304 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1305 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
1306 for i in range(2):
1307 dev[i].request("WPS_ER_START ifname=lo")
1308 for i in range(2):
1309 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1310 if ev is None:
1311 raise Exception("AP discovery timed out")
1312 dev[i].dump_monitor()
1313 for i in range(2):
1314 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1315 for i in range(2):
1316 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1317 if ev is None:
1318 raise Exception("AP learn timed out")
1319 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1320 if ev is None:
1321 raise Exception("WPS-FAIL after AP learn timed out")
1322
1323 time.sleep(0.1)
1324
1325 pin = dev[2].wps_read_pin()
1326 addr = dev[2].own_addr()
1327 dev[0].dump_monitor()
1328 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1329 dev[1].dump_monitor()
1330 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1331
1332 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1333 dev[2].dump_monitor()
1334 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1335 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1336 if ev is None:
1337 raise Exception("Enrollee did not report success")
1338 dev[2].wait_connected(timeout=15)
1339
1340 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1341 """WPS ER connected to AP and adding a new enrollee using PBC"""
1342 try:
1343 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1344 finally:
1345 dev[0].request("WPS_ER_STOP")
1346
1347 def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1348 ssid = "wps-er-add-enrollee-pbc"
1349 ap_pin = "12345670"
1350 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1351 hostapd.add_ap(apdev[0],
1352 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1353 "wpa_passphrase": "12345678", "wpa": "2",
1354 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1355 "device_name": "Wireless AP", "manufacturer": "Company",
1356 "model_name": "WAP", "model_number": "123",
1357 "serial_number": "12345", "device_type": "6-0050F204-1",
1358 "os_version": "01020300",
1359 "config_methods": "label push_button",
1360 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1361 logger.info("Learn AP configuration")
1362 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1363 dev[0].dump_monitor()
1364 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1365 status = dev[0].get_status()
1366 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1367 raise Exception("Not fully connected")
1368
1369 logger.info("Start ER")
1370 dev[0].request("WPS_ER_START ifname=lo")
1371 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1372 if ev is None:
1373 raise Exception("AP discovery timed out")
1374 if ap_uuid not in ev:
1375 raise Exception("Expected AP UUID not found")
1376
1377 enrollee = dev[1].p2p_interface_addr()
1378
1379 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1380 raise Exception("Unknown UUID not reported")
1381
1382 logger.info("Add Enrollee using ER and PBC")
1383 dev[0].dump_monitor()
1384 dev[1].dump_monitor()
1385 dev[1].request("WPS_PBC")
1386
1387 for i in range(0, 2):
1388 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1389 if ev is None:
1390 raise Exception("Enrollee discovery timed out")
1391 if enrollee in ev:
1392 break
1393 if i == 1:
1394 raise Exception("Expected Enrollee not found")
1395 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1396 raise Exception("Unknown UUID not reported")
1397 logger.info("Use learned network configuration on ER")
1398 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1399 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1400 raise Exception("WPS_ER_PBC failed")
1401
1402 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1403 if ev is None:
1404 raise Exception("Enrollee did not report success")
1405 dev[1].wait_connected(timeout=15)
1406 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1407 if ev is None:
1408 raise Exception("WPS ER did not report success")
1409 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1410
1411 def test_ap_wps_er_pbc_overlap(dev, apdev):
1412 """WPS ER connected to AP and PBC session overlap"""
1413 try:
1414 _test_ap_wps_er_pbc_overlap(dev, apdev)
1415 finally:
1416 dev[0].request("WPS_ER_STOP")
1417
1418 def _test_ap_wps_er_pbc_overlap(dev, apdev):
1419 ssid = "wps-er-add-enrollee-pbc"
1420 ap_pin = "12345670"
1421 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1422 hostapd.add_ap(apdev[0],
1423 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1424 "wpa_passphrase": "12345678", "wpa": "2",
1425 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1426 "device_name": "Wireless AP", "manufacturer": "Company",
1427 "model_name": "WAP", "model_number": "123",
1428 "serial_number": "12345", "device_type": "6-0050F204-1",
1429 "os_version": "01020300",
1430 "config_methods": "label push_button",
1431 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1432 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1433 dev[0].dump_monitor()
1434 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1435
1436 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1437 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1438 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1439 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1440
1441 dev[0].dump_monitor()
1442 dev[0].request("WPS_ER_START ifname=lo")
1443
1444 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1445 if ev is None:
1446 raise Exception("AP discovery timed out")
1447 if ap_uuid not in ev:
1448 raise Exception("Expected AP UUID not found")
1449
1450 # verify BSSID selection of the AP instead of UUID
1451 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1452 raise Exception("Could not select AP based on BSSID")
1453
1454 dev[0].dump_monitor()
1455 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1456 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1457 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1458 if ev is None:
1459 raise Exception("PBC scan failed")
1460 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1461 if ev is None:
1462 raise Exception("PBC scan failed")
1463 found1 = False
1464 found2 = False
1465 addr1 = dev[1].own_addr()
1466 addr2 = dev[2].own_addr()
1467 for i in range(3):
1468 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1469 if ev is None:
1470 raise Exception("Enrollee discovery timed out")
1471 if addr1 in ev:
1472 found1 = True
1473 if found2:
1474 break
1475 if addr2 in ev:
1476 found2 = True
1477 if found1:
1478 break
1479 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1480 raise Exception("PBC overlap not reported")
1481 dev[1].request("WPS_CANCEL")
1482 dev[2].request("WPS_CANCEL")
1483 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1484 raise Exception("Invalid WPS_ER_PBC accepted")
1485
1486 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1487 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
1488 try:
1489 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1490 finally:
1491 dev[0].request("WPS_ER_STOP")
1492
1493 def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1494 ssid = "wps-er-add-enrollee-pbc"
1495 ap_pin = "12345670"
1496 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1497 hostapd.add_ap(apdev[0],
1498 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1499 "wpa_passphrase": "12345678", "wpa": "2",
1500 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1501 "device_name": "Wireless AP", "manufacturer": "Company",
1502 "model_name": "WAP", "model_number": "123",
1503 "serial_number": "12345", "device_type": "6-0050F204-1",
1504 "os_version": "01020300",
1505 "config_methods": "label push_button",
1506 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1507 logger.info("Learn AP configuration")
1508 dev[0].request("SET wps_version_number 0x10")
1509 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1510 dev[0].dump_monitor()
1511 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1512 status = dev[0].get_status()
1513 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1514 raise Exception("Not fully connected")
1515
1516 logger.info("Start ER")
1517 dev[0].request("WPS_ER_START ifname=lo")
1518 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1519 if ev is None:
1520 raise Exception("AP discovery timed out")
1521 if ap_uuid not in ev:
1522 raise Exception("Expected AP UUID not found")
1523
1524 logger.info("Use learned network configuration on ER")
1525 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1526
1527 logger.info("Add Enrollee using ER and PIN")
1528 enrollee = dev[1].p2p_interface_addr()
1529 pin = dev[1].wps_read_pin()
1530 dev[0].dump_monitor()
1531 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1532 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1533 dev[1].dump_monitor()
1534 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1535 dev[1].wait_connected(timeout=30)
1536 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1537 if ev is None:
1538 raise Exception("WPS ER did not report success")
1539
1540 @remote_compatible
1541 def test_ap_wps_er_config_ap(dev, apdev):
1542 """WPS ER configuring AP over UPnP"""
1543 try:
1544 _test_ap_wps_er_config_ap(dev, apdev)
1545 finally:
1546 dev[0].request("WPS_ER_STOP")
1547
1548 def _test_ap_wps_er_config_ap(dev, apdev):
1549 ssid = "wps-er-ap-config"
1550 ap_pin = "12345670"
1551 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1552 hostapd.add_ap(apdev[0],
1553 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1554 "wpa_passphrase": "12345678", "wpa": "2",
1555 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1556 "device_name": "Wireless AP", "manufacturer": "Company",
1557 "model_name": "WAP", "model_number": "123",
1558 "serial_number": "12345", "device_type": "6-0050F204-1",
1559 "os_version": "01020300",
1560 "config_methods": "label push_button",
1561 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1562
1563 logger.info("Connect ER to the AP")
1564 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1565
1566 logger.info("WPS configuration step")
1567 dev[0].request("WPS_ER_START ifname=lo")
1568 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1569 if ev is None:
1570 raise Exception("AP discovery timed out")
1571 if ap_uuid not in ev:
1572 raise Exception("Expected AP UUID not found")
1573 new_passphrase = "1234567890"
1574 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1575 binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " +
1576 binascii.hexlify(new_passphrase.encode()).decode())
1577 ev = dev[0].wait_event(["WPS-SUCCESS"])
1578 if ev is None:
1579 raise Exception("WPS ER configuration operation timed out")
1580 dev[0].wait_disconnected(timeout=10)
1581 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1582
1583 logger.info("WPS ER restart")
1584 dev[0].request("WPS_ER_START")
1585 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1586 if ev is None:
1587 raise Exception("AP discovery timed out on ER restart")
1588 if ap_uuid not in ev:
1589 raise Exception("Expected AP UUID not found on ER restart")
1590 if "OK" not in dev[0].request("WPS_ER_STOP"):
1591 raise Exception("WPS_ER_STOP failed")
1592 if "OK" not in dev[0].request("WPS_ER_STOP"):
1593 raise Exception("WPS_ER_STOP failed")
1594
1595 @remote_compatible
1596 def test_ap_wps_er_cache_ap_settings(dev, apdev):
1597 """WPS ER caching AP settings"""
1598 try:
1599 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1600 finally:
1601 dev[0].request("WPS_ER_STOP")
1602
1603 def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1604 ssid = "wps-er-add-enrollee"
1605 ap_pin = "12345670"
1606 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1607 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1608 "wpa_passphrase": "12345678", "wpa": "2",
1609 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1610 "device_name": "Wireless AP", "manufacturer": "Company",
1611 "model_name": "WAP", "model_number": "123",
1612 "serial_number": "12345", "device_type": "6-0050F204-1",
1613 "os_version": "01020300",
1614 "config_methods": "label push_button",
1615 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1616 hapd = hostapd.add_ap(apdev[0], params)
1617 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1618 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1619 id = int(dev[0].list_networks()[0]['id'])
1620 dev[0].set_network(id, "scan_freq", "2412")
1621
1622 dev[0].request("WPS_ER_START ifname=lo")
1623 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1624 if ev is None:
1625 raise Exception("AP discovery timed out")
1626 if ap_uuid not in ev:
1627 raise Exception("Expected AP UUID not found")
1628
1629 dev[0].dump_monitor()
1630 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1631 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1632 if ev is None:
1633 raise Exception("AP learn timed out")
1634 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1635 if ev is None:
1636 raise Exception("WPS-FAIL after AP learn timed out")
1637 time.sleep(0.1)
1638
1639 hapd.disable()
1640
1641 for i in range(2):
1642 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1643 "CTRL-EVENT-DISCONNECTED" ],
1644 timeout=15)
1645 if ev is None:
1646 raise Exception("AP removal or disconnection timed out")
1647
1648 hapd = hostapd.add_ap(apdev[0], params)
1649 for i in range(2):
1650 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1651 timeout=15)
1652 if ev is None:
1653 raise Exception("AP discovery or connection timed out")
1654
1655 pin = dev[1].wps_read_pin()
1656 dev[0].dump_monitor()
1657 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1658
1659 time.sleep(0.2)
1660
1661 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1662 dev[1].dump_monitor()
1663 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1664 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1665 if ev is None:
1666 raise Exception("Enrollee did not report success")
1667 dev[1].wait_connected(timeout=15)
1668 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1669 if ev is None:
1670 raise Exception("WPS ER did not report success")
1671
1672 dev[0].dump_monitor()
1673 dev[0].request("WPS_ER_STOP")
1674
1675 def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1676 """WPS ER caching AP settings (OOM)"""
1677 try:
1678 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1679 finally:
1680 dev[0].request("WPS_ER_STOP")
1681
1682 def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1683 ssid = "wps-er-add-enrollee"
1684 ap_pin = "12345670"
1685 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1686 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1687 "wpa_passphrase": "12345678", "wpa": "2",
1688 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1689 "device_name": "Wireless AP", "manufacturer": "Company",
1690 "model_name": "WAP", "model_number": "123",
1691 "serial_number": "12345", "device_type": "6-0050F204-1",
1692 "os_version": "01020300",
1693 "config_methods": "label push_button",
1694 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1695 hapd = hostapd.add_ap(apdev[0], params)
1696 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1697 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1698 id = int(dev[0].list_networks()[0]['id'])
1699 dev[0].set_network(id, "scan_freq", "2412")
1700
1701 dev[0].request("WPS_ER_START ifname=lo")
1702 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1703 if ev is None:
1704 raise Exception("AP discovery timed out")
1705 if ap_uuid not in ev:
1706 raise Exception("Expected AP UUID not found")
1707
1708 dev[0].dump_monitor()
1709 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1710 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1711 if ev is None:
1712 raise Exception("AP learn timed out")
1713 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1714 if ev is None:
1715 raise Exception("WPS-FAIL after AP learn timed out")
1716 time.sleep(0.1)
1717
1718 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1719 hapd.disable()
1720
1721 for i in range(2):
1722 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1723 "CTRL-EVENT-DISCONNECTED" ],
1724 timeout=15)
1725 if ev is None:
1726 raise Exception("AP removal or disconnection timed out")
1727
1728 hapd = hostapd.add_ap(apdev[0], params)
1729 for i in range(2):
1730 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1731 timeout=15)
1732 if ev is None:
1733 raise Exception("AP discovery or connection timed out")
1734
1735 dev[0].request("WPS_ER_STOP")
1736
1737 def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1738 """WPS ER caching AP settings (OOM 2)"""
1739 try:
1740 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1741 finally:
1742 dev[0].request("WPS_ER_STOP")
1743
1744 def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1745 ssid = "wps-er-add-enrollee"
1746 ap_pin = "12345670"
1747 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1748 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1749 "wpa_passphrase": "12345678", "wpa": "2",
1750 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1751 "device_name": "Wireless AP", "manufacturer": "Company",
1752 "model_name": "WAP", "model_number": "123",
1753 "serial_number": "12345", "device_type": "6-0050F204-1",
1754 "os_version": "01020300",
1755 "config_methods": "label push_button",
1756 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1757 hapd = hostapd.add_ap(apdev[0], params)
1758 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1759 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1760 id = int(dev[0].list_networks()[0]['id'])
1761 dev[0].set_network(id, "scan_freq", "2412")
1762
1763 dev[0].request("WPS_ER_START ifname=lo")
1764 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1765 if ev is None:
1766 raise Exception("AP discovery timed out")
1767 if ap_uuid not in ev:
1768 raise Exception("Expected AP UUID not found")
1769
1770 dev[0].dump_monitor()
1771 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1772 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1773 if ev is None:
1774 raise Exception("AP learn timed out")
1775 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1776 if ev is None:
1777 raise Exception("WPS-FAIL after AP learn timed out")
1778 time.sleep(0.1)
1779
1780 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1781 hapd.disable()
1782
1783 for i in range(2):
1784 ev = dev[0].wait_event([ "WPS-ER-AP-REMOVE",
1785 "CTRL-EVENT-DISCONNECTED" ],
1786 timeout=15)
1787 if ev is None:
1788 raise Exception("AP removal or disconnection timed out")
1789
1790 hapd = hostapd.add_ap(apdev[0], params)
1791 for i in range(2):
1792 ev = dev[0].wait_event([ "WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED" ],
1793 timeout=15)
1794 if ev is None:
1795 raise Exception("AP discovery or connection timed out")
1796
1797 dev[0].request("WPS_ER_STOP")
1798
1799 def test_ap_wps_er_subscribe_oom(dev, apdev):
1800 """WPS ER subscribe OOM"""
1801 try:
1802 _test_ap_wps_er_subscribe_oom(dev, apdev)
1803 finally:
1804 dev[0].request("WPS_ER_STOP")
1805
1806 def _test_ap_wps_er_subscribe_oom(dev, apdev):
1807 ssid = "wps-er-add-enrollee"
1808 ap_pin = "12345670"
1809 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1810 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1811 "wpa_passphrase": "12345678", "wpa": "2",
1812 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1813 "device_name": "Wireless AP", "manufacturer": "Company",
1814 "model_name": "WAP", "model_number": "123",
1815 "serial_number": "12345", "device_type": "6-0050F204-1",
1816 "os_version": "01020300",
1817 "config_methods": "label push_button",
1818 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1819 hapd = hostapd.add_ap(apdev[0], params)
1820 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1821 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1822 id = int(dev[0].list_networks()[0]['id'])
1823 dev[0].set_network(id, "scan_freq", "2412")
1824
1825 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1826 dev[0].request("WPS_ER_START ifname=lo")
1827 for i in range(50):
1828 res = dev[0].request("GET_ALLOC_FAIL")
1829 if res.startswith("0:"):
1830 break
1831 time.sleep(0.1)
1832 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1833 if ev:
1834 raise Exception("Unexpected AP discovery during OOM")
1835
1836 dev[0].request("WPS_ER_STOP")
1837
1838 def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1839 """WPS ER SetSelectedRegistrar OOM"""
1840 try:
1841 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1842 finally:
1843 dev[0].request("WPS_ER_STOP")
1844
1845 def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1846 ssid = "wps-er-add-enrollee"
1847 ap_pin = "12345670"
1848 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1849 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1850 "wpa_passphrase": "12345678", "wpa": "2",
1851 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1852 "device_name": "Wireless AP", "manufacturer": "Company",
1853 "model_name": "WAP", "model_number": "123",
1854 "serial_number": "12345", "device_type": "6-0050F204-1",
1855 "os_version": "01020300",
1856 "config_methods": "label push_button",
1857 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1858 hapd = hostapd.add_ap(apdev[0], params)
1859 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1860 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1861
1862 dev[0].request("WPS_ER_START ifname=lo")
1863 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1864 if ev is None:
1865 raise Exception("AP not discovered")
1866
1867 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1868 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1869 if ev is None:
1870 raise Exception("AP learn timed out")
1871 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1872 if ev is None:
1873 raise Exception("WPS-FAIL timed out")
1874 time.sleep(0.1)
1875
1876 for func in [ "http_client_url_parse;wps_er_send_set_sel_reg",
1877 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1878 "http_client_addr;wps_er_send_set_sel_reg",
1879 "wpabuf_alloc;wps_er_set_sel_reg" ]:
1880 with alloc_fail(dev[0], 1, func):
1881 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1882 raise Exception("WPS_ER_PBC failed")
1883 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1884 if ev is None:
1885 raise Exception("WPS-PBC-ACTIVE not seen")
1886
1887 dev[0].request("WPS_ER_STOP")
1888
1889 @remote_compatible
1890 def test_ap_wps_er_learn_oom(dev, apdev):
1891 """WPS ER learn OOM"""
1892 try:
1893 _test_ap_wps_er_learn_oom(dev, apdev)
1894 finally:
1895 dev[0].request("WPS_ER_STOP")
1896
1897 def _test_ap_wps_er_learn_oom(dev, apdev):
1898 ssid = "wps-er-add-enrollee"
1899 ap_pin = "12345670"
1900 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1901 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1902 "wpa_passphrase": "12345678", "wpa": "2",
1903 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1904 "device_name": "Wireless AP", "manufacturer": "Company",
1905 "model_name": "WAP", "model_number": "123",
1906 "serial_number": "12345", "device_type": "6-0050F204-1",
1907 "os_version": "01020300",
1908 "config_methods": "label push_button",
1909 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo" }
1910 hapd = hostapd.add_ap(apdev[0], params)
1911 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1912 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1913
1914 dev[0].request("WPS_ER_START ifname=lo")
1915 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1916 if ev is None:
1917 raise Exception("AP not discovered")
1918
1919 for func in [ "wps_er_http_put_message_cb",
1920 "xml_get_base64_item;wps_er_http_put_message_cb",
1921 "http_client_url_parse;wps_er_ap_put_message",
1922 "wps_er_soap_hdr;wps_er_ap_put_message",
1923 "http_client_addr;wps_er_ap_put_message" ]:
1924 with alloc_fail(dev[0], 1, func):
1925 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1926 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1927 if ev is not None:
1928 raise Exception("AP learn succeeded during OOM")
1929
1930 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1931 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1932 if ev is None:
1933 raise Exception("AP learn did not succeed")
1934
1935 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1936 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1937
1938 dev[0].request("WPS_ER_STOP")
1939
1940 def test_ap_wps_fragmentation(dev, apdev):
1941 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1942 ssid = "test-wps-fragmentation"
1943 appin = "12345670"
1944 hapd = hostapd.add_ap(apdev[0],
1945 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1946 "wpa_passphrase": "12345678", "wpa": "3",
1947 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1948 "wpa_pairwise": "TKIP", "ap_pin": appin,
1949 "fragment_size": "50" })
1950 logger.info("WPS provisioning step (PBC)")
1951 hapd.request("WPS_PBC")
1952 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1953 dev[0].dump_monitor()
1954 dev[0].request("SET wps_fragment_size 50")
1955 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1956 dev[0].wait_connected(timeout=30)
1957 status = dev[0].get_status()
1958 if status['wpa_state'] != 'COMPLETED':
1959 raise Exception("Not fully connected")
1960 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1961 raise Exception("Unexpected encryption configuration")
1962 if status['key_mgmt'] != 'WPA2-PSK':
1963 raise Exception("Unexpected key_mgmt")
1964
1965 logger.info("WPS provisioning step (PIN)")
1966 pin = dev[1].wps_read_pin()
1967 hapd.request("WPS_PIN any " + pin)
1968 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1969 dev[1].request("SET wps_fragment_size 50")
1970 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1971 dev[1].wait_connected(timeout=30)
1972 status = dev[1].get_status()
1973 if status['wpa_state'] != 'COMPLETED':
1974 raise Exception("Not fully connected")
1975 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1976 raise Exception("Unexpected encryption configuration")
1977 if status['key_mgmt'] != 'WPA2-PSK':
1978 raise Exception("Unexpected key_mgmt")
1979
1980 logger.info("WPS connection as registrar")
1981 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1982 dev[2].request("SET wps_fragment_size 50")
1983 dev[2].wps_reg(apdev[0]['bssid'], appin)
1984 status = dev[2].get_status()
1985 if status['wpa_state'] != 'COMPLETED':
1986 raise Exception("Not fully connected")
1987 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1988 raise Exception("Unexpected encryption configuration")
1989 if status['key_mgmt'] != 'WPA2-PSK':
1990 raise Exception("Unexpected key_mgmt")
1991
1992 @remote_compatible
1993 def test_ap_wps_new_version_sta(dev, apdev):
1994 """WPS compatibility with new version number on the station"""
1995 ssid = "test-wps-ver"
1996 hapd = hostapd.add_ap(apdev[0],
1997 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
1998 "wpa_passphrase": "12345678", "wpa": "2",
1999 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
2000 logger.info("WPS provisioning step")
2001 hapd.request("WPS_PBC")
2002 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2003 dev[0].dump_monitor()
2004 dev[0].request("SET wps_version_number 0x43")
2005 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
2006 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2007 dev[0].wait_connected(timeout=30)
2008
2009 @remote_compatible
2010 def test_ap_wps_new_version_ap(dev, apdev):
2011 """WPS compatibility with new version number on the AP"""
2012 ssid = "test-wps-ver"
2013 hapd = hostapd.add_ap(apdev[0],
2014 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2015 "wpa_passphrase": "12345678", "wpa": "2",
2016 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
2017 logger.info("WPS provisioning step")
2018 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
2019 raise Exception("Failed to enable test functionality")
2020 hapd.request("WPS_PBC")
2021 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2022 dev[0].dump_monitor()
2023 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2024 dev[0].wait_connected(timeout=30)
2025 hapd.request("SET wps_version_number 0x20")
2026
2027 @remote_compatible
2028 def test_ap_wps_check_pin(dev, apdev):
2029 """Verify PIN checking through control interface"""
2030 hapd = hostapd.add_ap(apdev[0],
2031 { "ssid": "wps", "eap_server": "1", "wps_state": "2",
2032 "wpa_passphrase": "12345678", "wpa": "2",
2033 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
2034 for t in [ ("12345670", "12345670"),
2035 ("12345678", "FAIL-CHECKSUM"),
2036 ("12345", "FAIL"),
2037 ("123456789", "FAIL"),
2038 ("1234-5670", "12345670"),
2039 ("1234 5670", "12345670"),
2040 ("1-2.3:4 5670", "12345670") ]:
2041 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2042 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2043 if res != res2:
2044 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
2045 if res != t[1]:
2046 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
2047
2048 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
2049 raise Exception("Unexpected WPS_CHECK_PIN success")
2050 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
2051 raise Exception("Unexpected WPS_CHECK_PIN success")
2052
2053 for i in range(0, 10):
2054 pin = dev[0].request("WPS_PIN get")
2055 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
2056 if pin != rpin:
2057 raise Exception("Random PIN validation failed for " + pin)
2058
2059 def test_ap_wps_pin_get_failure(dev, apdev):
2060 """PIN generation failure"""
2061 with fail_test(dev[0], 1,
2062 "os_get_random;wpa_supplicant_ctrl_iface_wps_pin"):
2063 if "FAIL" not in dev[0].request("WPS_PIN get"):
2064 raise Exception("WPS_PIN did not report failure")
2065
2066 def test_ap_wps_wep_config(dev, apdev):
2067 """WPS 2.0 AP rejecting WEP configuration"""
2068 ssid = "test-wps-config"
2069 appin = "12345670"
2070 hapd = hostapd.add_ap(apdev[0],
2071 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2072 "ap_pin": appin})
2073 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2074 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2075 "hello", no_wait=True)
2076 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2077 if ev is None:
2078 raise Exception("WPS-FAIL timed out")
2079 if "reason=2" not in ev:
2080 raise Exception("Unexpected reason code in WPS-FAIL")
2081 status = hapd.request("WPS_GET_STATUS")
2082 if "Last WPS result: Failed" not in status:
2083 raise Exception("WPS failure result not shown correctly")
2084 if "Failure Reason: WEP Prohibited" not in status:
2085 raise Exception("Failure reason not reported correctly")
2086 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2087 raise Exception("Peer address not shown correctly")
2088
2089 def test_ap_wps_wep_enroll(dev, apdev):
2090 """WPS 2.0 STA rejecting WEP configuration"""
2091 ssid = "test-wps-wep"
2092 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2093 "skip_cred_build": "1", "extra_cred": "wps-wep-cred" }
2094 hapd = hostapd.add_ap(apdev[0], params)
2095 hapd.request("WPS_PBC")
2096 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2097 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2098 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2099 if ev is None:
2100 raise Exception("WPS-FAIL event timed out")
2101 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2102 raise Exception("Unexpected WPS-FAIL event: " + ev)
2103
2104 @remote_compatible
2105 def test_ap_wps_ie_fragmentation(dev, apdev):
2106 """WPS AP using fragmented WPS IE"""
2107 ssid = "test-wps-ie-fragmentation"
2108 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2109 "wpa_passphrase": "12345678", "wpa": "2",
2110 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2111 "device_name": "1234567890abcdef1234567890abcdef",
2112 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2113 "model_name": "1234567890abcdef1234567890abcdef",
2114 "model_number": "1234567890abcdef1234567890abcdef",
2115 "serial_number": "1234567890abcdef1234567890abcdef" }
2116 hapd = hostapd.add_ap(apdev[0], params)
2117 hapd.request("WPS_PBC")
2118 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2119 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2120 dev[0].wait_connected(timeout=30)
2121 bss = dev[0].get_bss(apdev[0]['bssid'])
2122 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
2123 logger.info("Device Name not received correctly")
2124 logger.info(bss)
2125 # This can fail if Probe Response frame is missed and Beacon frame was
2126 # used to fill in the BSS entry. This can happen, e.g., during heavy
2127 # load every now and then and is not really an error, so try to
2128 # workaround by runnign another scan.
2129 dev[0].scan(freq="2412", only_new=True)
2130 bss = dev[0].get_bss(apdev[0]['bssid'])
2131 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
2132 logger.info(bss)
2133 raise Exception("Device Name not received correctly")
2134 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2135 raise Exception("Unexpected number of WPS IEs")
2136
2137 def get_psk(pskfile):
2138 psks = {}
2139 with open(pskfile, "r") as f:
2140 lines = f.read().splitlines()
2141 for l in lines:
2142 if l == "# WPA PSKs":
2143 continue
2144 (addr,psk) = l.split(' ')
2145 psks[addr] = psk
2146 return psks
2147
2148 def test_ap_wps_per_station_psk(dev, apdev):
2149 """WPS PBC provisioning with per-station PSK"""
2150 addr0 = dev[0].own_addr()
2151 addr1 = dev[1].own_addr()
2152 addr2 = dev[2].own_addr()
2153 ssid = "wps"
2154 appin = "12345670"
2155 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2156 try:
2157 os.remove(pskfile)
2158 except:
2159 pass
2160
2161 hapd = None
2162 try:
2163 with open(pskfile, "w") as f:
2164 f.write("# WPA PSKs\n")
2165
2166 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2167 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2168 "rsn_pairwise": "CCMP", "ap_pin": appin,
2169 "wpa_psk_file": pskfile }
2170 hapd = hostapd.add_ap(apdev[0], params)
2171
2172 logger.info("First enrollee")
2173 hapd.request("WPS_PBC")
2174 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2175 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2176 dev[0].wait_connected(timeout=30)
2177
2178 logger.info("Second enrollee")
2179 hapd.request("WPS_PBC")
2180 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2181 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2182 dev[1].wait_connected(timeout=30)
2183
2184 logger.info("External registrar")
2185 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2186 dev[2].wps_reg(apdev[0]['bssid'], appin)
2187
2188 logger.info("Verifying PSK results")
2189 psks = get_psk(pskfile)
2190 if addr0 not in psks:
2191 raise Exception("No PSK recorded for sta0")
2192 if addr1 not in psks:
2193 raise Exception("No PSK recorded for sta1")
2194 if addr2 not in psks:
2195 raise Exception("No PSK recorded for sta2")
2196 if psks[addr0] == psks[addr1]:
2197 raise Exception("Same PSK recorded for sta0 and sta1")
2198 if psks[addr0] == psks[addr2]:
2199 raise Exception("Same PSK recorded for sta0 and sta2")
2200 if psks[addr1] == psks[addr2]:
2201 raise Exception("Same PSK recorded for sta1 and sta2")
2202
2203 dev[0].request("REMOVE_NETWORK all")
2204 logger.info("Second external registrar")
2205 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2206 dev[0].wps_reg(apdev[0]['bssid'], appin)
2207 psks2 = get_psk(pskfile)
2208 if addr0 not in psks2:
2209 raise Exception("No PSK recorded for sta0(reg)")
2210 if psks[addr0] == psks2[addr0]:
2211 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2212 finally:
2213 os.remove(pskfile)
2214 if hapd:
2215 dev[0].request("DISCONNECT")
2216 dev[1].request("DISCONNECT")
2217 dev[2].request("DISCONNECT")
2218 hapd.disable()
2219 dev[0].flush_scan_cache()
2220 dev[1].flush_scan_cache()
2221 dev[2].flush_scan_cache()
2222
2223 def test_ap_wps_per_station_psk_failure(dev, apdev):
2224 """WPS PBC provisioning with per-station PSK (file not writable)"""
2225 addr0 = dev[0].p2p_dev_addr()
2226 addr1 = dev[1].p2p_dev_addr()
2227 addr2 = dev[2].p2p_dev_addr()
2228 ssid = "wps"
2229 appin = "12345670"
2230 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2231 try:
2232 os.remove(pskfile)
2233 except:
2234 pass
2235
2236 hapd = None
2237 try:
2238 with open(pskfile, "w") as f:
2239 f.write("# WPA PSKs\n")
2240
2241 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2242 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2243 "rsn_pairwise": "CCMP", "ap_pin": appin,
2244 "wpa_psk_file": pskfile }
2245 hapd = hostapd.add_ap(apdev[0], params)
2246 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2247 raise Exception("Failed to set wpa_psk_file")
2248
2249 logger.info("First enrollee")
2250 hapd.request("WPS_PBC")
2251 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2252 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2253 dev[0].wait_connected(timeout=30)
2254
2255 logger.info("Second enrollee")
2256 hapd.request("WPS_PBC")
2257 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2258 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2259 dev[1].wait_connected(timeout=30)
2260
2261 logger.info("External registrar")
2262 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2263 dev[2].wps_reg(apdev[0]['bssid'], appin)
2264
2265 logger.info("Verifying PSK results")
2266 psks = get_psk(pskfile)
2267 if len(psks) > 0:
2268 raise Exception("PSK recorded unexpectedly")
2269 finally:
2270 if hapd:
2271 for i in range(3):
2272 dev[i].request("DISCONNECT")
2273 hapd.disable()
2274 for i in range(3):
2275 dev[i].flush_scan_cache()
2276 os.remove(pskfile)
2277
2278 def test_ap_wps_pin_request_file(dev, apdev):
2279 """WPS PIN provisioning with configured AP"""
2280 ssid = "wps"
2281 pinfile = "/tmp/ap_wps_pin_request_file.log"
2282 if os.path.exists(pinfile):
2283 os.remove(pinfile)
2284 hapd = hostapd.add_ap(apdev[0],
2285 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2286 "wps_pin_requests": pinfile,
2287 "wpa_passphrase": "12345678", "wpa": "2",
2288 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2289 uuid = dev[0].get_status_field("uuid")
2290 pin = dev[0].wps_read_pin()
2291 try:
2292 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2293 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
2294 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2295 if ev is None:
2296 raise Exception("PIN needed event not shown")
2297 if uuid not in ev:
2298 raise Exception("UUID mismatch")
2299 dev[0].request("WPS_CANCEL")
2300 success = False
2301 with open(pinfile, "r") as f:
2302 lines = f.readlines()
2303 for l in lines:
2304 if uuid in l:
2305 success = True
2306 break
2307 if not success:
2308 raise Exception("PIN request entry not in the log file")
2309 finally:
2310 try:
2311 os.remove(pinfile)
2312 except:
2313 pass
2314
2315 def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2316 """WPS auto-setup with configuration file"""
2317 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2318 ifname = apdev[0]['ifname']
2319 try:
2320 with open(conffile, "w") as f:
2321 f.write("driver=nl80211\n")
2322 f.write("hw_mode=g\n")
2323 f.write("channel=1\n")
2324 f.write("ieee80211n=1\n")
2325 f.write("interface=%s\n" % ifname)
2326 f.write("ctrl_interface=/var/run/hostapd\n")
2327 f.write("ssid=wps\n")
2328 f.write("eap_server=1\n")
2329 f.write("wps_state=1\n")
2330 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
2331 hapd.request("WPS_PBC")
2332 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2333 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2334 dev[0].wait_connected(timeout=30)
2335 with open(conffile, "r") as f:
2336 lines = f.read().splitlines()
2337 vals = dict()
2338 for l in lines:
2339 try:
2340 [name,value] = l.split('=', 1)
2341 vals[name] = value
2342 except ValueError as e:
2343 if "# WPS configuration" in l:
2344 pass
2345 else:
2346 raise Exception("Unexpected configuration line: " + l)
2347 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2348 raise Exception("Incorrect configuration: " + str(vals))
2349 finally:
2350 try:
2351 os.remove(conffile)
2352 except:
2353 pass
2354
2355 def test_ap_wps_pbc_timeout(dev, apdev, params):
2356 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
2357 if not params['long']:
2358 raise HwsimSkip("Skip test case with long duration due to --long not specified")
2359 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2360 hapd = add_ssdp_ap(apdev[0], ap_uuid)
2361
2362 location = ssdp_get_location(ap_uuid)
2363 urls = upnp_get_urls(location)
2364 eventurl = urlparse(urls['event_sub_url'])
2365 ctrlurl = urlparse(urls['control_url'])
2366
2367 url = urlparse(location)
2368 conn = HTTPConnection(url.netloc)
2369
2370 class WPSERHTTPServer(StreamRequestHandler):
2371 def handle(self):
2372 data = self.rfile.readline().strip()
2373 logger.debug(data)
2374 self.wfile.write(gen_wps_event())
2375
2376 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2377 server.timeout = 1
2378
2379 headers = { "callback": '<http://127.0.0.1:12345/event>',
2380 "NT": "upnp:event",
2381 "timeout": "Second-1234" }
2382 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2383 resp = conn.getresponse()
2384 if resp.status != 200:
2385 raise Exception("Unexpected HTTP response: %d" % resp.status)
2386 sid = resp.getheader("sid")
2387 logger.debug("Subscription SID " + sid)
2388
2389 msg = '''<?xml version="1.0"?>
2390 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2391 <s:Body>
2392 <u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2393 <NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2394 VFi5hrLk
2395 </NewMessage>
2396 </u:SetSelectedRegistrar>
2397 </s:Body>
2398 </s:Envelope>'''
2399 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2400 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2401 conn.request("POST", ctrlurl.path, msg, headers)
2402 resp = conn.getresponse()
2403 if resp.status != 200:
2404 raise Exception("Unexpected HTTP response: %d" % resp.status)
2405
2406 server.handle_request()
2407
2408 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2409 if "OK" not in dev[0].request("WPS_PBC"):
2410 raise Exception("WPS_PBC failed")
2411
2412 start = os.times()[4]
2413
2414 server.handle_request()
2415 dev[1].request("BSS_FLUSH 0")
2416 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2417 only_new=True)
2418 bss = dev[1].get_bss(apdev[0]['bssid'])
2419 logger.debug("BSS: " + str(bss))
2420 if '[WPS-AUTH]' not in bss['flags']:
2421 raise Exception("WPS not indicated authorized")
2422
2423 server.handle_request()
2424
2425 wps_timeout_seen = False
2426
2427 while True:
2428 hapd.dump_monitor()
2429 dev[1].dump_monitor()
2430 if not wps_timeout_seen:
2431 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2432 if ev is not None:
2433 logger.info("PBC timeout seen")
2434 wps_timeout_seen = True
2435 else:
2436 dev[0].dump_monitor()
2437 now = os.times()[4]
2438 if now - start > 130:
2439 raise Exception("Selected registration information not removed")
2440 dev[1].request("BSS_FLUSH 0")
2441 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2442 only_new=True)
2443 bss = dev[1].get_bss(apdev[0]['bssid'])
2444 logger.debug("BSS: " + str(bss))
2445 if '[WPS-AUTH]' not in bss['flags']:
2446 break
2447 server.handle_request()
2448
2449 server.server_close()
2450
2451 if wps_timeout_seen:
2452 return
2453
2454 now = os.times()[4]
2455 if now < start + 150:
2456 dur = start + 150 - now
2457 else:
2458 dur = 1
2459 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2460 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
2461 if ev is None:
2462 raise Exception("WPS-TIMEOUT not reported")
2463
2464 def add_ssdp_ap(ap, ap_uuid):
2465 ssid = "wps-ssdp"
2466 ap_pin = "12345670"
2467 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
2468 "wpa_passphrase": "12345678", "wpa": "2",
2469 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2470 "device_name": "Wireless AP", "manufacturer": "Company",
2471 "model_name": "WAP", "model_number": "123",
2472 "serial_number": "12345", "device_type": "6-0050F204-1",
2473 "os_version": "01020300",
2474 "config_methods": "label push_button",
2475 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2476 "friendly_name": "WPS Access Point",
2477 "manufacturer_url": "http://www.example.com/",
2478 "model_description": "Wireless Access Point",
2479 "model_url": "http://www.example.com/model/",
2480 "upc": "123456789012" }
2481 return hostapd.add_ap(ap, params)
2482
2483 def ssdp_send(msg, no_recv=False):
2484 socket.setdefaulttimeout(1)
2485 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2486 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2487 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2488 sock.bind(("127.0.0.1", 0))
2489 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2490 if no_recv:
2491 return None
2492 return sock.recv(1000).decode()
2493
2494 def ssdp_send_msearch(st, no_recv=False):
2495 msg = '\r\n'.join([
2496 'M-SEARCH * HTTP/1.1',
2497 'HOST: 239.255.255.250:1900',
2498 'MX: 1',
2499 'MAN: "ssdp:discover"',
2500 'ST: ' + st,
2501 '', ''])
2502 return ssdp_send(msg, no_recv=no_recv)
2503
2504 def test_ap_wps_ssdp_msearch(dev, apdev):
2505 """WPS AP and SSDP M-SEARCH messages"""
2506 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2507 add_ssdp_ap(apdev[0], ap_uuid)
2508
2509 msg = '\r\n'.join([
2510 'M-SEARCH * HTTP/1.1',
2511 'Host: 239.255.255.250:1900',
2512 'Mx: 1',
2513 'Man: "ssdp:discover"',
2514 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2515 '', ''])
2516 ssdp_send(msg)
2517
2518 msg = '\r\n'.join([
2519 'M-SEARCH * HTTP/1.1',
2520 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2521 'mx: \t1\t\t ',
2522 'man: \t \t "ssdp:discover" ',
2523 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2524 '', ''])
2525 ssdp_send(msg)
2526
2527 ssdp_send_msearch("ssdp:all")
2528 ssdp_send_msearch("upnp:rootdevice")
2529 ssdp_send_msearch("uuid:" + ap_uuid)
2530 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2531 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1")
2532
2533 msg = '\r\n'.join([
2534 'M-SEARCH * HTTP/1.1',
2535 'HOST:\t239.255.255.250:1900',
2536 'MAN: "ssdp:discover"',
2537 'MX: 130',
2538 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2539 '', ''])
2540 ssdp_send(msg, no_recv=True)
2541
2542 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2543 """WPS AP and invalid SSDP M-SEARCH messages"""
2544 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2545 add_ssdp_ap(apdev[0], ap_uuid)
2546
2547 socket.setdefaulttimeout(1)
2548 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2549 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2550 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2551 sock.bind(("127.0.0.1", 0))
2552
2553 logger.debug("Missing MX")
2554 msg = '\r\n'.join([
2555 'M-SEARCH * HTTP/1.1',
2556 'HOST: 239.255.255.250:1900',
2557 'MAN: "ssdp:discover"',
2558 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2559 '', ''])
2560 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2561
2562 logger.debug("Negative 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.encode(), ("239.255.255.250", 1900))
2571
2572 logger.debug("Invalid MX")
2573 msg = '\r\n'.join([
2574 'M-SEARCH * HTTP/1.1',
2575 'HOST: 239.255.255.250:1900',
2576 'MX; 1',
2577 'MAN: "ssdp:discover"',
2578 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2579 '', ''])
2580 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2581
2582 logger.debug("Missing MAN")
2583 msg = '\r\n'.join([
2584 'M-SEARCH * HTTP/1.1',
2585 'HOST: 239.255.255.250:1900',
2586 'MX: 1',
2587 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2588 '', ''])
2589 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2590
2591 logger.debug("Invalid MAN")
2592 msg = '\r\n'.join([
2593 'M-SEARCH * HTTP/1.1',
2594 'HOST: 239.255.255.250:1900',
2595 'MX: 1',
2596 'MAN: foo',
2597 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2598 '', ''])
2599 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2600 msg = '\r\n'.join([
2601 'M-SEARCH * HTTP/1.1',
2602 'HOST: 239.255.255.250:1900',
2603 'MX: 1',
2604 'MAN; "ssdp:discover"',
2605 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2606 '', ''])
2607 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2608
2609 logger.debug("Missing HOST")
2610 msg = '\r\n'.join([
2611 'M-SEARCH * HTTP/1.1',
2612 'MAN: "ssdp:discover"',
2613 'MX: 1',
2614 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2615 '', ''])
2616 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2617
2618 logger.debug("Missing ST")
2619 msg = '\r\n'.join([
2620 'M-SEARCH * HTTP/1.1',
2621 'HOST: 239.255.255.250:1900',
2622 'MAN: "ssdp:discover"',
2623 'MX: 1',
2624 '', ''])
2625 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2626
2627 logger.debug("Mismatching ST")
2628 msg = '\r\n'.join([
2629 'M-SEARCH * HTTP/1.1',
2630 'HOST: 239.255.255.250:1900',
2631 'MAN: "ssdp:discover"',
2632 'MX: 1',
2633 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2634 '', ''])
2635 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2636 msg = '\r\n'.join([
2637 'M-SEARCH * HTTP/1.1',
2638 'HOST: 239.255.255.250:1900',
2639 'MAN: "ssdp:discover"',
2640 'MX: 1',
2641 'ST: foo:bar',
2642 '', ''])
2643 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
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: foobar',
2650 '', ''])
2651 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2652
2653 logger.debug("Invalid ST")
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.encode(), ("239.255.255.250", 1900))
2662
2663 logger.debug("Invalid M-SEARCH")
2664 msg = '\r\n'.join([
2665 'M+SEARCH * HTTP/1.1',
2666 'HOST: 239.255.255.250:1900',
2667 'MAN: "ssdp:discover"',
2668 'MX: 1',
2669 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2670 '', ''])
2671 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2672 msg = '\r\n'.join([
2673 'M-SEARCH-* HTTP/1.1',
2674 'HOST: 239.255.255.250:1900',
2675 'MAN: "ssdp:discover"',
2676 'MX: 1',
2677 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2678 '', ''])
2679 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2680
2681 logger.debug("Invalid message format")
2682 sock.sendto(b"NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2683 msg = '\r'.join([
2684 'M-SEARCH * HTTP/1.1',
2685 'HOST: 239.255.255.250:1900',
2686 'MAN: "ssdp:discover"',
2687 'MX: 1',
2688 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2689 '', ''])
2690 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2691
2692 try:
2693 r = sock.recv(1000)
2694 raise Exception("Unexpected M-SEARCH response: " + r)
2695 except socket.timeout:
2696 pass
2697
2698 logger.debug("Valid M-SEARCH")
2699 msg = '\r\n'.join([
2700 'M-SEARCH * HTTP/1.1',
2701 'HOST: 239.255.255.250:1900',
2702 'MAN: "ssdp:discover"',
2703 'MX: 1',
2704 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2705 '', ''])
2706 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2707
2708 try:
2709 r = sock.recv(1000)
2710 pass
2711 except socket.timeout:
2712 raise Exception("No SSDP response")
2713
2714 def test_ap_wps_ssdp_burst(dev, apdev):
2715 """WPS AP and SSDP burst"""
2716 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2717 add_ssdp_ap(apdev[0], ap_uuid)
2718
2719 msg = '\r\n'.join([
2720 'M-SEARCH * HTTP/1.1',
2721 'HOST: 239.255.255.250:1900',
2722 'MAN: "ssdp:discover"',
2723 'MX: 1',
2724 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2725 '', ''])
2726 socket.setdefaulttimeout(1)
2727 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2728 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2729 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2730 sock.bind(("127.0.0.1", 0))
2731 for i in range(0, 25):
2732 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2733 resp = 0
2734 while True:
2735 try:
2736 r = sock.recv(1000).decode()
2737 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2738 raise Exception("Unexpected message: " + r)
2739 resp += 1
2740 except socket.timeout:
2741 break
2742 if resp < 20:
2743 raise Exception("Too few SSDP responses")
2744
2745 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2746 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2747 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2748 sock.bind(("127.0.0.1", 0))
2749 for i in range(0, 25):
2750 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2751 while True:
2752 try:
2753 r = sock.recv(1000).decode()
2754 if ap_uuid in r:
2755 break
2756 except socket.timeout:
2757 raise Exception("No SSDP response")
2758
2759 def ssdp_get_location(uuid):
2760 res = ssdp_send_msearch("uuid:" + uuid)
2761 location = None
2762 for l in res.splitlines():
2763 if l.lower().startswith("location:"):
2764 location = l.split(':', 1)[1].strip()
2765 break
2766 if location is None:
2767 raise Exception("No UPnP location found")
2768 return location
2769
2770 def upnp_get_urls(location):
2771 conn = urlopen(location, proxies={})
2772 tree = ET.parse(conn)
2773 root = tree.getroot()
2774 urn = '{urn:schemas-upnp-org:device-1-0}'
2775 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2776 res = {}
2777 res['scpd_url'] = urljoin(location, service.find(urn + 'SCPDURL').text)
2778 res['control_url'] = urljoin(location,
2779 service.find(urn + 'controlURL').text)
2780 res['event_sub_url'] = urljoin(location,
2781 service.find(urn + 'eventSubURL').text)
2782 return res
2783
2784 def upnp_soap_action(conn, path, action, include_soap_action=True,
2785 soap_action_override=None, newmsg=None, neweventtype=None,
2786 neweventmac=None):
2787 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2788 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2789 ET.register_namespace('soapenv', soapns)
2790 ET.register_namespace('wfa', wpsns)
2791 attrib = {}
2792 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2793 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2794 body = ET.SubElement(root, "{%s}Body" % soapns)
2795 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
2796 if newmsg:
2797 msg = ET.SubElement(act, "NewMessage")
2798 msg.text = base64.b64encode(newmsg.encode()).decode()
2799 if neweventtype:
2800 msg = ET.SubElement(act, "NewWLANEventType")
2801 msg.text = neweventtype
2802 if neweventmac:
2803 msg = ET.SubElement(act, "NewWLANEventMAC")
2804 msg.text = neweventmac
2805 tree = ET.ElementTree(root)
2806 soap = StringIO()
2807 tree.write(soap, xml_declaration=True, encoding='utf-8')
2808
2809 headers = { "Content-type": 'text/xml; charset="utf-8"' }
2810 if include_soap_action:
2811 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2812 elif soap_action_override:
2813 headers["SOAPAction"] = soap_action_override
2814 conn.request("POST", path, soap.getvalue(), headers)
2815 return conn.getresponse()
2816
2817 def test_ap_wps_upnp(dev, apdev):
2818 """WPS AP and UPnP operations"""
2819 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2820 add_ssdp_ap(apdev[0], ap_uuid)
2821
2822 location = ssdp_get_location(ap_uuid)
2823 urls = upnp_get_urls(location)
2824
2825 conn = urlopen(urls['scpd_url'], proxies={})
2826 scpd = conn.read()
2827
2828 conn = urlopen(urljoin(location, "unknown.html"), proxies={})
2829 if conn.getcode() != 404:
2830 raise Exception("Unexpected HTTP response to GET unknown URL")
2831
2832 url = urlparse(location)
2833 conn = HTTPConnection(url.netloc)
2834 #conn.set_debuglevel(1)
2835 headers = { "Content-type": 'text/xml; charset="utf-8"',
2836 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"' }
2837 conn.request("POST", "hello", "\r\n\r\n", headers)
2838 resp = conn.getresponse()
2839 if resp.status != 404:
2840 raise Exception("Unexpected HTTP response: %d" % resp.status)
2841
2842 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2843 resp = conn.getresponse()
2844 if resp.status != 501:
2845 raise Exception("Unexpected HTTP response: %d" % resp.status)
2846
2847 headers = { "Content-type": 'text/xml; charset="utf-8"',
2848 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"' }
2849 ctrlurl = urlparse(urls['control_url'])
2850 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2851 resp = conn.getresponse()
2852 if resp.status != 401:
2853 raise Exception("Unexpected HTTP response: %d" % resp.status)
2854
2855 logger.debug("GetDeviceInfo without SOAPAction header")
2856 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2857 include_soap_action=False)
2858 if resp.status != 401:
2859 raise Exception("Unexpected HTTP response: %d" % resp.status)
2860
2861 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2862 for act in [ "foo",
2863 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2864 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2865 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2866 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2867 include_soap_action=False,
2868 soap_action_override=act)
2869 if resp.status != 401:
2870 raise Exception("Unexpected HTTP response: %d" % resp.status)
2871
2872 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2873 if resp.status != 200:
2874 raise Exception("Unexpected HTTP response: %d" % resp.status)
2875 dev = resp.read()
2876 if "NewDeviceInfo" not in dev:
2877 raise Exception("Unexpected GetDeviceInfo response")
2878
2879 logger.debug("PutMessage without required parameters")
2880 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2881 if resp.status != 600:
2882 raise Exception("Unexpected HTTP response: %d" % resp.status)
2883
2884 logger.debug("PutWLANResponse without required parameters")
2885 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2886 if resp.status != 600:
2887 raise Exception("Unexpected HTTP response: %d" % resp.status)
2888
2889 logger.debug("SetSelectedRegistrar from unregistered ER")
2890 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2891 if resp.status != 501:
2892 raise Exception("Unexpected HTTP response: %d" % resp.status)
2893
2894 logger.debug("Unknown action")
2895 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2896 if resp.status != 401:
2897 raise Exception("Unexpected HTTP response: %d" % resp.status)
2898
2899 def test_ap_wps_upnp_subscribe(dev, apdev):
2900 """WPS AP and UPnP event subscription"""
2901 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2902 hapd = add_ssdp_ap(apdev[0], ap_uuid)
2903
2904 location = ssdp_get_location(ap_uuid)
2905 urls = upnp_get_urls(location)
2906 eventurl = urlparse(urls['event_sub_url'])
2907
2908 url = urlparse(location)
2909 conn = HTTPConnection(url.netloc)
2910 #conn.set_debuglevel(1)
2911 headers = { "callback": '<http://127.0.0.1:12345/event>',
2912 "timeout": "Second-1234" }
2913 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2914 resp = conn.getresponse()
2915 if resp.status != 412:
2916 raise Exception("Unexpected HTTP response: %d" % resp.status)
2917
2918 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2919 resp = conn.getresponse()
2920 if resp.status != 412:
2921 raise Exception("Unexpected HTTP response: %d" % resp.status)
2922
2923 headers = { "NT": "upnp:event",
2924 "timeout": "Second-1234" }
2925 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2926 resp = conn.getresponse()
2927 if resp.status != 412:
2928 raise Exception("Unexpected HTTP response: %d" % resp.status)
2929
2930 headers = { "callback": '<http://127.0.0.1:12345/event>',
2931 "NT": "upnp:foobar",
2932 "timeout": "Second-1234" }
2933 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2934 resp = conn.getresponse()
2935 if resp.status != 400:
2936 raise Exception("Unexpected HTTP response: %d" % resp.status)
2937
2938 logger.debug("Valid subscription")
2939 headers = { "callback": '<http://127.0.0.1:12345/event>',
2940 "NT": "upnp:event",
2941 "timeout": "Second-1234" }
2942 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2943 resp = conn.getresponse()
2944 if resp.status != 200:
2945 raise Exception("Unexpected HTTP response: %d" % resp.status)
2946 sid = resp.getheader("sid")
2947 logger.debug("Subscription SID " + sid)
2948
2949 logger.debug("Invalid re-subscription")
2950 headers = { "NT": "upnp:event",
2951 "sid": "123456734567854",
2952 "timeout": "Second-1234" }
2953 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2954 resp = conn.getresponse()
2955 if resp.status != 400:
2956 raise Exception("Unexpected HTTP response: %d" % resp.status)
2957
2958 logger.debug("Invalid re-subscription")
2959 headers = { "NT": "upnp:event",
2960 "sid": "uuid:123456734567854",
2961 "timeout": "Second-1234" }
2962 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2963 resp = conn.getresponse()
2964 if resp.status != 400:
2965 raise Exception("Unexpected HTTP response: %d" % resp.status)
2966
2967 logger.debug("Invalid re-subscription")
2968 headers = { "callback": '<http://127.0.0.1:12345/event>',
2969 "NT": "upnp:event",
2970 "sid": sid,
2971 "timeout": "Second-1234" }
2972 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2973 resp = conn.getresponse()
2974 if resp.status != 400:
2975 raise Exception("Unexpected HTTP response: %d" % resp.status)
2976
2977 logger.debug("SID mismatch in re-subscription")
2978 headers = { "NT": "upnp:event",
2979 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
2980 "timeout": "Second-1234" }
2981 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2982 resp = conn.getresponse()
2983 if resp.status != 412:
2984 raise Exception("Unexpected HTTP response: %d" % resp.status)
2985
2986 logger.debug("Valid re-subscription")
2987 headers = { "NT": "upnp:event",
2988 "sid": sid,
2989 "timeout": "Second-1234" }
2990 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2991 resp = conn.getresponse()
2992 if resp.status != 200:
2993 raise Exception("Unexpected HTTP response: %d" % resp.status)
2994 sid2 = resp.getheader("sid")
2995 logger.debug("Subscription SID " + sid2)
2996
2997 if sid != sid2:
2998 raise Exception("Unexpected SID change")
2999
3000 logger.debug("Valid re-subscription")
3001 headers = { "NT": "upnp:event",
3002 "sid": "uuid: \t \t" + sid.split(':')[1],
3003 "timeout": "Second-1234" }
3004 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3005 resp = conn.getresponse()
3006 if resp.status != 200:
3007 raise Exception("Unexpected HTTP response: %d" % resp.status)
3008
3009 logger.debug("Invalid unsubscription")
3010 headers = { "sid": sid }
3011 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
3012 resp = conn.getresponse()
3013 if resp.status != 412:
3014 raise Exception("Unexpected HTTP response: %d" % resp.status)
3015 headers = { "foo": "bar" }
3016 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3017 resp = conn.getresponse()
3018 if resp.status != 412:
3019 raise Exception("Unexpected HTTP response: %d" % resp.status)
3020
3021 logger.debug("Valid unsubscription")
3022 headers = { "sid": sid }
3023 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3024 resp = conn.getresponse()
3025 if resp.status != 200:
3026 raise Exception("Unexpected HTTP response: %d" % resp.status)
3027
3028 logger.debug("Unsubscription for not existing SID")
3029 headers = { "sid": sid }
3030 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3031 resp = conn.getresponse()
3032 if resp.status != 412:
3033 raise Exception("Unexpected HTTP response: %d" % resp.status)
3034
3035 logger.debug("Invalid unsubscription")
3036 headers = { "sid": " \t \tfoo" }
3037 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3038 resp = conn.getresponse()
3039 if resp.status != 400:
3040 raise Exception("Unexpected HTTP response: %d" % resp.status)
3041
3042 logger.debug("Invalid unsubscription")
3043 headers = { "sid": "uuid:\t \tfoo" }
3044 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3045 resp = conn.getresponse()
3046 if resp.status != 400:
3047 raise Exception("Unexpected HTTP response: %d" % resp.status)
3048
3049 logger.debug("Invalid unsubscription")
3050 headers = { "NT": "upnp:event",
3051 "sid": sid }
3052 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3053 resp = conn.getresponse()
3054 if resp.status != 400:
3055 raise Exception("Unexpected HTTP response: %d" % resp.status)
3056 headers = { "callback": '<http://127.0.0.1:12345/event>',
3057 "sid": sid }
3058 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3059 resp = conn.getresponse()
3060 if resp.status != 400:
3061 raise Exception("Unexpected HTTP response: %d" % resp.status)
3062
3063 logger.debug("Valid subscription with multiple callbacks")
3064 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>',
3065 "NT": "upnp:event",
3066 "timeout": "Second-1234" }
3067 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3068 resp = conn.getresponse()
3069 if resp.status != 200:
3070 raise Exception("Unexpected HTTP response: %d" % resp.status)
3071 sid = resp.getheader("sid")
3072 logger.debug("Subscription SID " + sid)
3073
3074 # Force subscription to be deleted due to errors
3075 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3076 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3077 with alloc_fail(hapd, 1, "event_build_message"):
3078 for i in range(10):
3079 dev[1].dump_monitor()
3080 dev[2].dump_monitor()
3081 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3082 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3083 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3084 dev[1].request("WPS_CANCEL")
3085 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3086 dev[2].request("WPS_CANCEL")
3087 if i % 4 == 1:
3088 time.sleep(1)
3089 else:
3090 time.sleep(0.1)
3091 time.sleep(0.2)
3092
3093 headers = { "sid": sid }
3094 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3095 resp = conn.getresponse()
3096 if resp.status != 200 and resp.status != 412:
3097 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3098
3099 headers = { "callback": '<http://127.0.0.1:12345/event>',
3100 "NT": "upnp:event",
3101 "timeout": "Second-1234" }
3102 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3103 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3104 resp = conn.getresponse()
3105 if resp.status != 200:
3106 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3107 sid = resp.getheader("sid")
3108 logger.debug("Subscription SID " + sid)
3109
3110 headers = { "sid": sid }
3111 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3112 resp = conn.getresponse()
3113 if resp.status != 200:
3114 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3115
3116 headers = { "callback": '<http://127.0.0.1:12345/event>',
3117 "NT": "upnp:event",
3118 "timeout": "Second-1234" }
3119 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3120 resp = conn.getresponse()
3121 if resp.status != 200:
3122 raise Exception("Unexpected HTTP response: %d" % resp.status)
3123 sid = resp.getheader("sid")
3124 logger.debug("Subscription SID " + sid)
3125
3126 with alloc_fail(hapd, 1, "=event_add"):
3127 for i in range(2):
3128 dev[1].dump_monitor()
3129 dev[2].dump_monitor()
3130 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3131 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3132 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3133 dev[1].request("WPS_CANCEL")
3134 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3135 dev[2].request("WPS_CANCEL")
3136 if i == 0:
3137 time.sleep(1)
3138 else:
3139 time.sleep(0.1)
3140
3141 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3142 resp = conn.getresponse()
3143 if resp.status != 200:
3144 raise Exception("Unexpected HTTP response: %d" % resp.status)
3145
3146 with alloc_fail(hapd, 1, "wpabuf_dup;event_add"):
3147 dev[1].dump_monitor()
3148 dev[2].dump_monitor()
3149 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3150 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3151 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3152 dev[1].request("WPS_CANCEL")
3153 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3154 dev[2].request("WPS_CANCEL")
3155 time.sleep(0.1)
3156
3157 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3158 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3159 resp = conn.getresponse()
3160 if resp.status != 500:
3161 raise Exception("Unexpected HTTP response: %d" % resp.status)
3162
3163 with alloc_fail(hapd, 1, "=subscription_start"):
3164 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3165 resp = conn.getresponse()
3166 if resp.status != 500:
3167 raise Exception("Unexpected HTTP response: %d" % resp.status)
3168
3169 headers = { "callback": '',
3170 "NT": "upnp:event",
3171 "timeout": "Second-1234" }
3172 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3173 resp = conn.getresponse()
3174 if resp.status != 500:
3175 raise Exception("Unexpected HTTP response: %d" % resp.status)
3176
3177 headers = { "callback": ' <',
3178 "NT": "upnp:event",
3179 "timeout": "Second-1234" }
3180 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3181 resp = conn.getresponse()
3182 if resp.status != 500:
3183 raise Exception("Unexpected HTTP response: %d" % resp.status)
3184
3185 headers = { "callback": '<http://127.0.0.1:12345/event>',
3186 "NT": "upnp:event",
3187 "timeout": "Second-1234" }
3188 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3189 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3190 resp = conn.getresponse()
3191 if resp.status != 500:
3192 raise Exception("Unexpected HTTP response: %d" % resp.status)
3193
3194 with alloc_fail(hapd, 1, "event_add;subscription_first_event"):
3195 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3196 resp = conn.getresponse()
3197 if resp.status != 500:
3198 raise Exception("Unexpected HTTP response: %d" % resp.status)
3199
3200 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3201 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3202 resp = conn.getresponse()
3203 if resp.status != 500:
3204 raise Exception("Unexpected HTTP response: %d" % resp.status)
3205
3206 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3207 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3208 resp = conn.getresponse()
3209 if resp.status != 500:
3210 raise Exception("Unexpected HTTP response: %d" % resp.status)
3211
3212 for i in range(6):
3213 headers = { "callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3214 "NT": "upnp:event",
3215 "timeout": "Second-1234" }
3216 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3217 resp = conn.getresponse()
3218 if resp.status != 200:
3219 raise Exception("Unexpected HTTP response: %d" % resp.status)
3220
3221 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3222 dev[1].dump_monitor()
3223 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3224 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3225 dev[1].request("WPS_CANCEL")
3226 time.sleep(0.1)
3227
3228 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3229 dev[1].dump_monitor()
3230 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3231 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3232 dev[1].request("WPS_CANCEL")
3233 time.sleep(0.1)
3234
3235 with alloc_fail(hapd, 1,
3236 "base64_gen_encode;?base64_encode;upnp_wps_device_send_wlan_event"):
3237 dev[1].dump_monitor()
3238 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3239 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3240 dev[1].request("WPS_CANCEL")
3241 time.sleep(0.1)
3242
3243 hapd.disable()
3244 with alloc_fail(hapd, 1, "get_netif_info"):
3245 if "FAIL" not in hapd.request("ENABLE"):
3246 raise Exception("ENABLE succeeded during OOM")
3247
3248 def test_ap_wps_upnp_subscribe_events(dev, apdev):
3249 """WPS AP and UPnP event subscription and many events"""
3250 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3251 hapd = add_ssdp_ap(apdev[0], ap_uuid)
3252
3253 location = ssdp_get_location(ap_uuid)
3254 urls = upnp_get_urls(location)
3255 eventurl = urlparse(urls['event_sub_url'])
3256
3257 class WPSERHTTPServer(StreamRequestHandler):
3258 def handle(self):
3259 data = self.rfile.readline().strip()
3260 logger.debug(data)
3261 self.wfile.write(gen_wps_event())
3262
3263 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3264 server.timeout = 1
3265
3266 url = urlparse(location)
3267 conn = HTTPConnection(url.netloc)
3268
3269 headers = { "callback": '<http://127.0.0.1:12345/event>',
3270 "NT": "upnp:event",
3271 "timeout": "Second-1234" }
3272 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3273 resp = conn.getresponse()
3274 if resp.status != 200:
3275 raise Exception("Unexpected HTTP response: %d" % resp.status)
3276 sid = resp.getheader("sid")
3277 logger.debug("Subscription SID " + sid)
3278
3279 # Fetch the first event message
3280 server.handle_request()
3281
3282 # Force subscription event queue to reach the maximum length by generating
3283 # new proxied events without the ER fetching any of the pending events.
3284 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3285 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3286 for i in range(16):
3287 dev[1].dump_monitor()
3288 dev[2].dump_monitor()
3289 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3290 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3291 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3292 dev[1].request("WPS_CANCEL")
3293 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3294 dev[2].request("WPS_CANCEL")
3295 if i % 4 == 1:
3296 time.sleep(1)
3297 else:
3298 time.sleep(0.1)
3299
3300 hapd.request("WPS_PIN any 12345670")
3301 dev[1].dump_monitor()
3302 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3303 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3304 if ev is None:
3305 raise Exception("WPS success not reported")
3306
3307 # Close the WPS ER HTTP server without fetching all the pending events.
3308 # This tests hostapd code path that clears subscription and the remaining
3309 # event queue when the interface is deinitialized.
3310 server.handle_request()
3311 server.server_close()
3312
3313 dev[1].wait_connected()
3314
3315 def test_ap_wps_upnp_http_proto(dev, apdev):
3316 """WPS AP and UPnP/HTTP protocol testing"""
3317 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3318 add_ssdp_ap(apdev[0], ap_uuid)
3319
3320 location = ssdp_get_location(ap_uuid)
3321
3322 url = urlparse(location)
3323 conn = HTTPConnection(url.netloc, timeout=0.2)
3324 #conn.set_debuglevel(1)
3325
3326 conn.request("HEAD", "hello")
3327 resp = conn.getresponse()
3328 if resp.status != 501:
3329 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3330 conn.close()
3331
3332 for cmd in [ "PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST" ]:
3333 try:
3334 conn.request(cmd, "hello")
3335 resp = conn.getresponse()
3336 except Exception as e:
3337 pass
3338 conn.close()
3339
3340 headers = { "Content-Length": 'abc' }
3341 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3342 try:
3343 resp = conn.getresponse()
3344 except Exception as e:
3345 pass
3346 conn.close()
3347
3348 headers = { "Content-Length": '-10' }
3349 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3350 try:
3351 resp = conn.getresponse()
3352 except Exception as e:
3353 pass
3354 conn.close()
3355
3356 headers = { "Content-Length": '10000000000000' }
3357 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3358 try:
3359 resp = conn.getresponse()
3360 except Exception as e:
3361 pass
3362 conn.close()
3363
3364 headers = { "Transfer-Encoding": 'abc' }
3365 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3366 resp = conn.getresponse()
3367 if resp.status != 501:
3368 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3369 conn.close()
3370
3371 headers = { "Transfer-Encoding": 'chunked' }
3372 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3373 resp = conn.getresponse()
3374 if resp.status != 501:
3375 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3376 conn.close()
3377
3378 # Too long a header
3379 conn.request("HEAD", 5000 * 'A')
3380 try:
3381 resp = conn.getresponse()
3382 except Exception as e:
3383 pass
3384 conn.close()
3385
3386 # Long URL but within header length limits
3387 conn.request("HEAD", 3000 * 'A')
3388 resp = conn.getresponse()
3389 if resp.status != 501:
3390 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3391 conn.close()
3392
3393 headers = { "Content-Length": '20' }
3394 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3395 try:
3396 resp = conn.getresponse()
3397 except Exception as e:
3398 pass
3399 conn.close()
3400
3401 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3402 resp = conn.getresponse()
3403 if resp.status != 404:
3404 raise Exception("Unexpected HTTP response: %d" % resp.status)
3405 conn.close()
3406
3407 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3408 try:
3409 resp = conn.getresponse()
3410 except Exception as e:
3411 pass
3412 conn.close()
3413
3414 def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3415 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3416 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3417 add_ssdp_ap(apdev[0], ap_uuid)
3418
3419 location = ssdp_get_location(ap_uuid)
3420
3421 url = urlparse(location)
3422 conn = HTTPConnection(url.netloc)
3423 #conn.set_debuglevel(1)
3424
3425 headers = { "Transfer-Encoding": 'chunked' }
3426 conn.request("POST", "hello",
3427 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3428 headers)
3429 resp = conn.getresponse()
3430 if resp.status != 404:
3431 raise Exception("Unexpected HTTP response: %d" % resp.status)
3432 conn.close()
3433
3434 conn.putrequest("POST", "hello")
3435 conn.putheader('Transfer-Encoding', 'chunked')
3436 conn.endheaders()
3437 conn.send(b"a\r\nabcdefghij\r\n")
3438 time.sleep(0.1)
3439 conn.send(b"2\r\nkl\r\n")
3440 conn.send(b"0\r\n\r\n")
3441 resp = conn.getresponse()
3442 if resp.status != 404:
3443 raise Exception("Unexpected HTTP response: %d" % resp.status)
3444 conn.close()
3445
3446 conn.putrequest("POST", "hello")
3447 conn.putheader('Transfer-Encoding', 'chunked')
3448 conn.endheaders()
3449 completed = False
3450 try:
3451 for i in range(20000):
3452 conn.send(b"1\r\nZ\r\n")
3453 conn.send(b"0\r\n\r\n")
3454 resp = conn.getresponse()
3455 completed = True
3456 except Exception as e:
3457 pass
3458 conn.close()
3459 if completed:
3460 raise Exception("Too long chunked request did not result in connection reset")
3461
3462 headers = { "Transfer-Encoding": 'chunked' }
3463 conn.request("POST", "hello", "80000000\r\na", headers)
3464 try:
3465 resp = conn.getresponse()
3466 except Exception as e:
3467 pass
3468 conn.close()
3469
3470 conn.request("POST", "hello", "10000000\r\na", headers)
3471 try:
3472 resp = conn.getresponse()
3473 except Exception as e:
3474 pass
3475 conn.close()
3476
3477 @remote_compatible
3478 def test_ap_wps_disabled(dev, apdev):
3479 """WPS operations while WPS is disabled"""
3480 ssid = "test-wps-disabled"
3481 hapd = hostapd.add_ap(apdev[0], { "ssid": ssid })
3482 if "FAIL" not in hapd.request("WPS_PBC"):
3483 raise Exception("WPS_PBC succeeded unexpectedly")
3484 if "FAIL" not in hapd.request("WPS_CANCEL"):
3485 raise Exception("WPS_CANCEL succeeded unexpectedly")
3486
3487 def test_ap_wps_mixed_cred(dev, apdev):
3488 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3489 ssid = "test-wps-wep"
3490 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3491 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred" }
3492 hapd = hostapd.add_ap(apdev[0], params)
3493 hapd.request("WPS_PBC")
3494 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3495 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3496 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
3497 if ev is None:
3498 raise Exception("WPS-SUCCESS event timed out")
3499 nets = dev[0].list_networks()
3500 if len(nets) != 1:
3501 raise Exception("Unexpected number of network blocks")
3502 id = nets[0]['id']
3503 proto = dev[0].get_network(id, "proto")
3504 if proto != "WPA RSN":
3505 raise Exception("Unexpected merged proto field value: " + proto)
3506 pairwise = dev[0].get_network(id, "pairwise")
3507 p = pairwise.split()
3508 if "CCMP" not in p or "TKIP" not in p:
3509 raise Exception("Unexpected merged pairwise field value: " + pairwise)
3510
3511 @remote_compatible
3512 def test_ap_wps_while_connected(dev, apdev):
3513 """WPS PBC provisioning while connected to another AP"""
3514 ssid = "test-wps-conf"
3515 hapd = hostapd.add_ap(apdev[0],
3516 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3517 "wpa_passphrase": "12345678", "wpa": "2",
3518 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3519
3520 hostapd.add_ap(apdev[1], { "ssid": "open" })
3521 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3522
3523 logger.info("WPS provisioning step")
3524 hapd.request("WPS_PBC")
3525 dev[0].dump_monitor()
3526 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3527 dev[0].wait_connected(timeout=30)
3528 status = dev[0].get_status()
3529 if status['bssid'] != apdev[0]['bssid']:
3530 raise Exception("Unexpected BSSID")
3531
3532 @remote_compatible
3533 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3534 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3535 ssid = "test-wps-conf"
3536 hapd = hostapd.add_ap(apdev[0],
3537 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3538 "wpa_passphrase": "12345678", "wpa": "2",
3539 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3540
3541 hostapd.add_ap(apdev[1], { "ssid": "open" })
3542
3543 try:
3544 dev[0].request("STA_AUTOCONNECT 0")
3545 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3546
3547 logger.info("WPS provisioning step")
3548 hapd.request("WPS_PBC")
3549 dev[0].dump_monitor()
3550 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3551 dev[0].wait_connected(timeout=30)
3552 status = dev[0].get_status()
3553 if status['bssid'] != apdev[0]['bssid']:
3554 raise Exception("Unexpected BSSID")
3555 finally:
3556 dev[0].request("STA_AUTOCONNECT 1")
3557
3558 @remote_compatible
3559 def test_ap_wps_from_event(dev, apdev):
3560 """WPS PBC event on AP to enable PBC"""
3561 ssid = "test-wps-conf"
3562 hapd = hostapd.add_ap(apdev[0],
3563 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3564 "wpa_passphrase": "12345678", "wpa": "2",
3565 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3566 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3567 dev[0].dump_monitor()
3568 hapd.dump_monitor()
3569 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3570
3571 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3572 if ev is None:
3573 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3574 vals = ev.split(' ')
3575 if vals[1] != dev[0].p2p_interface_addr():
3576 raise Exception("Unexpected enrollee address: " + vals[1])
3577 if vals[5] != '4':
3578 raise Exception("Unexpected Device Password Id: " + vals[5])
3579 hapd.request("WPS_PBC")
3580 dev[0].wait_connected(timeout=30)
3581
3582 def test_ap_wps_ap_scan_2(dev, apdev):
3583 """AP_SCAN 2 for WPS"""
3584 ssid = "test-wps-conf"
3585 hapd = hostapd.add_ap(apdev[0],
3586 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3587 "wpa_passphrase": "12345678", "wpa": "2",
3588 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3589 hapd.request("WPS_PBC")
3590
3591 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3592 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
3593 wpas.dump_monitor()
3594
3595 if "OK" not in wpas.request("AP_SCAN 2"):
3596 raise Exception("Failed to set AP_SCAN 2")
3597
3598 wpas.flush_scan_cache()
3599 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
3600 wpas.dump_monitor()
3601 wpas.request("WPS_PBC " + apdev[0]['bssid'])
3602 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3603 if ev is None:
3604 raise Exception("WPS-SUCCESS event timed out")
3605 wpas.wait_connected(timeout=30)
3606 wpas.dump_monitor()
3607 wpas.request("DISCONNECT")
3608 wpas.wait_disconnected()
3609 id = wpas.list_networks()[0]['id']
3610 pairwise = wpas.get_network(id, "pairwise")
3611 if "CCMP" not in pairwise.split():
3612 raise Exception("Unexpected pairwise parameter value: " + pairwise)
3613 group = wpas.get_network(id, "group")
3614 if "CCMP" not in group.split():
3615 raise Exception("Unexpected group parameter value: " + group)
3616 # Need to select a single cipher for ap_scan=2 testing
3617 wpas.set_network(id, "pairwise", "CCMP")
3618 wpas.set_network(id, "group", "CCMP")
3619 wpas.request("BSS_FLUSH 0")
3620 wpas.dump_monitor()
3621 wpas.request("REASSOCIATE")
3622 wpas.wait_connected(timeout=30)
3623 wpas.dump_monitor()
3624
3625 @remote_compatible
3626 def test_ap_wps_eapol_workaround(dev, apdev):
3627 """EAPOL workaround code path for 802.1X header length mismatch"""
3628 ssid = "test-wps"
3629 hapd = hostapd.add_ap(apdev[0],
3630 { "ssid": ssid, "eap_server": "1", "wps_state": "1" })
3631 bssid = apdev[0]['bssid']
3632 hapd.request("SET ext_eapol_frame_io 1")
3633 dev[0].request("SET ext_eapol_frame_io 1")
3634 hapd.request("WPS_PBC")
3635 dev[0].request("WPS_PBC")
3636
3637 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3638 if ev is None:
3639 raise Exception("Timeout on EAPOL-TX from hostapd")
3640
3641 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3642 if "OK" not in res:
3643 raise Exception("EAPOL_RX to wpa_supplicant failed")
3644
3645 def test_ap_wps_iteration(dev, apdev):
3646 """WPS PIN and iterate through APs without selected registrar"""
3647 ssid = "test-wps-conf"
3648 hapd = hostapd.add_ap(apdev[0],
3649 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3650 "wpa_passphrase": "12345678", "wpa": "2",
3651 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3652
3653 ssid2 = "test-wps-conf2"
3654 hapd2 = hostapd.add_ap(apdev[1],
3655 { "ssid": ssid2, "eap_server": "1", "wps_state": "2",
3656 "wpa_passphrase": "12345678", "wpa": "2",
3657 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3658
3659 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3660 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3661 dev[0].dump_monitor()
3662 pin = dev[0].request("WPS_PIN any")
3663
3664 # Wait for iteration through all WPS APs to happen before enabling any
3665 # Registrar.
3666 for i in range(2):
3667 ev = dev[0].wait_event(["Associated with"], timeout=30)
3668 if ev is None:
3669 raise Exception("No association seen")
3670 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3671 if ev is None:
3672 raise Exception("No M2D from AP")
3673 dev[0].wait_disconnected()
3674
3675 # Verify that each AP requested PIN
3676 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3677 if ev is None:
3678 raise Exception("No WPS-PIN-NEEDED event from AP")
3679 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3680 if ev is None:
3681 raise Exception("No WPS-PIN-NEEDED event from AP2")
3682
3683 # Provide PIN to one of the APs and verify that connection gets formed
3684 hapd.request("WPS_PIN any " + pin)
3685 dev[0].wait_connected(timeout=30)
3686
3687 def test_ap_wps_iteration_error(dev, apdev):
3688 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3689 ssid = "test-wps-conf-pin"
3690 hapd = hostapd.add_ap(apdev[0],
3691 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3692 "wpa_passphrase": "12345678", "wpa": "2",
3693 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3694 "wps_independent": "1" })
3695 hapd.request("SET ext_eapol_frame_io 1")
3696 bssid = apdev[0]['bssid']
3697 pin = dev[0].wps_read_pin()
3698 dev[0].request("WPS_PIN any " + pin)
3699
3700 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3701 if ev is None:
3702 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3703 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3704
3705 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3706 if ev is None:
3707 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3708 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3709 if ev is None:
3710 raise Exception("No CTRL-EVENT-EAP-STARTED")
3711
3712 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3713 # a case with an incorrectly behaving WPS AP.
3714
3715 # Start the real target AP and activate registrar on it.
3716 hapd2 = hostapd.add_ap(apdev[1],
3717 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3718 "wpa_passphrase": "12345678", "wpa": "2",
3719 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3720 "wps_independent": "1" })
3721 hapd2.request("WPS_PIN any " + pin)
3722
3723 dev[0].wait_disconnected(timeout=15)
3724 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3725 if ev is None:
3726 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3727 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3728 if ev is None:
3729 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3730 dev[0].wait_connected(timeout=15)
3731
3732 @remote_compatible
3733 def test_ap_wps_priority(dev, apdev):
3734 """WPS PIN provisioning with configured AP and wps_priority"""
3735 ssid = "test-wps-conf-pin"
3736 hapd = hostapd.add_ap(apdev[0],
3737 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3738 "wpa_passphrase": "12345678", "wpa": "2",
3739 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3740 logger.info("WPS provisioning step")
3741 pin = dev[0].wps_read_pin()
3742 hapd.request("WPS_PIN any " + pin)
3743 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3744 dev[0].dump_monitor()
3745 try:
3746 dev[0].request("SET wps_priority 6")
3747 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3748 dev[0].wait_connected(timeout=30)
3749 netw = dev[0].list_networks()
3750 prio = dev[0].get_network(netw[0]['id'], 'priority')
3751 if prio != '6':
3752 raise Exception("Unexpected network priority: " + prio)
3753 finally:
3754 dev[0].request("SET wps_priority 0")
3755
3756 @remote_compatible
3757 def test_ap_wps_and_non_wps(dev, apdev):
3758 """WPS and non-WPS AP in single hostapd process"""
3759 params = { "ssid": "wps", "eap_server": "1", "wps_state": "1" }
3760 hapd = hostapd.add_ap(apdev[0], params)
3761
3762 params = { "ssid": "no wps" }
3763 hapd2 = hostapd.add_ap(apdev[1], params)
3764
3765 appin = hapd.request("WPS_AP_PIN random")
3766 if "FAIL" in appin:
3767 raise Exception("Could not generate random AP PIN")
3768 if appin not in hapd.request("WPS_AP_PIN get"):
3769 raise Exception("Could not fetch current AP PIN")
3770
3771 if "FAIL" in hapd.request("WPS_PBC"):
3772 raise Exception("WPS_PBC failed")
3773 if "FAIL" in hapd.request("WPS_CANCEL"):
3774 raise Exception("WPS_CANCEL failed")
3775
3776 def test_ap_wps_init_oom(dev, apdev):
3777 """Initial AP configuration and OOM during PSK generation"""
3778 ssid = "test-wps"
3779 params = { "ssid": ssid, "eap_server": "1", "wps_state": "1" }
3780 hapd = hostapd.add_ap(apdev[0], params)
3781
3782 with alloc_fail(hapd, 1, "base64_gen_encode;?base64_encode;wps_build_cred"):
3783 pin = dev[0].wps_read_pin()
3784 hapd.request("WPS_PIN any " + pin)
3785 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3786 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3787 dev[0].wait_disconnected()
3788
3789 hapd.request("WPS_PIN any " + pin)
3790 dev[0].wait_connected(timeout=30)
3791
3792 @remote_compatible
3793 def test_ap_wps_er_oom(dev, apdev):
3794 """WPS ER OOM in XML processing"""
3795 try:
3796 _test_ap_wps_er_oom(dev, apdev)
3797 finally:
3798 dev[0].request("WPS_ER_STOP")
3799 dev[1].request("WPS_CANCEL")
3800 dev[0].request("DISCONNECT")
3801
3802 def _test_ap_wps_er_oom(dev, apdev):
3803 ssid = "wps-er-ap-config"
3804 ap_pin = "12345670"
3805 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3806 hostapd.add_ap(apdev[0],
3807 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3808 "wpa_passphrase": "12345678", "wpa": "2",
3809 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3810 "device_name": "Wireless AP", "manufacturer": "Company",
3811 "model_name": "WAP", "model_number": "123",
3812 "serial_number": "12345", "device_type": "6-0050F204-1",
3813 "os_version": "01020300",
3814 "config_methods": "label push_button",
3815 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3816
3817 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3818
3819 with alloc_fail(dev[0], 1,
3820 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
3821 dev[0].request("WPS_ER_START ifname=lo")
3822 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3823 if ev is not None:
3824 raise Exception("Unexpected AP discovery")
3825
3826 dev[0].request("WPS_ER_STOP")
3827 dev[0].request("WPS_ER_START ifname=lo")
3828 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3829 if ev is None:
3830 raise Exception("AP discovery timed out")
3831
3832 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3833 with alloc_fail(dev[0], 1,
3834 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
3835 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3836 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3837 if ev is None:
3838 raise Exception("PBC scan failed")
3839 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3840 if ev is None:
3841 raise Exception("Enrollee discovery timed out")
3842
3843 @remote_compatible
3844 def test_ap_wps_er_init_oom(dev, apdev):
3845 """WPS ER and OOM during init"""
3846 try:
3847 _test_ap_wps_er_init_oom(dev, apdev)
3848 finally:
3849 dev[0].request("WPS_ER_STOP")
3850
3851 def _test_ap_wps_er_init_oom(dev, apdev):
3852 with alloc_fail(dev[0], 1, "wps_er_init"):
3853 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3854 raise Exception("WPS_ER_START succeeded during OOM")
3855 with alloc_fail(dev[0], 1, "http_server_init"):
3856 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3857 raise Exception("WPS_ER_START succeeded during OOM")
3858 with alloc_fail(dev[0], 2, "http_server_init"):
3859 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3860 raise Exception("WPS_ER_START succeeded during OOM")
3861 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
3862 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3863 raise Exception("WPS_ER_START succeeded during OOM")
3864 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3865 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3866 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3867
3868 @remote_compatible
3869 def test_ap_wps_er_init_fail(dev, apdev):
3870 """WPS ER init failure"""
3871 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3872 dev[0].request("WPS_ER_STOP")
3873 raise Exception("WPS_ER_START with non-existing ifname succeeded")
3874
3875 def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3876 """WPS events and wpa_cli action script"""
3877 logdir = os.path.abspath(test_params['logdir'])
3878 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3879 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3880 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
3881
3882 with open(actionfile, 'w') as f:
3883 f.write('#!/bin/sh\n')
3884 f.write('echo $* >> %s\n' % logfile)
3885 # Kill the process and wait some time before returning to allow all the
3886 # pending events to be processed with some of this happening after the
3887 # eloop SIGALRM signal has been scheduled.
3888 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3889
3890 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3891 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
3892
3893 ssid = "test-wps-conf"
3894 hapd = hostapd.add_ap(apdev[0],
3895 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
3896 "wpa_passphrase": "12345678", "wpa": "2",
3897 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3898
3899 prg = os.path.join(test_params['logdir'],
3900 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3901 if not os.path.exists(prg):
3902 prg = '../../wpa_supplicant/wpa_cli'
3903 arg = [ prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile ]
3904 subprocess.call(arg)
3905
3906 arg = [ 'ps', 'ax' ]
3907 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3908 out = cmd.communicate()[0].decode()
3909 cmd.wait()
3910 logger.debug("Processes:\n" + out)
3911 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3912 raise Exception("Did not see wpa_cli running")
3913
3914 hapd.request("WPS_PIN any 12345670")
3915 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3916 dev[0].dump_monitor()
3917 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3918 dev[0].wait_connected(timeout=30)
3919
3920 for i in range(30):
3921 if not os.path.exists(pidfile):
3922 break
3923 time.sleep(0.1)
3924
3925 if not os.path.exists(logfile):
3926 raise Exception("wpa_cli action results file not found")
3927 with open(logfile, 'r') as f:
3928 res = f.read()
3929 if "WPS-SUCCESS" not in res:
3930 raise Exception("WPS-SUCCESS event not seen in action file")
3931
3932 arg = [ 'ps', 'ax' ]
3933 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3934 out = cmd.communicate()[0].decode()
3935 cmd.wait()
3936 logger.debug("Remaining processes:\n" + out)
3937 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3938 raise Exception("wpa_cli still running")
3939
3940 if os.path.exists(pidfile):
3941 raise Exception("PID file not removed")
3942
3943 def test_ap_wps_er_ssdp_proto(dev, apdev):
3944 """WPS ER SSDP protocol testing"""
3945 try:
3946 _test_ap_wps_er_ssdp_proto(dev, apdev)
3947 finally:
3948 dev[0].request("WPS_ER_STOP")
3949
3950 def _test_ap_wps_er_ssdp_proto(dev, apdev):
3951 socket.setdefaulttimeout(1)
3952 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3953 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3954 sock.bind(("239.255.255.250", 1900))
3955 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3956 raise Exception("Invalid filter accepted")
3957 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3958 raise Exception("WPS_ER_START with filter failed")
3959 (msg,addr) = sock.recvfrom(1000)
3960 msg = msg.decode()
3961 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3962 if "M-SEARCH" not in msg:
3963 raise Exception("Not an M-SEARCH")
3964 sock.sendto(b"FOO", addr)
3965 time.sleep(0.1)
3966 dev[0].request("WPS_ER_STOP")
3967
3968 dev[0].request("WPS_ER_START ifname=lo")
3969 (msg,addr) = sock.recvfrom(1000)
3970 msg = msg.decode()
3971 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3972 if "M-SEARCH" not in msg:
3973 raise Exception("Not an M-SEARCH")
3974 sock.sendto(b"FOO", addr)
3975 sock.sendto(b"HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
3976 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
3977 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3978 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
3979 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
3980 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
3981 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
3982 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
3983 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
3984 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
3985 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
3986 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nNTS:ssdp:byebye\r\n\r\n", addr)
3987 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\nlocation:foo\r\n\r\n", addr)
3988 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
3989 sock.sendto(b"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)
3990 time.sleep(0.1)
3991 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
3992 sock.sendto(b"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)
3993 time.sleep(0.1)
3994
3995 # Add an AP with bogus URL
3996 sock.sendto(b"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)
3997 # Update timeout on AP without updating URL
3998 sock.sendto(b"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)
3999 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4000 if ev is None:
4001 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4002
4003 # Add an AP with a valid URL (but no server listing to it)
4004 sock.sendto(b"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)
4005 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4006 if ev is None:
4007 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4008
4009 sock.close()
4010
4011 wps_event_url = None
4012
4013 def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
4014 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4015 payload = '''<?xml version="1.0"?>
4016 <root xmlns="urn:schemas-upnp-org:device-1-0">
4017 <specVersion>
4018 <major>1</major>
4019 <minor>0</minor>
4020 </specVersion>
4021 <device>
4022 <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
4023 <friendlyName>WPS Access Point</friendlyName>
4024 <manufacturer>Company</manufacturer>
4025 <modelName>WAP</modelName>
4026 <modelNumber>123</modelNumber>
4027 <serialNumber>12345</serialNumber>
4028 '''
4029 if udn:
4030 payload += '<UDN>' + udn + '</UDN>'
4031 payload += '''<serviceList>
4032 <service>
4033 <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
4034 <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
4035 <SCPDURL>wps_scpd.xml</SCPDURL>
4036 '''
4037 if controlURL:
4038 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4039 if eventSubURL:
4040 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4041 payload += '''</service>
4042 </serviceList>
4043 </device>
4044 </root>
4045 '''
4046 hdr = 'HTTP/1.1 200 OK\r\n' + \
4047 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4048 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4049 'Connection: close\r\n' + \
4050 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4051 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4052 return (hdr + payload).encode()
4053
4054 def gen_wps_control(payload_override=None):
4055 payload = '''<?xml version="1.0"?>
4056 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4057 <s:Body>
4058 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4059 <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
4060 Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
4061 +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
4062 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
4063 KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
4064 AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
4065 AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
4066 AAYANyoAASA=
4067 </NewDeviceInfo>
4068 </u:GetDeviceInfoResponse>
4069 </s:Body>
4070 </s:Envelope>
4071 '''
4072 if payload_override:
4073 payload = payload_override
4074 hdr = 'HTTP/1.1 200 OK\r\n' + \
4075 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4076 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4077 'Connection: close\r\n' + \
4078 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4079 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4080 return (hdr + payload).encode()
4081
4082 def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4083 payload = ""
4084 hdr = 'HTTP/1.1 200 OK\r\n' + \
4085 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4086 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4087 'Connection: close\r\n' + \
4088 'Content-Length: ' + str(len(payload)) + '\r\n'
4089 if sid:
4090 hdr += 'SID: ' + sid + '\r\n'
4091 hdr += 'Timeout: Second-1801\r\n' + \
4092 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4093 return (hdr + payload).encode()
4094
4095 class WPSAPHTTPServer(StreamRequestHandler):
4096 def handle(self):
4097 data = self.rfile.readline().strip()
4098 logger.info("HTTP server received: " + data)
4099 while True:
4100 hdr = self.rfile.readline().strip()
4101 if len(hdr) == 0:
4102 break
4103 logger.info("HTTP header: " + hdr)
4104 if "CALLBACK:" in hdr:
4105 global wps_event_url
4106 wps_event_url = hdr.split(' ')[1].strip('<>')
4107
4108 if "GET /foo.xml" in data:
4109 self.handle_upnp_info()
4110 elif "POST /wps_control" in data:
4111 self.handle_wps_control()
4112 elif "SUBSCRIBE /wps_event" in data:
4113 self.handle_wps_event()
4114 else:
4115 self.handle_others(data)
4116
4117 def handle_upnp_info(self):
4118 self.wfile.write(gen_upnp_info())
4119
4120 def handle_wps_control(self):
4121 self.wfile.write(gen_wps_control())
4122
4123 def handle_wps_event(self):
4124 self.wfile.write(gen_wps_event())
4125
4126 def handle_others(self, data):
4127 logger.info("Ignore HTTP request: " + data)
4128
4129 class MyTCPServer(TCPServer):
4130 def __init__(self, addr, handler):
4131 self.allow_reuse_address = True
4132 TCPServer.__init__(self, addr, handler)
4133
4134 def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4135 location_url=None):
4136 socket.setdefaulttimeout(1)
4137 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4138 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4139 sock.bind(("239.255.255.250", 1900))
4140 dev.request("WPS_ER_START ifname=lo")
4141 for i in range(100):
4142 (msg,addr) = sock.recvfrom(1000)
4143 msg = msg.decode()
4144 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4145 if "M-SEARCH" in msg:
4146 break
4147 if not wait_m_search:
4148 raise Exception("Not an M-SEARCH")
4149 if i == 99:
4150 raise Exception("No M-SEARCH seen")
4151
4152 # Add an AP with a valid URL and server listing to it
4153 server = MyTCPServer(("127.0.0.1", 12345), http_server)
4154 if not location_url:
4155 location_url = 'http://127.0.0.1:12345/foo.xml'
4156 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)).encode(), addr)
4157 server.timeout = 1
4158 return server,sock
4159
4160 def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4161 sock.close()
4162 server.server_close()
4163
4164 if on_alloc_fail:
4165 done = False
4166 for i in range(50):
4167 res = dev.request("GET_ALLOC_FAIL")
4168 if res.startswith("0:"):
4169 done = True
4170 break
4171 time.sleep(0.1)
4172 if not done:
4173 raise Exception("No allocation failure reported")
4174 else:
4175 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4176 if ev is None:
4177 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4178 dev.request("WPS_ER_STOP")
4179
4180 def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
4181 try:
4182 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
4183 server,sock = wps_er_start(dev, handler, location_url=location_url)
4184 global wps_event_url
4185 wps_event_url = None
4186 server.handle_request()
4187 server.handle_request()
4188 server.handle_request()
4189 server.server_close()
4190 if no_event_url:
4191 if wps_event_url:
4192 raise Exception("Received event URL unexpectedly")
4193 return
4194 if wps_event_url is None:
4195 raise Exception("Did not get event URL")
4196 logger.info("Event URL: " + wps_event_url)
4197 finally:
4198 dev.request("WPS_ER_STOP")
4199
4200 def send_wlanevent(url, uuid, data, no_response=False):
4201 conn = HTTPConnection(url.netloc)
4202 payload = '''<?xml version="1.0" encoding="utf-8"?>
4203 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4204 <e:property><STAStatus>1</STAStatus></e:property>
4205 <e:property><APStatus>1</APStatus></e:property>
4206 <e:property><WLANEvent>'''
4207 payload += base64.b64encode(data).decode()
4208 payload += '</WLANEvent></e:property></e:propertyset>'
4209 headers = { "Content-type": 'text/xml; charset="utf-8"',
4210 "Server": "Unspecified, UPnP/1.0, Unspecified",
4211 "HOST": url.netloc,
4212 "NT": "upnp:event",
4213 "SID": "uuid:" + uuid,
4214 "SEQ": "0",
4215 "Content-Length": str(len(payload)) }
4216 conn.request("NOTIFY", url.path, payload, headers)
4217 if no_response:
4218 try:
4219 conn.getresponse()
4220 except Exception as e:
4221 pass
4222 return
4223 resp = conn.getresponse()
4224 if resp.status != 200:
4225 raise Exception("Unexpected HTTP response: %d" % resp.status)
4226
4227 def test_ap_wps_er_http_proto(dev, apdev):
4228 """WPS ER HTTP protocol testing"""
4229 try:
4230 _test_ap_wps_er_http_proto(dev, apdev)
4231 finally:
4232 dev[0].request("WPS_ER_STOP")
4233
4234 def _test_ap_wps_er_http_proto(dev, apdev):
4235 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
4236 server,sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
4237 global wps_event_url
4238 wps_event_url = None
4239 server.handle_request()
4240 server.handle_request()
4241 server.handle_request()
4242 server.server_close()
4243 if wps_event_url is None:
4244 raise Exception("Did not get event URL")
4245 logger.info("Event URL: " + wps_event_url)
4246
4247 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4248 if ev is None:
4249 raise Exception("No WPS-ER-AP-ADD event")
4250 if uuid not in ev:
4251 raise Exception("UUID mismatch")
4252
4253 sock.close()
4254
4255 logger.info("Valid Probe Request notification")
4256 url = urlparse(wps_event_url)
4257 conn = HTTPConnection(url.netloc)
4258 payload = '''<?xml version="1.0" encoding="utf-8"?>
4259 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4260 <e:property><STAStatus>1</STAStatus></e:property>
4261 <e:property><APStatus>1</APStatus></e:property>
4262 <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4263 EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4264 RGV2aWNlIEEQSQAGADcqAAEg
4265 </WLANEvent></e:property>
4266 </e:propertyset>
4267 '''
4268 headers = { "Content-type": 'text/xml; charset="utf-8"',
4269 "Server": "Unspecified, UPnP/1.0, Unspecified",
4270 "HOST": url.netloc,
4271 "NT": "upnp:event",
4272 "SID": "uuid:" + uuid,
4273 "SEQ": "0",
4274 "Content-Length": str(len(payload)) }
4275 conn.request("NOTIFY", url.path, payload, headers)
4276 resp = conn.getresponse()
4277 if resp.status != 200:
4278 raise Exception("Unexpected HTTP response: %d" % resp.status)
4279
4280 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4281 if ev is None:
4282 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4283 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4284 raise Exception("No Enrollee UUID match")
4285
4286 logger.info("Incorrect event URL AP id")
4287 conn = HTTPConnection(url.netloc)
4288 conn.request("NOTIFY", url.path + '123', payload, headers)
4289 resp = conn.getresponse()
4290 if resp.status != 404:
4291 raise Exception("Unexpected HTTP response: %d" % resp.status)
4292
4293 logger.info("Missing AP id")
4294 conn = HTTPConnection(url.netloc)
4295 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4296 payload, headers)
4297 time.sleep(0.1)
4298
4299 logger.info("Incorrect event URL event id")
4300 conn = HTTPConnection(url.netloc)
4301 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4302 time.sleep(0.1)
4303
4304 logger.info("Incorrect event URL prefix")
4305 conn = HTTPConnection(url.netloc)
4306 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4307 resp = conn.getresponse()
4308 if resp.status != 404:
4309 raise Exception("Unexpected HTTP response: %d" % resp.status)
4310
4311 logger.info("Unsupported request")
4312 conn = HTTPConnection(url.netloc)
4313 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4314 resp = conn.getresponse()
4315 if resp.status != 501:
4316 raise Exception("Unexpected HTTP response: %d" % resp.status)
4317
4318 logger.info("Unsupported request and OOM")
4319 with alloc_fail(dev[0], 1, "wps_er_http_req"):
4320 conn = HTTPConnection(url.netloc)
4321 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4322 time.sleep(0.5)
4323
4324 logger.info("Too short WLANEvent")
4325 data = b'\x00'
4326 send_wlanevent(url, uuid, data)
4327
4328 logger.info("Invalid WLANEventMAC")
4329 data = b'\x00qwertyuiopasdfghjklzxcvbnm'
4330 send_wlanevent(url, uuid, data)
4331
4332 logger.info("Unknown WLANEventType")
4333 data = b'\xff02:00:00:00:00:00'
4334 send_wlanevent(url, uuid, data)
4335
4336 logger.info("Probe Request notification without any attributes")
4337 data = b'\x0102:00:00:00:00:00'
4338 send_wlanevent(url, uuid, data)
4339
4340 logger.info("Probe Request notification with invalid attribute")
4341 data = b'\x0102:00:00:00:00:00\xff'
4342 send_wlanevent(url, uuid, data)
4343
4344 logger.info("EAP message without any attributes")
4345 data = b'\x0202:00:00:00:00:00'
4346 send_wlanevent(url, uuid, data)
4347
4348 logger.info("EAP message with invalid attribute")
4349 data = b'\x0202:00:00:00:00:00\xff'
4350 send_wlanevent(url, uuid, data)
4351
4352 logger.info("EAP message from new STA and not M1")
4353 data = b'\x0202:ff:ff:ff:ff:ff' + b'\x10\x22\x00\x01\x05'
4354 send_wlanevent(url, uuid, data)
4355
4356 logger.info("EAP message: M1")
4357 data = b'\x0202:00:00:00:00:00'
4358 data += b'\x10\x22\x00\x01\x04'
4359 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4360 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4361 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4362 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4363 data += b'\x10\x04\x00\x02\x00\x00'
4364 data += b'\x10\x10\x00\x02\x00\x00'
4365 data += b'\x10\x0d\x00\x01\x00'
4366 data += b'\x10\x08\x00\x02\x00\x00'
4367 data += b'\x10\x44\x00\x01\x00'
4368 data += b'\x10\x21\x00\x00'
4369 data += b'\x10\x23\x00\x00'
4370 data += b'\x10\x24\x00\x00'
4371 data += b'\x10\x42\x00\x00'
4372 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4373 data += b'\x10\x11\x00\x00'
4374 data += b'\x10\x3c\x00\x01\x00'
4375 data += b'\x10\x02\x00\x02\x00\x00'
4376 data += b'\x10\x12\x00\x02\x00\x00'
4377 data += b'\x10\x09\x00\x02\x00\x00'
4378 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
4379 m1 = data
4380 send_wlanevent(url, uuid, data)
4381
4382 logger.info("EAP message: WSC_ACK")
4383 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0d'
4384 send_wlanevent(url, uuid, data)
4385
4386 logger.info("EAP message: M1")
4387 send_wlanevent(url, uuid, m1)
4388
4389 logger.info("EAP message: WSC_NACK")
4390 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0e'
4391 send_wlanevent(url, uuid, data)
4392
4393 logger.info("EAP message: M1 - Too long attribute values")
4394 data = b'\x0202:00:00:00:00:00'
4395 data += b'\x10\x11\x00\x21' + 33 * b'\x00'
4396 data += b'\x10\x45\x00\x21' + 33 * b'\x00'
4397 data += b'\x10\x42\x00\x21' + 33 * b'\x00'
4398 data += b'\x10\x24\x00\x21' + 33 * b'\x00'
4399 data += b'\x10\x23\x00\x21' + 33 * b'\x00'
4400 data += b'\x10\x21\x00\x41' + 65 * b'\x00'
4401 data += b'\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4402 send_wlanevent(url, uuid, data)
4403
4404 logger.info("EAP message: M1 missing UUID-E")
4405 data = b'\x0202:00:00:00:00:00'
4406 data += b'\x10\x22\x00\x01\x04'
4407 send_wlanevent(url, uuid, data)
4408
4409 logger.info("EAP message: M1 missing MAC Address")
4410 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4411 send_wlanevent(url, uuid, data)
4412
4413 logger.info("EAP message: M1 missing Enrollee Nonce")
4414 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4415 send_wlanevent(url, uuid, data)
4416
4417 logger.info("EAP message: M1 missing Public Key")
4418 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4419 send_wlanevent(url, uuid, data)
4420
4421 logger.info("EAP message: M1 missing Authentication Type flags")
4422 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4423 send_wlanevent(url, uuid, data)
4424
4425 logger.info("EAP message: M1 missing Encryption Type Flags")
4426 data += b'\x10\x04\x00\x02\x00\x00'
4427 send_wlanevent(url, uuid, data)
4428
4429 logger.info("EAP message: M1 missing Connection Type flags")
4430 data += b'\x10\x10\x00\x02\x00\x00'
4431 send_wlanevent(url, uuid, data)
4432
4433 logger.info("EAP message: M1 missing Config Methods")
4434 data += b'\x10\x0d\x00\x01\x00'
4435 send_wlanevent(url, uuid, data)
4436
4437 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4438 data += b'\x10\x08\x00\x02\x00\x00'
4439 send_wlanevent(url, uuid, data)
4440
4441 logger.info("EAP message: M1 missing Manufacturer")
4442 data += b'\x10\x44\x00\x01\x00'
4443 send_wlanevent(url, uuid, data)
4444
4445 logger.info("EAP message: M1 missing Model Name")
4446 data += b'\x10\x21\x00\x00'
4447 send_wlanevent(url, uuid, data)
4448
4449 logger.info("EAP message: M1 missing Model Number")
4450 data += b'\x10\x23\x00\x00'
4451 send_wlanevent(url, uuid, data)
4452
4453 logger.info("EAP message: M1 missing Serial Number")
4454 data += b'\x10\x24\x00\x00'
4455 send_wlanevent(url, uuid, data)
4456
4457 logger.info("EAP message: M1 missing Primary Device Type")
4458 data += b'\x10\x42\x00\x00'
4459 send_wlanevent(url, uuid, data)
4460
4461 logger.info("EAP message: M1 missing Device Name")
4462 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4463 send_wlanevent(url, uuid, data)
4464
4465 logger.info("EAP message: M1 missing RF Bands")
4466 data += b'\x10\x11\x00\x00'
4467 send_wlanevent(url, uuid, data)
4468
4469 logger.info("EAP message: M1 missing Association State")
4470 data += b'\x10\x3c\x00\x01\x00'
4471 send_wlanevent(url, uuid, data)
4472
4473 logger.info("EAP message: M1 missing Device Password ID")
4474 data += b'\x10\x02\x00\x02\x00\x00'
4475 send_wlanevent(url, uuid, data)
4476
4477 logger.info("EAP message: M1 missing Configuration Error")
4478 data += b'\x10\x12\x00\x02\x00\x00'
4479 send_wlanevent(url, uuid, data)
4480
4481 logger.info("EAP message: M1 missing OS Version")
4482 data += b'\x10\x09\x00\x02\x00\x00'
4483 send_wlanevent(url, uuid, data)
4484
4485 logger.info("Check max concurrent requests")
4486 addr = (url.hostname, url.port)
4487 socks = {}
4488 for i in range(20):
4489 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4490 socket.IPPROTO_TCP)
4491 socks[i].settimeout(10)
4492 socks[i].connect(addr)
4493 for i in range(20):
4494 socks[i].send(b"GET / HTTP/1.1\r\n\r\n")
4495 count = 0
4496 for i in range(20):
4497 try:
4498 res = socks[i].recv(100).decode()
4499 if "HTTP/1" in res:
4500 count += 1
4501 else:
4502 logger.info("recv[%d]: len=%d" % (i, len(res)))
4503 except:
4504 pass
4505 socks[i].close()
4506 logger.info("%d concurrent HTTP GET operations returned response" % count)
4507 if count < 8:
4508 raise Exception("Too few concurrent HTTP connections accepted")
4509
4510 logger.info("OOM in HTTP server")
4511 for func in [ "http_request_init", "httpread_create",
4512 "eloop_register_timeout;httpread_create",
4513 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
4514 "httpread_hdr_analyze" ]:
4515 with alloc_fail(dev[0], 1, func):
4516 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4517 socket.IPPROTO_TCP)
4518 sock.connect(addr)
4519 sock.send(b"GET / HTTP/1.1\r\n\r\n")
4520 try:
4521 sock.recv(100)
4522 except:
4523 pass
4524 sock.close()
4525
4526 logger.info("Invalid HTTP header")
4527 for req in [ " GET / HTTP/1.1\r\n\r\n",
4528 "HTTP/1.1 200 OK\r\n\r\n",
4529 "HTTP/\r\n\r\n",
4530 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4531 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4532 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4533 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4534 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4535 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4536 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4537 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra" ]:
4538 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4539 socket.IPPROTO_TCP)
4540 sock.settimeout(0.1)
4541 sock.connect(addr)
4542 sock.send(req.encode())
4543 try:
4544 sock.recv(100)
4545 except:
4546 pass
4547 sock.close()
4548
4549 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4550 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4551 socket.IPPROTO_TCP)
4552 sock.connect(addr)
4553 sock.send(b"NOTIFY / HTTP/1.1\r\n\r\n" + 4500 * b'a')
4554 try:
4555 sock.recv(100)
4556 except:
4557 pass
4558 sock.close()
4559
4560 conn = HTTPConnection(url.netloc)
4561 payload = '<foo'
4562 headers = { "Content-type": 'text/xml; charset="utf-8"',
4563 "Server": "Unspecified, UPnP/1.0, Unspecified",
4564 "HOST": url.netloc,
4565 "NT": "upnp:event",
4566 "SID": "uuid:" + uuid,
4567 "SEQ": "0",
4568 "Content-Length": str(len(payload)) }
4569 conn.request("NOTIFY", url.path, payload, headers)
4570 resp = conn.getresponse()
4571 if resp.status != 200:
4572 raise Exception("Unexpected HTTP response: %d" % resp.status)
4573
4574 conn = HTTPConnection(url.netloc)
4575 payload = '<WLANEvent foo></WLANEvent>'
4576 headers = { "Content-type": 'text/xml; charset="utf-8"',
4577 "Server": "Unspecified, UPnP/1.0, Unspecified",
4578 "HOST": url.netloc,
4579 "NT": "upnp:event",
4580 "SID": "uuid:" + uuid,
4581 "SEQ": "0",
4582 "Content-Length": str(len(payload)) }
4583 conn.request("NOTIFY", url.path, payload, headers)
4584 resp = conn.getresponse()
4585 if resp.status != 200:
4586 raise Exception("Unexpected HTTP response: %d" % resp.status)
4587
4588 with alloc_fail(dev[0], 1, "xml_get_first_item"):
4589 send_wlanevent(url, uuid, b'')
4590
4591 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4592 send_wlanevent(url, uuid, b'foo')
4593
4594 for func in [ "wps_init",
4595 "wps_process_manufacturer",
4596 "wps_process_model_name",
4597 "wps_process_model_number",
4598 "wps_process_serial_number",
4599 "wps_process_dev_name" ]:
4600 with alloc_fail(dev[0], 1, func):
4601 send_wlanevent(url, uuid, m1)
4602
4603 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4604 send_wlanevent(url, uuid, m1, no_response=True)
4605
4606 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4607 url2 = urlparse(wps_event_url.replace('/event/', '/notfound/'))
4608 send_wlanevent(url2, uuid, m1, no_response=True)
4609
4610 logger.info("EAP message: M1")
4611 data = b'\x0202:11:22:00:00:00'
4612 data += b'\x10\x22\x00\x01\x04'
4613 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4614 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4615 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4616 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4617 data += b'\x10\x04\x00\x02\x00\x00'
4618 data += b'\x10\x10\x00\x02\x00\x00'
4619 data += b'\x10\x0d\x00\x01\x00'
4620 data += b'\x10\x08\x00\x02\x00\x00'
4621 data += b'\x10\x44\x00\x01\x00'
4622 data += b'\x10\x21\x00\x00'
4623 data += b'\x10\x23\x00\x00'
4624 data += b'\x10\x24\x00\x00'
4625 data += b'\x10\x42\x00\x00'
4626 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4627 data += b'\x10\x11\x00\x00'
4628 data += b'\x10\x3c\x00\x01\x00'
4629 data += b'\x10\x02\x00\x02\x00\x00'
4630 data += b'\x10\x12\x00\x02\x00\x00'
4631 data += b'\x10\x09\x00\x02\x00\x00'
4632 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
4633 dev[0].dump_monitor()
4634 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4635 send_wlanevent(url, uuid, data)
4636 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4637 if ev is not None:
4638 raise Exception("Unexpected enrollee add event")
4639 send_wlanevent(url, uuid, data)
4640 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4641 if ev is None:
4642 raise Exception("Enrollee add event not seen")
4643
4644 with alloc_fail(dev[0], 1,
4645 "base64_gen_encode;?base64_encode;wps_er_soap_hdr"):
4646 send_wlanevent(url, uuid, data)
4647
4648 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4649 send_wlanevent(url, uuid, data)
4650
4651 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4652 send_wlanevent(url, uuid, data)
4653
4654 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4655 send_wlanevent(url, uuid, data)
4656
4657 def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4658 """WPS ER HTTP protocol testing - no eventSubURL"""
4659 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4660 def handle_upnp_info(self):
4661 self.wfile.write(gen_upnp_info(eventSubURL=None))
4662 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4663 no_event_url=True)
4664
4665 def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4666 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
4667 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4668 def handle_upnp_info(self):
4669 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4670 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4671 no_event_url=True)
4672
4673 def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4674 """WPS ER HTTP protocol testing - subscribe OOM"""
4675 try:
4676 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4677 finally:
4678 dev[0].request("WPS_ER_STOP")
4679
4680 def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4681 tests = [ (1, "http_client_url_parse"),
4682 (1, "wpabuf_alloc;wps_er_subscribe"),
4683 (1, "http_client_addr"),
4684 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4685 (1, "eloop_register_timeout;http_client_addr") ]
4686 for count,func in tests:
4687 with alloc_fail(dev[0], count, func):
4688 server,sock = wps_er_start(dev[0], WPSAPHTTPServer)
4689 server.handle_request()
4690 server.handle_request()
4691 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
4692
4693 def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4694 """WPS ER HTTP protocol testing - no SID"""
4695 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4696 def handle_wps_event(self):
4697 self.wfile.write(gen_wps_event(sid=None))
4698 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4699
4700 def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4701 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4702 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4703 def handle_wps_event(self):
4704 self.wfile.write(gen_wps_event(sid='FOO'))
4705 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4706
4707 def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4708 """WPS ER HTTP protocol testing - invalid SID UUID"""
4709 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4710 def handle_wps_event(self):
4711 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4712 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4713
4714 def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4715 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4716 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4717 def handle_wps_event(self):
4718 payload = ""
4719 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4720 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4721 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4722 'Connection: close\r\n' + \
4723 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4724 'Timeout: Second-1801\r\n' + \
4725 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4726 self.wfile.write((hdr + payload).encode())
4727 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4728
4729 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4730 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4731 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4732 def handle_wps_event(self):
4733 payload = ""
4734 hdr = 'HTTP/1.1 FOO\r\n' + \
4735 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4736 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4737 'Connection: close\r\n' + \
4738 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4739 'Timeout: Second-1801\r\n' + \
4740 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4741 self.wfile.write((hdr + payload).encode())
4742 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4743
4744 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4745 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4746 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4747 def handle_wps_control(self):
4748 payload = '''<?xml version="1.0"?>
4749 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4750 <s:Body>
4751 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4752 <NewDeviceInfo>Rk9P</NewDeviceInfo>
4753 </u:GetDeviceInfoResponse>
4754 </s:Body>
4755 </s:Envelope>
4756 '''
4757 self.wfile.write(gen_wps_control(payload_override=payload))
4758 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4759
4760 def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4761 """WPS ER HTTP protocol testing - No device in UPnP info"""
4762 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4763 def handle_upnp_info(self):
4764 payload = '''<?xml version="1.0"?>
4765 <root xmlns="urn:schemas-upnp-org:device-1-0">
4766 <specVersion>
4767 <major>1</major>
4768 <minor>0</minor>
4769 </specVersion>
4770 </root>
4771 '''
4772 hdr = 'HTTP/1.1 200 OK\r\n' + \
4773 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4774 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4775 'Connection: close\r\n' + \
4776 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4777 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4778 self.wfile.write((hdr + payload).encode())
4779 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4780
4781 def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4782 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4783 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4784 def handle_upnp_info(self):
4785 payload = '''<?xml version="1.0"?>
4786 <root xmlns="urn:schemas-upnp-org:device-1-0">
4787 <specVersion>
4788 <major>1</major>
4789 <minor>0</minor>
4790 </specVersion>
4791 <device>
4792 </device>
4793 </root>
4794 '''
4795 hdr = 'HTTP/1.1 200 OK\r\n' + \
4796 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4797 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4798 'Connection: close\r\n' + \
4799 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4800 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4801 self.wfile.write((hdr + payload).encode())
4802 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4803
4804 def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4805 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4806 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4807 def handle_upnp_info(self):
4808 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4809 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4810
4811 def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4812 """WPS ER HTTP protocol testing - no controlURL"""
4813 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4814 def handle_upnp_info(self):
4815 self.wfile.write(gen_upnp_info(controlURL=None))
4816 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4817 no_event_url=True)
4818
4819 def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4820 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4821 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4822 def handle_upnp_info(self):
4823 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4824 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4825 no_event_url=True)
4826
4827 def test_ap_wps_http_timeout(dev, apdev):
4828 """WPS AP/ER and HTTP timeout"""
4829 try:
4830 _test_ap_wps_http_timeout(dev, apdev)
4831 finally:
4832 dev[0].request("WPS_ER_STOP")
4833
4834 def _test_ap_wps_http_timeout(dev, apdev):
4835 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4836 add_ssdp_ap(apdev[0], ap_uuid)
4837
4838 location = ssdp_get_location(ap_uuid)
4839 url = urlparse(location)
4840 addr = (url.hostname, url.port)
4841 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4842 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4843 socket.IPPROTO_TCP)
4844 sock.connect(addr)
4845 sock.send(b"G")
4846
4847 class DummyServer(StreamRequestHandler):
4848 def handle(self):
4849 logger.debug("DummyServer - start 31 sec wait")
4850 time.sleep(31)
4851 logger.debug("DummyServer - wait done")
4852
4853 logger.debug("Start WPS ER")
4854 server,sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4855 wait_m_search=True)
4856
4857 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4858 # This will wait for 31 seconds..
4859 server.handle_request()
4860
4861 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4862 try:
4863 sock.send("ET / HTTP/1.1\r\n\r\n")
4864 res = sock.recv(100)
4865 sock.close()
4866 except:
4867 pass
4868
4869 def test_ap_wps_er_url_parse(dev, apdev):
4870 """WPS ER and URL parsing special cases"""
4871 try:
4872 _test_ap_wps_er_url_parse(dev, apdev)
4873 finally:
4874 dev[0].request("WPS_ER_STOP")
4875
4876 def _test_ap_wps_er_url_parse(dev, apdev):
4877 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4878 sock.settimeout(1)
4879 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4880 sock.bind(("239.255.255.250", 1900))
4881 dev[0].request("WPS_ER_START ifname=lo")
4882 (msg,addr) = sock.recvfrom(1000)
4883 msg = msg.decode()
4884 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4885 if "M-SEARCH" not in msg:
4886 raise Exception("Not an M-SEARCH")
4887 sock.sendto(b"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)
4888 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4889 sock.sendto(b"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)
4890 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4891 sock.sendto(b"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)
4892 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4893
4894 sock.close()
4895
4896 def test_ap_wps_er_link_update(dev, apdev):
4897 """WPS ER and link update special cases"""
4898 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4899 def handle_upnp_info(self):
4900 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4901 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4902
4903 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4904 def handle_others(self, data):
4905 if "GET / " in data:
4906 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4907 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4908 location_url='http://127.0.0.1:12345')
4909
4910 def test_ap_wps_er_http_client(dev, apdev):
4911 """WPS ER and HTTP client special cases"""
4912 with alloc_fail(dev[0], 1, "http_link_update"):
4913 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4914
4915 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4916 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4917
4918 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4919 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4920
4921 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4922 def handle_upnp_info(self):
4923 self.wfile.write(b"GET / HTTP/1.1\r\n\r\n")
4924 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4925 no_event_url=True)
4926
4927 def test_ap_wps_init_oom(dev, apdev):
4928 """wps_init OOM cases"""
4929 ssid = "test-wps"
4930 appin = "12345670"
4931 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
4932 "ap_pin": appin }
4933 hapd = hostapd.add_ap(apdev[0], params)
4934 pin = dev[0].wps_read_pin()
4935
4936 with alloc_fail(hapd, 1, "wps_init"):
4937 hapd.request("WPS_PIN any " + pin)
4938 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4939 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4940 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4941 if ev is None:
4942 raise Exception("No EAP failure reported")
4943 dev[0].request("WPS_CANCEL")
4944
4945 with alloc_fail(dev[0], 2, "wps_init"):
4946 hapd.request("WPS_PIN any " + pin)
4947 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4948 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4949 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4950 if ev is None:
4951 raise Exception("No EAP failure reported")
4952 dev[0].request("WPS_CANCEL")
4953
4954 with alloc_fail(dev[0], 2, "wps_init"):
4955 hapd.request("WPS_PBC")
4956 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4957 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4958 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4959 if ev is None:
4960 raise Exception("No EAP failure reported")
4961 dev[0].request("WPS_CANCEL")
4962
4963 dev[0].dump_monitor()
4964 new_ssid = "wps-new-ssid"
4965 new_passphrase = "1234567890"
4966 with alloc_fail(dev[0], 3, "wps_init"):
4967 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
4968 new_passphrase, no_wait=True)
4969 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4970 if ev is None:
4971 raise Exception("No EAP failure reported")
4972
4973 dev[0].flush_scan_cache()
4974
4975 @remote_compatible
4976 def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
4977 """WPS and invalid IE in Association Request frame"""
4978 ssid = "test-wps"
4979 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
4980 hapd = hostapd.add_ap(apdev[0], params)
4981 pin = "12345670"
4982 hapd.request("WPS_PIN any " + pin)
4983 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4984 try:
4985 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
4986 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4987 for i in range(5):
4988 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
4989 if ev and "vendor=14122" in ev:
4990 break
4991 if ev is None or "vendor=14122" not in ev:
4992 raise Exception("EAP-WSC not started")
4993 dev[0].request("WPS_CANCEL")
4994 finally:
4995 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
4996
4997 def test_ap_wps_pbc_pin_mismatch(dev, apdev):
4998 """WPS PBC/PIN mismatch"""
4999 ssid = "test-wps"
5000 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
5001 hapd = hostapd.add_ap(apdev[0], params)
5002 hapd.request("SET wps_version_number 0x10")
5003 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5004 hapd.request("WPS_PBC")
5005 pin = dev[0].wps_read_pin()
5006 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5007 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5008 if ev is None:
5009 raise Exception("Scan did not complete")
5010 dev[0].request("WPS_CANCEL")
5011
5012 hapd.request("WPS_CANCEL")
5013 dev[0].flush_scan_cache()
5014
5015 @remote_compatible
5016 def test_ap_wps_ie_invalid(dev, apdev):
5017 """WPS PIN attempt with AP that has invalid WSC IE"""
5018 ssid = "test-wps"
5019 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5020 "vendor_elements": "dd050050f20410" }
5021 hapd = hostapd.add_ap(apdev[0], params)
5022 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
5023 hostapd.add_ap(apdev[1], params)
5024 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5025 pin = dev[0].wps_read_pin()
5026 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5027 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5028 if ev is None:
5029 raise Exception("Scan did not complete")
5030 dev[0].request("WPS_CANCEL")
5031
5032 @remote_compatible
5033 def test_ap_wps_scan_prio_order(dev, apdev):
5034 """WPS scan priority ordering"""
5035 ssid = "test-wps"
5036 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
5037 hapd = hostapd.add_ap(apdev[0], params)
5038 params = { 'ssid': "another", "vendor_elements": "dd050050f20410" }
5039 hostapd.add_ap(apdev[1], params)
5040 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5041 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5042 pin = dev[0].wps_read_pin()
5043 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5044 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5045 if ev is None:
5046 raise Exception("Scan did not complete")
5047 dev[0].request("WPS_CANCEL")
5048
5049 def test_ap_wps_probe_req_ie_oom(dev, apdev):
5050 """WPS ProbeReq IE OOM"""
5051 ssid = "test-wps"
5052 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
5053 hapd = hostapd.add_ap(apdev[0], params)
5054 pin = dev[0].wps_read_pin()
5055 hapd.request("WPS_PIN any " + pin)
5056 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5057 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
5058 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5059 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5060 if ev is None:
5061 raise Exception("Association not seen")
5062 dev[0].request("WPS_CANCEL")
5063 dev[0].wait_disconnected()
5064
5065 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
5066 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5067 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5068 if ev is None:
5069 raise Exception("Association not seen")
5070 dev[0].request("WPS_CANCEL")
5071 hapd.disable()
5072 dev[0].request("REMOVE_NETWORK all")
5073 dev[0].wait_disconnected()
5074 time.sleep(0.2)
5075 dev[0].flush_scan_cache()
5076
5077 def test_ap_wps_assoc_req_ie_oom(dev, apdev):
5078 """WPS AssocReq IE OOM"""
5079 ssid = "test-wps"
5080 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
5081 hapd = hostapd.add_ap(apdev[0], params)
5082 pin = dev[0].wps_read_pin()
5083 hapd.request("WPS_PIN any " + pin)
5084 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5085 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
5086 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5087 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5088 if ev is None:
5089 raise Exception("Association not seen")
5090 dev[0].request("WPS_CANCEL")
5091
5092 def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
5093 """WPS AssocResp IE OOM"""
5094 ssid = "test-wps"
5095 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2" }
5096 hapd = hostapd.add_ap(apdev[0], params)
5097 pin = dev[0].wps_read_pin()
5098 hapd.request("WPS_PIN any " + pin)
5099 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5100 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
5101 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5102 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5103 if ev is None:
5104 raise Exception("Association not seen")
5105 dev[0].request("WPS_CANCEL")
5106
5107 @remote_compatible
5108 def test_ap_wps_bss_info_errors(dev, apdev):
5109 """WPS BSS info errors"""
5110 params = { "ssid": "1",
5111 "vendor_elements": "dd0e0050f20410440001ff101100010a" }
5112 hostapd.add_ap(apdev[0], params)
5113 params = { 'ssid': "2", "vendor_elements": "dd050050f20410" }
5114 hostapd.add_ap(apdev[1], params)
5115 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5116 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5117 bss = dev[0].get_bss(apdev[0]['bssid'])
5118 logger.info("BSS: " + str(bss))
5119 if "wps_state" in bss:
5120 raise Exception("Unexpected wps_state in BSS info")
5121 if 'wps_device_name' not in bss:
5122 raise Exception("No wps_device_name in BSS info")
5123 if bss['wps_device_name'] != '_':
5124 raise Exception("Unexpected wps_device_name value")
5125 bss = dev[0].get_bss(apdev[1]['bssid'])
5126 logger.info("BSS: " + str(bss))
5127
5128 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5129 bss = dev[0].get_bss(apdev[0]['bssid'])
5130 logger.info("BSS(OOM): " + str(bss))
5131
5132 def wps_run_pbc_fail_ap(apdev, dev, hapd):
5133 hapd.request("WPS_PBC")
5134 dev.scan_for_bss(apdev['bssid'], freq="2412")
5135 dev.request("WPS_PBC " + apdev['bssid'])
5136 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5137 if ev is None:
5138 raise Exception("No EAP failure reported")
5139 dev.request("WPS_CANCEL")
5140 dev.wait_disconnected()
5141 for i in range(5):
5142 try:
5143 dev.flush_scan_cache()
5144 break
5145 except Exception as e:
5146 if str(e).startswith("Failed to trigger scan"):
5147 # Try again
5148 time.sleep(1)
5149 else:
5150 raise
5151
5152 def wps_run_pbc_fail(apdev, dev):
5153 hapd = wps_start_ap(apdev)
5154 wps_run_pbc_fail_ap(apdev, dev, hapd)
5155
5156 @remote_compatible
5157 def test_ap_wps_pk_oom(dev, apdev):
5158 """WPS and public key OOM"""
5159 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5160 wps_run_pbc_fail(apdev[0], dev[0])
5161
5162 @remote_compatible
5163 def test_ap_wps_pk_oom_ap(dev, apdev):
5164 """WPS and public key OOM on AP"""
5165 hapd = wps_start_ap(apdev[0])
5166 with alloc_fail(hapd, 1, "wps_build_public_key"):
5167 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5168
5169 @remote_compatible
5170 def test_ap_wps_encr_oom_ap(dev, apdev):
5171 """WPS and encrypted settings decryption OOM on AP"""
5172 hapd = wps_start_ap(apdev[0])
5173 pin = dev[0].wps_read_pin()
5174 hapd.request("WPS_PIN any " + pin)
5175 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5176 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5177 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5178 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5179 if ev is None:
5180 raise Exception("No WPS-FAIL reported")
5181 dev[0].request("WPS_CANCEL")
5182 dev[0].wait_disconnected()
5183
5184 @remote_compatible
5185 def test_ap_wps_encr_no_random_ap(dev, apdev):
5186 """WPS and no random data available for encryption on AP"""
5187 hapd = wps_start_ap(apdev[0])
5188 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5189 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5190
5191 @remote_compatible
5192 def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5193 """WPS and no random data available for e-hash on STA"""
5194 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5195 wps_run_pbc_fail(apdev[0], dev[0])
5196
5197 @remote_compatible
5198 def test_ap_wps_m1_no_random(dev, apdev):
5199 """WPS and no random for M1 on STA"""
5200 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5201 wps_run_pbc_fail(apdev[0], dev[0])
5202
5203 @remote_compatible
5204 def test_ap_wps_m1_oom(dev, apdev):
5205 """WPS and OOM for M1 on STA"""
5206 with alloc_fail(dev[0], 1, "wps_build_m1"):
5207 wps_run_pbc_fail(apdev[0], dev[0])
5208
5209 @remote_compatible
5210 def test_ap_wps_m3_oom(dev, apdev):
5211 """WPS and OOM for M3 on STA"""
5212 with alloc_fail(dev[0], 1, "wps_build_m3"):
5213 wps_run_pbc_fail(apdev[0], dev[0])
5214
5215 @remote_compatible
5216 def test_ap_wps_m5_oom(dev, apdev):
5217 """WPS and OOM for M5 on STA"""
5218 hapd = wps_start_ap(apdev[0])
5219 hapd.request("WPS_PBC")
5220 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5221 for i in range(1, 3):
5222 with alloc_fail(dev[0], i, "wps_build_m5"):
5223 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5224 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5225 if ev is None:
5226 raise Exception("No EAP failure reported")
5227 dev[0].request("WPS_CANCEL")
5228 dev[0].wait_disconnected()
5229 dev[0].flush_scan_cache()
5230
5231 @remote_compatible
5232 def test_ap_wps_m5_no_random(dev, apdev):
5233 """WPS and no random for M5 on STA"""
5234 with fail_test(dev[0], 1,
5235 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5236 wps_run_pbc_fail(apdev[0], dev[0])
5237
5238 @remote_compatible
5239 def test_ap_wps_m7_oom(dev, apdev):
5240 """WPS and OOM for M7 on STA"""
5241 hapd = wps_start_ap(apdev[0])
5242 hapd.request("WPS_PBC")
5243 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5244 for i in range(1, 3):
5245 with alloc_fail(dev[0], i, "wps_build_m7"):
5246 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5247 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5248 if ev is None:
5249 raise Exception("No EAP failure reported")
5250 dev[0].request("WPS_CANCEL")
5251 dev[0].wait_disconnected()
5252 dev[0].flush_scan_cache()
5253
5254 @remote_compatible
5255 def test_ap_wps_m7_no_random(dev, apdev):
5256 """WPS and no random for M7 on STA"""
5257 with fail_test(dev[0], 1,
5258 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5259 wps_run_pbc_fail(apdev[0], dev[0])
5260
5261 @remote_compatible
5262 def test_ap_wps_wsc_done_oom(dev, apdev):
5263 """WPS and OOM for WSC_Done on STA"""
5264 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5265 wps_run_pbc_fail(apdev[0], dev[0])
5266
5267 def test_ap_wps_random_psk_fail(dev, apdev):
5268 """WPS and no random for PSK on AP"""
5269 ssid = "test-wps"
5270 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5271 appin = "12345670"
5272 try:
5273 os.remove(pskfile)
5274 except:
5275 pass
5276
5277 try:
5278 with open(pskfile, "w") as f:
5279 f.write("# WPA PSKs\n")
5280
5281 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5282 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5283 "rsn_pairwise": "CCMP", "ap_pin": appin,
5284 "wpa_psk_file": pskfile }
5285 hapd = hostapd.add_ap(apdev[0], params)
5286
5287 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5288 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5289 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5290 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5291 if ev is None:
5292 raise Exception("No EAP failure reported")
5293 dev[0].request("WPS_CANCEL")
5294 dev[0].wait_disconnected()
5295
5296 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5297 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5298
5299 with alloc_fail(hapd, 1, "wps_build_cred"):
5300 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5301
5302 with alloc_fail(hapd, 2, "wps_build_cred"):
5303 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5304 finally:
5305 os.remove(pskfile)
5306
5307 def wps_ext_eap_identity_req(dev, hapd, bssid):
5308 logger.debug("EAP-Identity/Request")
5309 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5310 if ev is None:
5311 raise Exception("Timeout on EAPOL-TX from hostapd")
5312 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5313 if "OK" not in res:
5314 raise Exception("EAPOL_RX to wpa_supplicant failed")
5315
5316 def wps_ext_eap_identity_resp(hapd, dev, addr):
5317 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5318 if ev is None:
5319 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5320 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5321 if "OK" not in res:
5322 raise Exception("EAPOL_RX to hostapd failed")
5323
5324 def wps_ext_eap_wsc(dst, src, src_addr, msg):
5325 logger.debug(msg)
5326 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5327 if ev is None:
5328 raise Exception("Timeout on EAPOL-TX")
5329 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5330 if "OK" not in res:
5331 raise Exception("EAPOL_RX failed")
5332
5333 def wps_start_ext(apdev, dev, pbc=False, pin=None):
5334 addr = dev.own_addr()
5335 bssid = apdev['bssid']
5336 ssid = "test-wps-conf"
5337 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5338 "wpa_passphrase": "12345678", "wpa": "2",
5339 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
5340 hapd = hostapd.add_ap(apdev, params)
5341
5342 if pbc:
5343 hapd.request("WPS_PBC")
5344 else:
5345 if pin is None:
5346 pin = dev.wps_read_pin()
5347 hapd.request("WPS_PIN any " + pin)
5348 dev.scan_for_bss(bssid, freq="2412")
5349 hapd.request("SET ext_eapol_frame_io 1")
5350 dev.request("SET ext_eapol_frame_io 1")
5351
5352 if pbc:
5353 dev.request("WPS_PBC " + bssid)
5354 else:
5355 dev.request("WPS_PIN " + bssid + " " + pin)
5356 return addr,bssid,hapd
5357
5358 def wps_auth_corrupt(dst, src, addr):
5359 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5360 if ev is None:
5361 raise Exception("Timeout on EAPOL-TX")
5362 src.request("SET ext_eapol_frame_io 0")
5363 dst.request("SET ext_eapol_frame_io 0")
5364 msg = ev.split(' ')[2]
5365 if msg[-24:-16] != '10050008':
5366 raise Exception("Could not find Authenticator attribute")
5367 # Corrupt Authenticator value
5368 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5369 res = dst.request("EAPOL_RX " + addr + " " + msg)
5370 if "OK" not in res:
5371 raise Exception("EAPOL_RX failed")
5372
5373 def wps_fail_finish(hapd, dev, fail_str):
5374 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5375 if ev is None:
5376 raise Exception("WPS-FAIL not indicated")
5377 if fail_str not in ev:
5378 raise Exception("Unexpected WPS-FAIL value: " + ev)
5379 dev.request("WPS_CANCEL")
5380 dev.wait_disconnected()
5381
5382 def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5383 wps_auth_corrupt(dev, hapd, bssid)
5384 wps_fail_finish(hapd, dev, fail_str)
5385
5386 def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5387 wps_auth_corrupt(hapd, dev, addr)
5388 wps_fail_finish(hapd, dev, fail_str)
5389
5390 def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5391 """WPS and Authenticator attribute mismatch in M2"""
5392 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5393 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5394 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5395 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5396 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5397 logger.debug("M2")
5398 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5399
5400 def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5401 """WPS and Authenticator attribute mismatch in M3"""
5402 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5403 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5404 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5405 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5406 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5407 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5408 logger.debug("M3")
5409 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5410
5411 def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5412 """WPS and Authenticator attribute mismatch in M4"""
5413 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5414 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5415 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5416 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5417 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5418 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5419 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5420 logger.debug("M4")
5421 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5422
5423 def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5424 """WPS and Authenticator attribute mismatch in M5"""
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 logger.debug("M5")
5434 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5435
5436 def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5437 """WPS and Authenticator attribute mismatch in M6"""
5438 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5439 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5440 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5441 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5442 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5443 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5444 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5445 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5446 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5447 logger.debug("M6")
5448 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5449
5450 def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5451 """WPS and Authenticator attribute mismatch in M7"""
5452 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5453 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5454 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5455 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5456 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5457 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5458 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5459 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5460 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5461 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5462 logger.debug("M7")
5463 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5464
5465 def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5466 """WPS and Authenticator attribute mismatch in M8"""
5467 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5468 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5469 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5470 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5471 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5472 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5473 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5474 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5475 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5476 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5477 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5478 logger.debug("M8")
5479 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5480
5481 def test_ap_wps_authenticator_missing_m2(dev, apdev):
5482 """WPS and Authenticator attribute missing from M2"""
5483 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5484 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5485 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5486 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5487 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5488 logger.debug("M2")
5489 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5490 if ev is None:
5491 raise Exception("Timeout on EAPOL-TX")
5492 hapd.request("SET ext_eapol_frame_io 0")
5493 dev[0].request("SET ext_eapol_frame_io 0")
5494 msg = ev.split(' ')[2]
5495 if msg[-24:-16] != '10050008':
5496 raise Exception("Could not find Authenticator attribute")
5497 # Remove Authenticator value
5498 msg = msg[:-24]
5499 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5500 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5501 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5502 if "OK" not in res:
5503 raise Exception("EAPOL_RX failed")
5504 wps_fail_finish(hapd, dev[0], "msg=5")
5505
5506 def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5507 """WPS and M2 with different Device Password ID (P2P)"""
5508 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5509 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5510 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5511 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5512 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5513 logger.debug("M2")
5514 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5515 if ev is None:
5516 raise Exception("Timeout on EAPOL-TX")
5517 hapd.request("SET ext_eapol_frame_io 0")
5518 dev[0].request("SET ext_eapol_frame_io 0")
5519 msg = ev.split(' ')[2]
5520 if msg[722:730] != '10120002':
5521 raise Exception("Could not find Device Password ID attribute")
5522 # Replace Device Password ID value. This will fail Authenticator check, but
5523 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5524 # log.
5525 msg = msg[0:730] + "0005" + msg[734:]
5526 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5527 if "OK" not in res:
5528 raise Exception("EAPOL_RX failed")
5529 wps_fail_finish(hapd, dev[0], "msg=5")
5530
5531 def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5532 """WPS and M2 with different Device Password ID (PIN to PBC)"""
5533 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5534 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5535 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5536 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5537 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5538 logger.debug("M2")
5539 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5540 if ev is None:
5541 raise Exception("Timeout on EAPOL-TX")
5542 hapd.request("SET ext_eapol_frame_io 0")
5543 dev[0].request("SET ext_eapol_frame_io 0")
5544 msg = ev.split(' ')[2]
5545 if msg[722:730] != '10120002':
5546 raise Exception("Could not find Device Password ID attribute")
5547 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5548 msg = msg[0:730] + "0004" + msg[734:]
5549 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5550 if "OK" not in res:
5551 raise Exception("EAPOL_RX failed")
5552 wps_fail_finish(hapd, dev[0], "msg=5")
5553
5554 def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5555 """WPS and M2 with different Device Password ID (PBC to PIN)"""
5556 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5557 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5558 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5559 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5560 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5561 logger.debug("M2")
5562 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5563 if ev is None:
5564 raise Exception("Timeout on EAPOL-TX")
5565 hapd.request("SET ext_eapol_frame_io 0")
5566 dev[0].request("SET ext_eapol_frame_io 0")
5567 msg = ev.split(' ')[2]
5568 if msg[722:730] != '10120002':
5569 raise Exception("Could not find Device Password ID attribute")
5570 # Replace Device Password ID value. This will fail Authenticator check, but
5571 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5572 # log.
5573 msg = msg[0:730] + "0000" + 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 dev[0].flush_scan_cache()
5579
5580 def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5581 """WPS and M2 without Device Password ID"""
5582 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0])
5583 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5584 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5585 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5586 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5587 logger.debug("M2")
5588 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5589 if ev is None:
5590 raise Exception("Timeout on EAPOL-TX")
5591 hapd.request("SET ext_eapol_frame_io 0")
5592 dev[0].request("SET ext_eapol_frame_io 0")
5593 msg = ev.split(' ')[2]
5594 if msg[722:730] != '10120002':
5595 raise Exception("Could not find Device Password ID attribute")
5596 # Remove Device Password ID value. This will fail Authenticator check, but
5597 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5598 # log.
5599 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5600 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5601 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5602 if "OK" not in res:
5603 raise Exception("EAPOL_RX failed")
5604 wps_fail_finish(hapd, dev[0], "msg=5")
5605
5606 def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5607 """WPS and M2 without Registrar Nonce"""
5608 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5609 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5610 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5611 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5612 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5613 logger.debug("M2")
5614 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5615 if ev is None:
5616 raise Exception("Timeout on EAPOL-TX")
5617 hapd.request("SET ext_eapol_frame_io 0")
5618 dev[0].request("SET ext_eapol_frame_io 0")
5619 msg = ev.split(' ')[2]
5620 if msg[96:104] != '10390010':
5621 raise Exception("Could not find Registrar Nonce attribute")
5622 # Remove Registrar Nonce. This will fail Authenticator check, but
5623 # allows the code path in wps_process_registrar_nonce() to be checked from
5624 # the debug log.
5625 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5626 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5627 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5628 if "OK" not in res:
5629 raise Exception("EAPOL_RX failed")
5630 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5631 if ev is None:
5632 raise Exception("Disconnect event not seen")
5633 dev[0].request("WPS_CANCEL")
5634 dev[0].flush_scan_cache()
5635
5636 def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5637 """WPS and M2 without Enrollee Nonce"""
5638 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5639 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5640 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5641 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5642 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5643 logger.debug("M2")
5644 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5645 if ev is None:
5646 raise Exception("Timeout on EAPOL-TX")
5647 hapd.request("SET ext_eapol_frame_io 0")
5648 dev[0].request("SET ext_eapol_frame_io 0")
5649 msg = ev.split(' ')[2]
5650 if msg[56:64] != '101a0010':
5651 raise Exception("Could not find enrollee Nonce attribute")
5652 # Remove Enrollee Nonce. This will fail Authenticator check, but
5653 # allows the code path in wps_process_enrollee_nonce() to be checked from
5654 # the debug log.
5655 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5656 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5657 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5658 if "OK" not in res:
5659 raise Exception("EAPOL_RX failed")
5660 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5661 if ev is None:
5662 raise Exception("Disconnect event not seen")
5663 dev[0].request("WPS_CANCEL")
5664 dev[0].flush_scan_cache()
5665
5666 def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5667 """WPS and M2 without UUID-R"""
5668 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5669 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5670 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5671 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5672 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5673 logger.debug("M2")
5674 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5675 if ev is None:
5676 raise Exception("Timeout on EAPOL-TX")
5677 hapd.request("SET ext_eapol_frame_io 0")
5678 dev[0].request("SET ext_eapol_frame_io 0")
5679 msg = ev.split(' ')[2]
5680 if msg[136:144] != '10480010':
5681 raise Exception("Could not find enrollee Nonce attribute")
5682 # Remove UUID-R. This will fail Authenticator check, but allows the code
5683 # path in wps_process_uuid_r() to be checked from the debug log.
5684 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5685 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5686 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5687 if "OK" not in res:
5688 raise Exception("EAPOL_RX failed")
5689 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5690 if ev is None:
5691 raise Exception("Disconnect event not seen")
5692 dev[0].request("WPS_CANCEL")
5693 dev[0].flush_scan_cache()
5694
5695 def test_ap_wps_m2_invalid(dev, apdev):
5696 """WPS and M2 parsing failure"""
5697 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5698 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5699 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5700 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5701 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5702 logger.debug("M2")
5703 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5704 if ev is None:
5705 raise Exception("Timeout on EAPOL-TX")
5706 hapd.request("SET ext_eapol_frame_io 0")
5707 dev[0].request("SET ext_eapol_frame_io 0")
5708 msg = ev.split(' ')[2]
5709 if msg[136:144] != '10480010':
5710 raise Exception("Could not find enrollee Nonce attribute")
5711 # Remove UUID-R. This will fail Authenticator check, but allows the code
5712 # path in wps_process_uuid_r() to be checked from the debug log.
5713 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5714 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5715 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5716 if "OK" not in res:
5717 raise Exception("EAPOL_RX failed")
5718 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5719 if ev is None:
5720 raise Exception("Disconnect event not seen")
5721 dev[0].request("WPS_CANCEL")
5722 dev[0].flush_scan_cache()
5723
5724 def test_ap_wps_m2_missing_msg_type(dev, apdev):
5725 """WPS and M2 without Message Type"""
5726 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5727 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5728 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5729 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5730 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5731 logger.debug("M2")
5732 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5733 if ev is None:
5734 raise Exception("Timeout on EAPOL-TX")
5735 hapd.request("SET ext_eapol_frame_io 0")
5736 dev[0].request("SET ext_eapol_frame_io 0")
5737 msg = ev.split(' ')[2]
5738 if msg[46:54] != '10220001':
5739 raise Exception("Could not find Message Type attribute")
5740 # Remove Message Type. This will fail Authenticator check, but allows the
5741 # code path in wps_process_wsc_msg() to be checked from the debug log.
5742 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5743 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + 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
5753 def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5754 """WPS and M2 but unknown Message Type"""
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 if msg[46:54] != '10220001':
5768 raise Exception("Could not find Message Type attribute")
5769 # Replace Message Type value. This will be rejected.
5770 msg = msg[0:54] + "00" + msg[56:]
5771 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5772 if "OK" not in res:
5773 raise Exception("EAPOL_RX failed")
5774 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5775 if ev is None:
5776 raise Exception("Disconnect event not seen")
5777 dev[0].request("WPS_CANCEL")
5778 dev[0].flush_scan_cache()
5779
5780 def test_ap_wps_m2_unknown_opcode(dev, apdev):
5781 """WPS and M2 but unknown opcode"""
5782 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5783 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5784 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5785 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5786 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5787 logger.debug("M2")
5788 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5789 if ev is None:
5790 raise Exception("Timeout on EAPOL-TX")
5791 hapd.request("SET ext_eapol_frame_io 0")
5792 dev[0].request("SET ext_eapol_frame_io 0")
5793 msg = ev.split(' ')[2]
5794 # Replace opcode. This will be discarded in EAP-WSC processing.
5795 msg = msg[0:32] + "00" + msg[34:]
5796 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5797 if "OK" not in res:
5798 raise Exception("EAPOL_RX failed")
5799 dev[0].request("WPS_CANCEL")
5800 dev[0].wait_disconnected()
5801 dev[0].flush_scan_cache()
5802
5803 def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5804 """WPS and M2 but unknown opcode (WSC_Start)"""
5805 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5806 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5807 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5808 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5809 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5810 logger.debug("M2")
5811 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5812 if ev is None:
5813 raise Exception("Timeout on EAPOL-TX")
5814 hapd.request("SET ext_eapol_frame_io 0")
5815 dev[0].request("SET ext_eapol_frame_io 0")
5816 msg = ev.split(' ')[2]
5817 # Replace opcode. This will be discarded in EAP-WSC processing.
5818 msg = msg[0:32] + "01" + msg[34:]
5819 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5820 if "OK" not in res:
5821 raise Exception("EAPOL_RX failed")
5822 dev[0].request("WPS_CANCEL")
5823 dev[0].wait_disconnected()
5824 dev[0].flush_scan_cache()
5825
5826 def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5827 """WPS and M2 but unknown opcode (WSC_Done)"""
5828 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5829 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5830 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5831 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5832 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5833 logger.debug("M2")
5834 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5835 if ev is None:
5836 raise Exception("Timeout on EAPOL-TX")
5837 hapd.request("SET ext_eapol_frame_io 0")
5838 dev[0].request("SET ext_eapol_frame_io 0")
5839 msg = ev.split(' ')[2]
5840 # Replace opcode. This will be discarded in WPS Enrollee processing.
5841 msg = msg[0:32] + "05" + msg[34:]
5842 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5843 if "OK" not in res:
5844 raise Exception("EAPOL_RX failed")
5845 dev[0].request("WPS_CANCEL")
5846 dev[0].wait_disconnected()
5847 dev[0].flush_scan_cache()
5848
5849 def wps_m2_but_other(dev, apdev, title, msgtype):
5850 addr,bssid,hapd = wps_start_ext(apdev, dev)
5851 wps_ext_eap_identity_req(dev, hapd, bssid)
5852 wps_ext_eap_identity_resp(hapd, dev, addr)
5853 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5854 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5855 logger.debug(title)
5856 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5857 if ev is None:
5858 raise Exception("Timeout on EAPOL-TX")
5859 hapd.request("SET ext_eapol_frame_io 0")
5860 dev.request("SET ext_eapol_frame_io 0")
5861 msg = ev.split(' ')[2]
5862 if msg[46:54] != '10220001':
5863 raise Exception("Could not find Message Type attribute")
5864 # Replace Message Type value. This will be rejected.
5865 msg = msg[0:54] + msgtype + msg[56:]
5866 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5867 if "OK" not in res:
5868 raise Exception("EAPOL_RX failed")
5869 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5870 if ev is None:
5871 raise Exception("WPS-FAIL event not seen")
5872 dev.request("WPS_CANCEL")
5873 dev.wait_disconnected()
5874
5875 def wps_m4_but_other(dev, apdev, title, msgtype):
5876 addr,bssid,hapd = wps_start_ext(apdev, dev)
5877 wps_ext_eap_identity_req(dev, hapd, bssid)
5878 wps_ext_eap_identity_resp(hapd, dev, addr)
5879 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5880 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5881 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5882 wps_ext_eap_wsc(hapd, dev, addr, "M3")
5883 logger.debug(title)
5884 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5885 if ev is None:
5886 raise Exception("Timeout on EAPOL-TX")
5887 hapd.request("SET ext_eapol_frame_io 0")
5888 dev.request("SET ext_eapol_frame_io 0")
5889 msg = ev.split(' ')[2]
5890 if msg[46:54] != '10220001':
5891 raise Exception("Could not find Message Type attribute")
5892 # Replace Message Type value. This will be rejected.
5893 msg = msg[0:54] + msgtype + msg[56:]
5894 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5895 if "OK" not in res:
5896 raise Exception("EAPOL_RX failed")
5897 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5898 if ev is None:
5899 raise Exception("WPS-FAIL event not seen")
5900 dev.request("WPS_CANCEL")
5901 dev.wait_disconnected()
5902
5903 def test_ap_wps_m2_msg_type_m4(dev, apdev):
5904 """WPS and M2 but Message Type M4"""
5905 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5906
5907 def test_ap_wps_m2_msg_type_m6(dev, apdev):
5908 """WPS and M2 but Message Type M6"""
5909 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5910
5911 def test_ap_wps_m2_msg_type_m8(dev, apdev):
5912 """WPS and M2 but Message Type M8"""
5913 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5914
5915 def test_ap_wps_m4_msg_type_m2(dev, apdev):
5916 """WPS and M4 but Message Type M2"""
5917 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5918
5919 def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5920 """WPS and M4 but Message Type M2D"""
5921 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5922
5923 @remote_compatible
5924 def test_ap_wps_config_methods(dev, apdev):
5925 """WPS configuration method parsing"""
5926 ssid = "test-wps-conf"
5927 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5928 "wpa_passphrase": "12345678", "wpa": "2",
5929 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5930 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button" }
5931 hapd = hostapd.add_ap(apdev[0], params)
5932 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
5933 "wpa_passphrase": "12345678", "wpa": "2",
5934 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5935 "config_methods": "display push_button" }
5936 hapd2 = hostapd.add_ap(apdev[1], params)
5937
5938 def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5939 """WPS UPnP SetSelectedRegistrar protocol testing"""
5940 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5941 hapd = add_ssdp_ap(apdev[0], ap_uuid)
5942
5943 location = ssdp_get_location(ap_uuid)
5944 urls = upnp_get_urls(location)
5945 eventurl = urlparse(urls['event_sub_url'])
5946 ctrlurl = urlparse(urls['control_url'])
5947 url = urlparse(location)
5948 conn = HTTPConnection(url.netloc)
5949
5950 class WPSERHTTPServer(StreamRequestHandler):
5951 def handle(self):
5952 data = self.rfile.readline().strip()
5953 logger.debug(data)
5954 self.wfile.write(gen_wps_event())
5955
5956 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5957 server.timeout = 1
5958
5959 headers = { "callback": '<http://127.0.0.1:12345/event>',
5960 "NT": "upnp:event",
5961 "timeout": "Second-1234" }
5962 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5963 resp = conn.getresponse()
5964 if resp.status != 200:
5965 raise Exception("Unexpected HTTP response: %d" % resp.status)
5966 sid = resp.getheader("sid")
5967 logger.debug("Subscription SID " + sid)
5968 server.handle_request()
5969
5970 tests = [ (500, "10"),
5971 (200, "104a000110" + "1041000101" + "101200020000" +
5972 "105300023148" +
5973 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
5974 "10480010362db47ba53a519188fb5458b986b2e4"),
5975 (200, "104a000110" + "1041000100" + "101200020000" +
5976 "105300020000"),
5977 (200, "104a000110" + "1041000100"),
5978 (200, "104a000110") ]
5979 for status,test in tests:
5980 tlvs = binascii.unhexlify(test)
5981 newmsg = base64.b64encode(tlvs).decode()
5982 msg = '<?xml version="1.0"?>\n'
5983 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
5984 msg += '<s:Body>'
5985 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
5986 msg += '<NewMessage>'
5987 msg += newmsg
5988 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
5989 headers = { "Content-type": 'text/xml; charset="utf-8"' }
5990 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
5991 conn.request("POST", ctrlurl.path, msg, headers)
5992 resp = conn.getresponse()
5993 if resp.status != status:
5994 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
5995
5996 def test_ap_wps_adv_oom(dev, apdev):
5997 """WPS AP and advertisement OOM"""
5998 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5999 hapd = add_ssdp_ap(apdev[0], ap_uuid)
6000
6001 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
6002 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6003 no_recv=True)
6004 time.sleep(0.2)
6005
6006 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
6007 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6008 no_recv=True)
6009 time.sleep(0.2)
6010
6011 with alloc_fail(hapd, 1,
6012 "next_advertisement;advertisement_state_machine_stop"):
6013 hapd.disable()
6014
6015 with alloc_fail(hapd, 1, "ssdp_listener_start"):
6016 if "FAIL" not in hapd.request("ENABLE"):
6017 raise Exception("ENABLE succeeded during OOM")
6018
6019 def test_wps_config_methods(dev):
6020 """WPS config method update"""
6021 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6022 wpas.interface_add("wlan5")
6023 if "OK" not in wpas.request("SET config_methods display label"):
6024 raise Exception("Failed to set config_methods")
6025 if wpas.request("GET config_methods").strip() != "display label":
6026 raise Exception("config_methods were not updated")
6027 if "OK" not in wpas.request("SET config_methods "):
6028 raise Exception("Failed to clear config_methods")
6029 if wpas.request("GET config_methods").strip() != "":
6030 raise Exception("config_methods were not cleared")
6031
6032 WPS_VENDOR_ID_WFA = 14122
6033 WPS_VENDOR_TYPE = 1
6034
6035 # EAP-WSC Op-Code values
6036 WSC_Start = 0x01
6037 WSC_ACK = 0x02
6038 WSC_NACK = 0x03
6039 WSC_MSG = 0x04
6040 WSC_Done = 0x05
6041 WSC_FRAG_ACK = 0x06
6042
6043 ATTR_AP_CHANNEL = 0x1001
6044 ATTR_ASSOC_STATE = 0x1002
6045 ATTR_AUTH_TYPE = 0x1003
6046 ATTR_AUTH_TYPE_FLAGS = 0x1004
6047 ATTR_AUTHENTICATOR = 0x1005
6048 ATTR_CONFIG_METHODS = 0x1008
6049 ATTR_CONFIG_ERROR = 0x1009
6050 ATTR_CONFIRM_URL4 = 0x100a
6051 ATTR_CONFIRM_URL6 = 0x100b
6052 ATTR_CONN_TYPE = 0x100c
6053 ATTR_CONN_TYPE_FLAGS = 0x100d
6054 ATTR_CRED = 0x100e
6055 ATTR_ENCR_TYPE = 0x100f
6056 ATTR_ENCR_TYPE_FLAGS = 0x1010
6057 ATTR_DEV_NAME = 0x1011
6058 ATTR_DEV_PASSWORD_ID = 0x1012
6059 ATTR_E_HASH1 = 0x1014
6060 ATTR_E_HASH2 = 0x1015
6061 ATTR_E_SNONCE1 = 0x1016
6062 ATTR_E_SNONCE2 = 0x1017
6063 ATTR_ENCR_SETTINGS = 0x1018
6064 ATTR_ENROLLEE_NONCE = 0x101a
6065 ATTR_FEATURE_ID = 0x101b
6066 ATTR_IDENTITY = 0x101c
6067 ATTR_IDENTITY_PROOF = 0x101d
6068 ATTR_KEY_WRAP_AUTH = 0x101e
6069 ATTR_KEY_ID = 0x101f
6070 ATTR_MAC_ADDR = 0x1020
6071 ATTR_MANUFACTURER = 0x1021
6072 ATTR_MSG_TYPE = 0x1022
6073 ATTR_MODEL_NAME = 0x1023
6074 ATTR_MODEL_NUMBER = 0x1024
6075 ATTR_NETWORK_INDEX = 0x1026
6076 ATTR_NETWORK_KEY = 0x1027
6077 ATTR_NETWORK_KEY_INDEX = 0x1028
6078 ATTR_NEW_DEVICE_NAME = 0x1029
6079 ATTR_NEW_PASSWORD = 0x102a
6080 ATTR_OOB_DEVICE_PASSWORD = 0x102c
6081 ATTR_OS_VERSION = 0x102d
6082 ATTR_POWER_LEVEL = 0x102f
6083 ATTR_PSK_CURRENT = 0x1030
6084 ATTR_PSK_MAX = 0x1031
6085 ATTR_PUBLIC_KEY = 0x1032
6086 ATTR_RADIO_ENABLE = 0x1033
6087 ATTR_REBOOT = 0x1034
6088 ATTR_REGISTRAR_CURRENT = 0x1035
6089 ATTR_REGISTRAR_ESTABLISHED = 0x1036
6090 ATTR_REGISTRAR_LIST = 0x1037
6091 ATTR_REGISTRAR_MAX = 0x1038
6092 ATTR_REGISTRAR_NONCE = 0x1039
6093 ATTR_REQUEST_TYPE = 0x103a
6094 ATTR_RESPONSE_TYPE = 0x103b
6095 ATTR_RF_BANDS = 0x103c
6096 ATTR_R_HASH1 = 0x103d
6097 ATTR_R_HASH2 = 0x103e
6098 ATTR_R_SNONCE1 = 0x103f
6099 ATTR_R_SNONCE2 = 0x1040
6100 ATTR_SELECTED_REGISTRAR = 0x1041
6101 ATTR_SERIAL_NUMBER = 0x1042
6102 ATTR_WPS_STATE = 0x1044
6103 ATTR_SSID = 0x1045
6104 ATTR_TOTAL_NETWORKS = 0x1046
6105 ATTR_UUID_E = 0x1047
6106 ATTR_UUID_R = 0x1048
6107 ATTR_VENDOR_EXT = 0x1049
6108 ATTR_VERSION = 0x104a
6109 ATTR_X509_CERT_REQ = 0x104b
6110 ATTR_X509_CERT = 0x104c
6111 ATTR_EAP_IDENTITY = 0x104d
6112 ATTR_MSG_COUNTER = 0x104e
6113 ATTR_PUBKEY_HASH = 0x104f
6114 ATTR_REKEY_KEY = 0x1050
6115 ATTR_KEY_LIFETIME = 0x1051
6116 ATTR_PERMITTED_CFG_METHODS = 0x1052
6117 ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
6118 ATTR_PRIMARY_DEV_TYPE = 0x1054
6119 ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
6120 ATTR_PORTABLE_DEV = 0x1056
6121 ATTR_AP_SETUP_LOCKED = 0x1057
6122 ATTR_APPLICATION_EXT = 0x1058
6123 ATTR_EAP_TYPE = 0x1059
6124 ATTR_IV = 0x1060
6125 ATTR_KEY_PROVIDED_AUTO = 0x1061
6126 ATTR_802_1X_ENABLED = 0x1062
6127 ATTR_APPSESSIONKEY = 0x1063
6128 ATTR_WEPTRANSMITKEY = 0x1064
6129 ATTR_REQUESTED_DEV_TYPE = 0x106a
6130
6131 # Message Type
6132 WPS_Beacon = 0x01
6133 WPS_ProbeRequest = 0x02
6134 WPS_ProbeResponse = 0x03
6135 WPS_M1 = 0x04
6136 WPS_M2 = 0x05
6137 WPS_M2D = 0x06
6138 WPS_M3 = 0x07
6139 WPS_M4 = 0x08
6140 WPS_M5 = 0x09
6141 WPS_M6 = 0x0a
6142 WPS_M7 = 0x0b
6143 WPS_M8 = 0x0c
6144 WPS_WSC_ACK = 0x0d
6145 WPS_WSC_NACK = 0x0e
6146 WPS_WSC_DONE = 0x0f
6147
6148 def get_wsc_msg(dev):
6149 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6150 if ev is None:
6151 raise Exception("Timeout on EAPOL-TX")
6152 data = binascii.unhexlify(ev.split(' ')[2])
6153 msg = {}
6154
6155 # Parse EAPOL header
6156 if len(data) < 4:
6157 raise Exception("No room for EAPOL header")
6158 version,type,length = struct.unpack('>BBH', data[0:4])
6159 msg['eapol_version'] = version
6160 msg['eapol_type'] = type
6161 msg['eapol_length'] = length
6162 data = data[4:]
6163 if length != len(data):
6164 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6165 if type != 0:
6166 raise Exception("Unexpected EAPOL header type: %d" % type)
6167
6168 # Parse EAP header
6169 if len(data) < 4:
6170 raise Exception("No room for EAP header")
6171 code,identifier,length = struct.unpack('>BBH', data[0:4])
6172 msg['eap_code'] = code
6173 msg['eap_identifier'] = identifier
6174 msg['eap_length'] = length
6175 data = data[4:]
6176 if msg['eapol_length'] != msg['eap_length']:
6177 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6178
6179 # Parse EAP expanded header
6180 if len(data) < 1:
6181 raise Exception("No EAP type included")
6182 msg['eap_type'], = struct.unpack('B', data[0:1])
6183 data = data[1:]
6184
6185 if msg['eap_type'] == 254:
6186 if len(data) < 3 + 4:
6187 raise Exception("Truncated EAP expanded header")
6188 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', b'\x00' + data[0:7])
6189 data = data[7:]
6190 else:
6191 raise Exception("Unexpected EAP type")
6192
6193 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6194 raise Exception("Unexpected Vendor-Id")
6195 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6196 raise Exception("Unexpected Vendor-Type")
6197
6198 # Parse EAP-WSC header
6199 if len(data) < 2:
6200 raise Exception("Truncated EAP-WSC header")
6201 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6202 data = data[2:]
6203
6204 # Parse WSC attributes
6205 msg['raw_attrs'] = data
6206 attrs = {}
6207 while len(data) > 0:
6208 if len(data) < 4:
6209 raise Exception("Truncated attribute header")
6210 attr,length = struct.unpack('>HH', data[0:4])
6211 data = data[4:]
6212 if length > len(data):
6213 raise Exception("Truncated attribute 0x%04x" % attr)
6214 attrs[attr] = data[0:length]
6215 data = data[length:]
6216 msg['wsc_attrs'] = attrs
6217
6218 if ATTR_MSG_TYPE in attrs:
6219 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6220
6221 return msg
6222
6223 def recv_wsc_msg(dev, opcode, msg_type):
6224 msg = get_wsc_msg(dev)
6225 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6226 raise Exception("Unexpected Op-Code/MsgType")
6227 return msg, msg['wsc_attrs'], msg['raw_attrs']
6228
6229 def build_wsc_attr(attr, payload):
6230 _payload = payload if type(payload) == bytes else payload.encode()
6231 return struct.pack('>HH', attr, len(_payload)) + _payload
6232
6233 def build_attr_msg_type(msg_type):
6234 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6235
6236 def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6237 length = 4 + 8 + 2 + len(payload)
6238 # EAPOL header
6239 msg = struct.pack('>BBH', 2, 0, length)
6240 # EAP header
6241 msg += struct.pack('>BBH', eap_code, eap_id, length)
6242 # EAP expanded header for EAP-WSC
6243 msg += struct.pack('B', 254)
6244 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6245 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6246 # EAP-WSC header
6247 msg += struct.pack('BB', opcode, 0)
6248 # WSC attributes
6249 msg += payload
6250 return msg
6251
6252 def build_eap_success(eap_id):
6253 length = 4
6254 # EAPOL header
6255 msg = struct.pack('>BBH', 2, 0, length)
6256 # EAP header
6257 msg += struct.pack('>BBH', 3, eap_id, length)
6258 return msg
6259
6260 def build_eap_failure(eap_id):
6261 length = 4
6262 # EAPOL header
6263 msg = struct.pack('>BBH', 2, 0, length)
6264 # EAP header
6265 msg += struct.pack('>BBH', 4, eap_id, length)
6266 return msg
6267
6268 def send_wsc_msg(dev, src, msg):
6269 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg).decode())
6270 if "OK" not in res:
6271 raise Exception("EAPOL_RX failed")
6272
6273 group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6274 group_5_generator = 2
6275
6276 def wsc_kdf(key, label, bits):
6277 result = b''
6278 i = 1
6279 while len(result) * 8 < bits:
6280 data = struct.pack('>L', i) + label.encode() + struct.pack('>L', bits)
6281 m = hmac.new(key, data, hashlib.sha256)
6282 result += m.digest()
6283 i += 1
6284 return result[0:bits // 8]
6285
6286 def wsc_keys(kdk):
6287 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6288 authkey = keys[0:32]
6289 keywrapkey = keys[32:48]
6290 emsk = keys[48:80]
6291 return authkey,keywrapkey,emsk
6292
6293 def wsc_dev_pw_half_psk(authkey, dev_pw):
6294 m = hmac.new(authkey, dev_pw.encode(), hashlib.sha256)
6295 return m.digest()[0:16]
6296
6297 def wsc_dev_pw_psk(authkey, dev_pw):
6298 dev_pw_1 = dev_pw[0:len(dev_pw) // 2]
6299 dev_pw_2 = dev_pw[len(dev_pw) // 2:]
6300 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6301 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6302 return psk1,psk2
6303
6304 def build_attr_authenticator(authkey, prev_msg, curr_msg):
6305 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6306 auth = m.digest()[0:8]
6307 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6308
6309 def build_attr_encr_settings(authkey, keywrapkey, data):
6310 m = hmac.new(authkey, data, hashlib.sha256)
6311 kwa = m.digest()[0:8]
6312 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6313 iv = 16*b'\x99'
6314 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6315 pad_len = 16 - len(data) % 16
6316 ps = pad_len * struct.pack('B', pad_len)
6317 data += ps
6318 wrapped = aes.encrypt(data)
6319 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6320
6321 def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6322 if len(data) < 32 or len(data) % 16 != 0:
6323 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6324 iv = data[0:16]
6325 encr = data[16:]
6326 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6327 decrypted = aes.decrypt(encr)
6328 pad_len, = struct.unpack('B', decrypted[-1:])
6329 if pad_len > len(decrypted):
6330 raise Exception("Invalid padding in Encrypted Settings")
6331 for i in range(-pad_len, -1):
6332 if decrypted[i] != decrypted[-1]:
6333 raise Exception("Invalid PS value in Encrypted Settings")
6334
6335 decrypted = decrypted[0:len(decrypted) - pad_len]
6336 if len(decrypted) < 12:
6337 raise Exception("Truncated Encrypted Settings plaintext")
6338 kwa = decrypted[-12:]
6339 attr,length = struct.unpack(">HH", kwa[0:4])
6340 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6341 raise Exception("Invalid KWA header")
6342 kwa = kwa[4:]
6343 decrypted = decrypted[0:len(decrypted) - 12]
6344
6345 m = hmac.new(authkey, decrypted, hashlib.sha256)
6346 calc_kwa = m.digest()[0:8]
6347 if kwa != calc_kwa:
6348 raise Exception("KWA mismatch")
6349
6350 return decrypted
6351
6352 def zeropad_str(val, pad_len):
6353 while len(val) < pad_len * 2:
6354 val = '0' + val
6355 return val
6356
6357 def wsc_dh_init():
6358 # For now, use a hardcoded private key. In theory, this is supposed to be
6359 # randomly selected.
6360 own_private = 0x123456789
6361 own_public = pow(group_5_generator, own_private, group_5_prime)
6362 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6363 return own_private, pk
6364
6365 def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6366 peer_public = int(binascii.hexlify(peer_pk), 16)
6367 if peer_public < 2 or peer_public >= group_5_prime:
6368 raise Exception("Invalid peer public key")
6369 if pow(peer_public, (group_5_prime - 1) // 2, group_5_prime) != 1:
6370 raise Exception("Unexpected Legendre symbol for peer public key")
6371
6372 shared_secret = pow(peer_public, own_private, group_5_prime)
6373 ss = zeropad_str(format(shared_secret, "02x"), 192)
6374 logger.debug("DH shared secret: " + ss)
6375
6376 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6377 logger.debug("DHKey: " + binascii.hexlify(dhkey).decode())
6378
6379 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6380 kdk = m.digest()
6381 logger.debug("KDK: " + binascii.hexlify(kdk).decode())
6382 authkey,keywrapkey,emsk = wsc_keys(kdk)
6383 logger.debug("AuthKey: " + binascii.hexlify(authkey).decode())
6384 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey).decode())
6385 logger.debug("EMSK: " + binascii.hexlify(emsk).decode())
6386 return authkey,keywrapkey
6387
6388 def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6389 psk1,psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6390 logger.debug("PSK1: " + binascii.hexlify(psk1).decode())
6391 logger.debug("PSK2: " + binascii.hexlify(psk2).decode())
6392
6393 # Note: Secret values are supposed to be random, but hardcoded values are
6394 # fine for testing.
6395 s1 = 16*b'\x77'
6396 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6397 hash1 = m.digest()
6398 logger.debug("Hash1: " + binascii.hexlify(hash1).decode())
6399
6400 s2 = 16*b'\x88'
6401 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6402 hash2 = m.digest()
6403 logger.debug("Hash2: " + binascii.hexlify(hash2).decode())
6404 return s1,s2,hash1,hash2
6405
6406 def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6407 manufacturer='', model_name='', config_methods='\x00\x00'):
6408 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6409 attrs += build_attr_msg_type(WPS_M1)
6410 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6411 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6412 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6413 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6414 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6415 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6416 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6417 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6418 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6419 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6420 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6421 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6422 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6423 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6424 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6425 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6426 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6427 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6428 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6429 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6430 m1 = build_eap_wsc(2, eap_id, attrs)
6431 return m1, attrs
6432
6433 def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6434 dev_pw_id='\x00\x00', eap_code=1):
6435 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6436 attrs += build_attr_msg_type(WPS_M2)
6437 if e_nonce:
6438 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6439 if r_nonce:
6440 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6441 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6442 if r_pk:
6443 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6444 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6445 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6446 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6447 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6448 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6449 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6450 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6451 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6452 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6453 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6454 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6455 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6456 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6457 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6458 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6459 attrs += build_attr_authenticator(authkey, m1, attrs)
6460 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6461 return m2, attrs
6462
6463 def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6464 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6465 attrs += build_attr_msg_type(WPS_M2D)
6466 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6467 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6468 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6469 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6470 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6471 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6472 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6473 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6474 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6475 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6476 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6477 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6478 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6479 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6480 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6481 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6482 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6483 if dev_pw_id:
6484 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6485 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6486 return m2d, attrs
6487
6488 def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6489 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6490 if msg_type is not None:
6491 attrs += build_attr_msg_type(msg_type)
6492 if e_nonce:
6493 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6494 if r_nonce:
6495 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6496 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6497 return msg, attrs
6498
6499 def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6500 msg_type=WPS_WSC_NACK, eap_code=1):
6501 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6502 if msg_type is not None:
6503 attrs += build_attr_msg_type(msg_type)
6504 if e_nonce:
6505 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6506 if r_nonce:
6507 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6508 if config_error:
6509 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6510 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6511 return msg, attrs
6512
6513 def test_wps_ext(dev, apdev):
6514 """WPS against external implementation"""
6515 pin = "12345670"
6516 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6517 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6518 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6519
6520 logger.debug("Receive WSC/Start from AP")
6521 msg = get_wsc_msg(hapd)
6522 if msg['wsc_opcode'] != WSC_Start:
6523 raise Exception("Unexpected Op-Code for WSC/Start")
6524 wsc_start_id = msg['eap_identifier']
6525
6526 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6527 uuid_e = 16*b'\x11'
6528 e_nonce = 16*b'\x22'
6529 own_private, e_pk = wsc_dh_init()
6530
6531 logger.debug("Send M1 to AP")
6532 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6533 e_nonce, e_pk)
6534 send_wsc_msg(hapd, addr, m1)
6535
6536 logger.debug("Receive M2 from AP")
6537 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6538
6539 authkey,keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6540 mac_addr, e_nonce,
6541 m2_attrs[ATTR_REGISTRAR_NONCE])
6542 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6543 m2_attrs[ATTR_PUBLIC_KEY])
6544
6545 logger.debug("Send M3 to AP")
6546 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6547 attrs += build_attr_msg_type(WPS_M3)
6548 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6549 m2_attrs[ATTR_REGISTRAR_NONCE])
6550 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6551 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6552 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6553 raw_m3_attrs = attrs
6554 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6555 send_wsc_msg(hapd, addr, m3)
6556
6557 logger.debug("Receive M4 from AP")
6558 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6559
6560 logger.debug("Send M5 to AP")
6561 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6562 attrs += build_attr_msg_type(WPS_M5)
6563 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6564 m2_attrs[ATTR_REGISTRAR_NONCE])
6565 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6566 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6567 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6568 raw_m5_attrs = attrs
6569 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6570 send_wsc_msg(hapd, addr, m5)
6571
6572 logger.debug("Receive M6 from AP")
6573 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6574
6575 logger.debug("Send M7 to AP")
6576 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6577 attrs += build_attr_msg_type(WPS_M7)
6578 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6579 m2_attrs[ATTR_REGISTRAR_NONCE])
6580 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6581 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6582 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6583 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6584 raw_m7_attrs = attrs
6585 send_wsc_msg(hapd, addr, m7)
6586
6587 logger.debug("Receive M8 from AP")
6588 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6589 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6590 m8_attrs[ATTR_ENCR_SETTINGS])
6591 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred).decode())
6592
6593 logger.debug("Prepare WSC_Done")
6594 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6595 attrs += build_attr_msg_type(WPS_WSC_DONE)
6596 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6597 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6598 m2_attrs[ATTR_REGISTRAR_NONCE])
6599 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6600 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6601 # AP disconnects.
6602
6603 uuid_r = 16*b'\x33'
6604 r_nonce = 16*b'\x44'
6605
6606 eap_id = wsc_start_id
6607 logger.debug("Send WSC/Start to STA")
6608 wsc_start = build_eap_wsc(1, eap_id, b'', opcode=WSC_Start)
6609 send_wsc_msg(dev[0], bssid, wsc_start)
6610 eap_id = (eap_id + 1) % 256
6611
6612 logger.debug("Receive M1 from STA")
6613 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6614
6615 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6616 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6617 r_nonce)
6618 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6619 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6620
6621 logger.debug("Send M2 to STA")
6622 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6623 m1_attrs[ATTR_ENROLLEE_NONCE],
6624 r_nonce, uuid_r, e_pk)
6625 send_wsc_msg(dev[0], bssid, m2)
6626 eap_id = (eap_id + 1) % 256
6627
6628 logger.debug("Receive M3 from STA")
6629 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6630
6631 logger.debug("Send M4 to STA")
6632 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6633 attrs += build_attr_msg_type(WPS_M4)
6634 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6635 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6636 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6637 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6638 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6639 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6640 raw_m4_attrs = attrs
6641 m4 = build_eap_wsc(1, eap_id, attrs)
6642 send_wsc_msg(dev[0], bssid, m4)
6643 eap_id = (eap_id + 1) % 256
6644
6645 logger.debug("Receive M5 from STA")
6646 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6647
6648 logger.debug("Send M6 to STA")
6649 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6650 attrs += build_attr_msg_type(WPS_M6)
6651 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6652 m1_attrs[ATTR_ENROLLEE_NONCE])
6653 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6654 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6655 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6656 raw_m6_attrs = attrs
6657 m6 = build_eap_wsc(1, eap_id, attrs)
6658 send_wsc_msg(dev[0], bssid, m6)
6659 eap_id = (eap_id + 1) % 256
6660
6661 logger.debug("Receive M7 from STA")
6662 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6663
6664 logger.debug("Send M8 to STA")
6665 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6666 attrs += build_attr_msg_type(WPS_M8)
6667 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6668 m1_attrs[ATTR_ENROLLEE_NONCE])
6669 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6670 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6671 raw_m8_attrs = attrs
6672 m8 = build_eap_wsc(1, eap_id, attrs)
6673 send_wsc_msg(dev[0], bssid, m8)
6674 eap_id = (eap_id + 1) % 256
6675
6676 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6677 if ev is None:
6678 raise Exception("wpa_supplicant did not report credential")
6679
6680 logger.debug("Receive WSC_Done from STA")
6681 msg = get_wsc_msg(dev[0])
6682 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6683 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6684
6685 logger.debug("Send WSC_Done to AP")
6686 hapd.request("SET ext_eapol_frame_io 0")
6687 dev[0].request("SET ext_eapol_frame_io 0")
6688 send_wsc_msg(hapd, addr, wsc_done)
6689
6690 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6691 if ev is None:
6692 raise Exception("hostapd did not report WPS success")
6693
6694 dev[0].wait_connected()
6695
6696 def wps_start_kwa(dev, apdev):
6697 pin = "12345670"
6698 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6699 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6700 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6701 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6702
6703 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6704 uuid_r = 16*b'\x33'
6705 r_nonce = 16*b'\x44'
6706 own_private, e_pk = wsc_dh_init()
6707
6708 logger.debug("Receive M1 from STA")
6709 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6710 eap_id = (msg['eap_identifier'] + 1) % 256
6711
6712 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6713 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6714 r_nonce)
6715 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6716 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6717
6718 logger.debug("Send M2 to STA")
6719 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6720 m1_attrs[ATTR_ENROLLEE_NONCE],
6721 r_nonce, uuid_r, e_pk)
6722 send_wsc_msg(dev[0], bssid, m2)
6723 eap_id = (eap_id + 1) % 256
6724
6725 logger.debug("Receive M3 from STA")
6726 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6727
6728 logger.debug("Send M4 to STA")
6729 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6730 attrs += build_attr_msg_type(WPS_M4)
6731 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6732 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6733 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6734
6735 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6736
6737 def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6738 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6739 m4 = build_eap_wsc(1, eap_id, attrs)
6740 send_wsc_msg(dev[0], bssid, m4)
6741 eap_id = (eap_id + 1) % 256
6742
6743 logger.debug("Receive M5 from STA")
6744 msg = get_wsc_msg(dev[0])
6745 if msg['wsc_opcode'] != WSC_NACK:
6746 raise Exception("Unexpected message - expected WSC_Nack")
6747
6748 dev[0].request("WPS_CANCEL")
6749 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6750 dev[0].wait_disconnected()
6751
6752 def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6753 """WPS and KWA error: No KWA attribute"""
6754 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6755 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6756 # Encrypted Settings without KWA
6757 iv = 16*b'\x99'
6758 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6759 pad_len = 16 - len(data) % 16
6760 ps = pad_len * struct.pack('B', pad_len)
6761 data += ps
6762 wrapped = aes.encrypt(data)
6763 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6764 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6765
6766 def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6767 """WPS and KWA error: Data after KWA"""
6768 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6769 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6770 # Encrypted Settings and data after KWA
6771 m = hmac.new(authkey, data, hashlib.sha256)
6772 kwa = m.digest()[0:8]
6773 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6774 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6775 iv = 16*b'\x99'
6776 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6777 pad_len = 16 - len(data) % 16
6778 ps = pad_len * struct.pack('B', pad_len)
6779 data += ps
6780 wrapped = aes.encrypt(data)
6781 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6782 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6783
6784 def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6785 """WPS and KWA error: KWA mismatch"""
6786 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6787 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6788 # Encrypted Settings and KWA with incorrect value
6789 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6790 iv = 16*b'\x99'
6791 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6792 pad_len = 16 - len(data) % 16
6793 ps = pad_len * struct.pack('B', pad_len)
6794 data += ps
6795 wrapped = aes.encrypt(data)
6796 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6797 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6798
6799 def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6800 pin = "12345670"
6801 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6802 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6803 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6804 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6805
6806 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6807 uuid_r = 16*b'\x33'
6808 r_nonce = 16*b'\x44'
6809 own_private, e_pk = wsc_dh_init()
6810
6811 logger.debug("Receive M1 from STA")
6812 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6813 eap_id = (msg['eap_identifier'] + 1) % 256
6814
6815 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6816 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6817 r_nonce)
6818 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6819 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6820
6821 logger.debug("Send M2 to STA")
6822 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6823 m1_attrs[ATTR_ENROLLEE_NONCE],
6824 r_nonce, uuid_r, e_pk)
6825 send_wsc_msg(dev[0], bssid, m2)
6826 eap_id = (eap_id + 1) % 256
6827
6828 logger.debug("Receive M3 from STA")
6829 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6830
6831 logger.debug("Send M4 to STA")
6832 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6833 attrs += build_attr_msg_type(WPS_M4)
6834 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6835 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6836 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6837 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6838 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6839 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6840 raw_m4_attrs = attrs
6841 m4 = build_eap_wsc(1, eap_id, attrs)
6842 send_wsc_msg(dev[0], bssid, m4)
6843 eap_id = (eap_id + 1) % 256
6844
6845 logger.debug("Receive M5 from STA")
6846 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6847
6848 logger.debug("Send M6 to STA")
6849 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6850 attrs += build_attr_msg_type(WPS_M6)
6851 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6852 m1_attrs[ATTR_ENROLLEE_NONCE])
6853 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6854 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6855 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6856 raw_m6_attrs = attrs
6857 m6 = build_eap_wsc(1, eap_id, attrs)
6858 send_wsc_msg(dev[0], bssid, m6)
6859 eap_id = (eap_id + 1) % 256
6860
6861 logger.debug("Receive M7 from STA")
6862 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6863
6864 logger.debug("Send M8 to STA")
6865 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6866 attrs += build_attr_msg_type(WPS_M8)
6867 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6868 m1_attrs[ATTR_ENROLLEE_NONCE])
6869 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6870 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6871 raw_m8_attrs = attrs
6872 m8 = build_eap_wsc(1, eap_id, attrs)
6873 send_wsc_msg(dev[0], bssid, m8)
6874 eap_id = (eap_id + 1) % 256
6875
6876 if no_connect:
6877 logger.debug("Receive WSC_Done from STA")
6878 msg = get_wsc_msg(dev[0])
6879 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6880 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6881
6882 hapd.request("SET ext_eapol_frame_io 0")
6883 dev[0].request("SET ext_eapol_frame_io 0")
6884
6885 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6886
6887 dev[0].wait_disconnected()
6888 dev[0].request("REMOVE_NETWORK all")
6889 elif connect:
6890 logger.debug("Receive WSC_Done from STA")
6891 msg = get_wsc_msg(dev[0])
6892 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6893 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6894
6895 hapd.request("SET ext_eapol_frame_io 0")
6896 dev[0].request("SET ext_eapol_frame_io 0")
6897
6898 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6899
6900 dev[0].wait_connected()
6901 else:
6902 # Verify STA NACK's the credential
6903 msg = get_wsc_msg(dev[0])
6904 if msg['wsc_opcode'] != WSC_NACK:
6905 raise Exception("Unexpected message - expected WSC_Nack")
6906 dev[0].request("WPS_CANCEL")
6907 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6908 dev[0].wait_disconnected()
6909
6910 def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6911 encr_type='\x00\x08', nw_key="12345678",
6912 mac_addr='\x00\x00\x00\x00\x00\x00'):
6913 attrs = b''
6914 if nw_idx is not None:
6915 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6916 if ssid is not None:
6917 attrs += build_wsc_attr(ATTR_SSID, ssid)
6918 if auth_type is not None:
6919 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6920 if encr_type is not None:
6921 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6922 if nw_key is not None:
6923 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6924 if mac_addr is not None:
6925 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6926 return build_wsc_attr(ATTR_CRED, attrs)
6927
6928 def test_wps_ext_cred_proto_success(dev, apdev):
6929 """WPS and Credential: success"""
6930 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6931 m8_cred = build_cred(mac_addr=mac_addr)
6932 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6933
6934 def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6935 """WPS and Credential: MAC Address mismatch"""
6936 m8_cred = build_cred()
6937 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6938
6939 def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6940 """WPS and Credential: zeropadded attributes"""
6941 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6942 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6943 nw_key="12345678\x00")
6944 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6945
6946 def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6947 """WPS and Credential: SSID missing"""
6948 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6949 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6950 wps_run_cred_proto(dev, apdev, m8_cred)
6951
6952 def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6953 """WPS and Credential: Zero-length SSID"""
6954 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6955 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6956 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6957
6958 def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6959 """WPS and Credential: Auth Type missing"""
6960 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6961 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6962 wps_run_cred_proto(dev, apdev, m8_cred)
6963
6964 def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6965 """WPS and Credential: Encr Type missing"""
6966 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6967 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6968 wps_run_cred_proto(dev, apdev, m8_cred)
6969
6970 def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6971 """WPS and Credential: Network Key missing"""
6972 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6973 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6974 wps_run_cred_proto(dev, apdev, m8_cred)
6975
6976 def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6977 """WPS and Credential: Network Key missing (open)"""
6978 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6979 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6980 encr_type='\x00\x01', nw_key=None, ssid="foo")
6981 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6982
6983 def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6984 """WPS and Credential: MAC Address missing"""
6985 m8_cred = build_cred(mac_addr=None)
6986 wps_run_cred_proto(dev, apdev, m8_cred)
6987
6988 def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
6989 """WPS and Credential: Invalid Encr Type"""
6990 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6991 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
6992 wps_run_cred_proto(dev, apdev, m8_cred)
6993
6994 def test_wps_ext_cred_proto_missing_cred(dev, apdev):
6995 """WPS and Credential: Missing Credential"""
6996 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6997 m8_cred = b''
6998 wps_run_cred_proto(dev, apdev, m8_cred)
6999
7000 def test_wps_ext_proto_m2_no_public_key(dev, apdev):
7001 """WPS and no Public Key in M2"""
7002 pin = "12345670"
7003 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7004 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7005 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7006 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7007
7008 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7009 uuid_r = 16*b'\x33'
7010 r_nonce = 16*b'\x44'
7011 own_private, e_pk = wsc_dh_init()
7012
7013 logger.debug("Receive M1 from STA")
7014 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7015 eap_id = (msg['eap_identifier'] + 1) % 256
7016
7017 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7018 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7019 r_nonce)
7020 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7021 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7022
7023 logger.debug("Send M2 to STA")
7024 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7025 m1_attrs[ATTR_ENROLLEE_NONCE],
7026 r_nonce, uuid_r, None)
7027 send_wsc_msg(dev[0], bssid, m2)
7028 eap_id = (eap_id + 1) % 256
7029
7030 # Verify STA NACK's the credential
7031 msg = get_wsc_msg(dev[0])
7032 if msg['wsc_opcode'] != WSC_NACK:
7033 raise Exception("Unexpected message - expected WSC_Nack")
7034 dev[0].request("WPS_CANCEL")
7035 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7036 dev[0].wait_disconnected()
7037
7038 def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
7039 """WPS and invalid Public Key in M2"""
7040 pin = "12345670"
7041 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7042 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7043 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7044 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7045
7046 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7047 uuid_r = 16*b'\x33'
7048 r_nonce = 16*b'\x44'
7049 own_private, e_pk = wsc_dh_init()
7050
7051 logger.debug("Receive M1 from STA")
7052 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7053 eap_id = (msg['eap_identifier'] + 1) % 256
7054
7055 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7056 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7057 r_nonce)
7058 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7059 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7060
7061 logger.debug("Send M2 to STA")
7062 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7063 m1_attrs[ATTR_ENROLLEE_NONCE],
7064 r_nonce, uuid_r, 192*b'\xff')
7065 send_wsc_msg(dev[0], bssid, m2)
7066 eap_id = (eap_id + 1) % 256
7067
7068 # Verify STA NACK's the credential
7069 msg = get_wsc_msg(dev[0])
7070 if msg['wsc_opcode'] != WSC_NACK:
7071 raise Exception("Unexpected message - expected WSC_Nack")
7072 dev[0].request("WPS_CANCEL")
7073 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7074 dev[0].wait_disconnected()
7075
7076 def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7077 """WPS and Public Key OOM in M2"""
7078 pin = "12345670"
7079 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7080 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7081 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7082 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7083
7084 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7085 uuid_r = 16*b'\x33'
7086 r_nonce = 16*b'\x44'
7087 own_private, e_pk = wsc_dh_init()
7088
7089 logger.debug("Receive M1 from STA")
7090 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7091 eap_id = (msg['eap_identifier'] + 1) % 256
7092
7093 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7094 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7095 r_nonce)
7096 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7097 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7098
7099 logger.debug("Send M2 to STA")
7100 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7101 m1_attrs[ATTR_ENROLLEE_NONCE],
7102 r_nonce, uuid_r, e_pk)
7103 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7104 send_wsc_msg(dev[0], bssid, m2)
7105 eap_id = (eap_id + 1) % 256
7106
7107 # Verify STA NACK's the credential
7108 msg = get_wsc_msg(dev[0])
7109 if msg['wsc_opcode'] != WSC_NACK:
7110 raise Exception("Unexpected message - expected WSC_Nack")
7111 dev[0].request("WPS_CANCEL")
7112 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7113 dev[0].wait_disconnected()
7114
7115 def test_wps_ext_proto_nack_m3(dev, apdev):
7116 """WPS and NACK M3"""
7117 pin = "12345670"
7118 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7119 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7120 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7121 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7122
7123 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7124 uuid_r = 16*b'\x33'
7125 r_nonce = 16*b'\x44'
7126 own_private, e_pk = wsc_dh_init()
7127
7128 logger.debug("Receive M1 from STA")
7129 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7130 eap_id = (msg['eap_identifier'] + 1) % 256
7131
7132 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7133 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7134 r_nonce)
7135 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7136 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7137
7138 logger.debug("Send M2 to STA")
7139 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7140 m1_attrs[ATTR_ENROLLEE_NONCE],
7141 r_nonce, uuid_r, e_pk)
7142 send_wsc_msg(dev[0], bssid, m2)
7143 eap_id = (eap_id + 1) % 256
7144
7145 logger.debug("Receive M3 from STA")
7146 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7147
7148 logger.debug("Send NACK to STA")
7149 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7150 r_nonce, config_error='\x01\x23')
7151 send_wsc_msg(dev[0], bssid, msg)
7152 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7153 if ev is None:
7154 raise Exception("Failure not reported")
7155 if "msg=7 config_error=291" not in ev:
7156 raise Exception("Unexpected failure reason: " + ev)
7157
7158 def test_wps_ext_proto_nack_m5(dev, apdev):
7159 """WPS and NACK M5"""
7160 pin = "12345670"
7161 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7162 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7163 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7164 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7165
7166 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7167 uuid_r = 16*b'\x33'
7168 r_nonce = 16*b'\x44'
7169 own_private, e_pk = wsc_dh_init()
7170
7171 logger.debug("Receive M1 from STA")
7172 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7173 eap_id = (msg['eap_identifier'] + 1) % 256
7174
7175 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7176 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7177 r_nonce)
7178 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7179 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7180
7181 logger.debug("Send M2 to STA")
7182 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7183 m1_attrs[ATTR_ENROLLEE_NONCE],
7184 r_nonce, uuid_r, e_pk)
7185 send_wsc_msg(dev[0], bssid, m2)
7186 eap_id = (eap_id + 1) % 256
7187
7188 logger.debug("Receive M3 from STA")
7189 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7190
7191 logger.debug("Send M4 to STA")
7192 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7193 attrs += build_attr_msg_type(WPS_M4)
7194 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7195 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7196 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7197 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7198 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7199 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7200 raw_m4_attrs = attrs
7201 m4 = build_eap_wsc(1, eap_id, attrs)
7202 send_wsc_msg(dev[0], bssid, m4)
7203 eap_id = (eap_id + 1) % 256
7204
7205 logger.debug("Receive M5 from STA")
7206 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7207
7208 logger.debug("Send NACK to STA")
7209 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7210 r_nonce, config_error='\x01\x24')
7211 send_wsc_msg(dev[0], bssid, msg)
7212 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7213 if ev is None:
7214 raise Exception("Failure not reported")
7215 if "msg=9 config_error=292" not in ev:
7216 raise Exception("Unexpected failure reason: " + ev)
7217
7218 def wps_nack_m3(dev, apdev):
7219 pin = "00000000"
7220 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7221 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7222 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7223 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7224
7225 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7226 uuid_r = 16*b'\x33'
7227 r_nonce = 16*b'\x44'
7228 own_private, e_pk = wsc_dh_init()
7229
7230 logger.debug("Receive M1 from STA")
7231 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7232 eap_id = (msg['eap_identifier'] + 1) % 256
7233
7234 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7235 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7236 r_nonce)
7237 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7238 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7239
7240 logger.debug("Send M2 to STA")
7241 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7242 m1_attrs[ATTR_ENROLLEE_NONCE],
7243 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7244 send_wsc_msg(dev[0], bssid, m2)
7245 eap_id = (eap_id + 1) % 256
7246
7247 logger.debug("Receive M3 from STA")
7248 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7249 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7250
7251 def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7252 """WPS and NACK M3 missing Config Error"""
7253 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7254 logger.debug("Send NACK to STA")
7255 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7256 send_wsc_msg(dev[0], bssid, msg)
7257 dev[0].request("WPS_CANCEL")
7258 dev[0].wait_disconnected()
7259 dev[0].flush_scan_cache()
7260
7261 def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7262 """WPS and NACK M3 missing E-Nonce"""
7263 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7264 logger.debug("Send NACK to STA")
7265 msg, attrs = build_nack(eap_id, None, r_nonce)
7266 send_wsc_msg(dev[0], bssid, msg)
7267 dev[0].request("WPS_CANCEL")
7268 dev[0].wait_disconnected()
7269 dev[0].flush_scan_cache()
7270
7271 def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7272 """WPS and NACK M3 E-Nonce mismatch"""
7273 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7274 logger.debug("Send NACK to STA")
7275 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7276 send_wsc_msg(dev[0], bssid, msg)
7277 dev[0].request("WPS_CANCEL")
7278 dev[0].wait_disconnected()
7279 dev[0].flush_scan_cache()
7280
7281 def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7282 """WPS and NACK M3 missing R-Nonce"""
7283 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7284 logger.debug("Send NACK to STA")
7285 msg, attrs = build_nack(eap_id, e_nonce, None)
7286 send_wsc_msg(dev[0], bssid, msg)
7287 dev[0].request("WPS_CANCEL")
7288 dev[0].wait_disconnected()
7289 dev[0].flush_scan_cache()
7290
7291 def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7292 """WPS and NACK M3 R-Nonce mismatch"""
7293 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7294 logger.debug("Send NACK to STA")
7295 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7296 send_wsc_msg(dev[0], bssid, msg)
7297 dev[0].request("WPS_CANCEL")
7298 dev[0].wait_disconnected()
7299 dev[0].flush_scan_cache()
7300
7301 def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7302 """WPS and NACK M3 no Message Type"""
7303 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7304 logger.debug("Send NACK to STA")
7305 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7306 send_wsc_msg(dev[0], bssid, msg)
7307 dev[0].request("WPS_CANCEL")
7308 dev[0].wait_disconnected()
7309 dev[0].flush_scan_cache()
7310
7311 def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7312 """WPS and NACK M3 invalid Message Type"""
7313 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7314 logger.debug("Send NACK to STA")
7315 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7316 send_wsc_msg(dev[0], bssid, msg)
7317 dev[0].request("WPS_CANCEL")
7318 dev[0].wait_disconnected()
7319 dev[0].flush_scan_cache()
7320
7321 def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7322 """WPS and NACK M3 invalid attribute"""
7323 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7324 logger.debug("Send NACK to STA")
7325 attrs = b'\x10\x10\x00'
7326 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7327 send_wsc_msg(dev[0], bssid, msg)
7328 dev[0].request("WPS_CANCEL")
7329 dev[0].wait_disconnected()
7330 dev[0].flush_scan_cache()
7331
7332 def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7333 """WPS and ACK M3 missing E-Nonce"""
7334 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7335 logger.debug("Send NACK to STA")
7336 msg, attrs = build_ack(eap_id, None, r_nonce)
7337 send_wsc_msg(dev[0], bssid, msg)
7338 dev[0].request("WPS_CANCEL")
7339 dev[0].wait_disconnected()
7340 dev[0].flush_scan_cache()
7341
7342 def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7343 """WPS and ACK M3 E-Nonce mismatch"""
7344 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7345 logger.debug("Send NACK to STA")
7346 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7347 send_wsc_msg(dev[0], bssid, msg)
7348 dev[0].request("WPS_CANCEL")
7349 dev[0].wait_disconnected()
7350 dev[0].flush_scan_cache()
7351
7352 def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7353 """WPS and ACK M3 missing R-Nonce"""
7354 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7355 logger.debug("Send NACK to STA")
7356 msg, attrs = build_ack(eap_id, e_nonce, None)
7357 send_wsc_msg(dev[0], bssid, msg)
7358 dev[0].request("WPS_CANCEL")
7359 dev[0].wait_disconnected()
7360 dev[0].flush_scan_cache()
7361
7362 def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7363 """WPS and ACK M3 R-Nonce mismatch"""
7364 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7365 logger.debug("Send NACK to STA")
7366 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7367 send_wsc_msg(dev[0], bssid, msg)
7368 dev[0].request("WPS_CANCEL")
7369 dev[0].wait_disconnected()
7370 dev[0].flush_scan_cache()
7371
7372 def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7373 """WPS and ACK M3 no Message Type"""
7374 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7375 logger.debug("Send NACK to STA")
7376 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7377 send_wsc_msg(dev[0], bssid, msg)
7378 dev[0].request("WPS_CANCEL")
7379 dev[0].wait_disconnected()
7380 dev[0].flush_scan_cache()
7381
7382 def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7383 """WPS and ACK M3 invalid Message Type"""
7384 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7385 logger.debug("Send NACK to STA")
7386 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7387 send_wsc_msg(dev[0], bssid, msg)
7388 dev[0].request("WPS_CANCEL")
7389 dev[0].wait_disconnected()
7390 dev[0].flush_scan_cache()
7391
7392 def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7393 """WPS and ACK M3 invalid attribute"""
7394 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7395 logger.debug("Send ACK to STA")
7396 attrs = b'\x10\x10\x00'
7397 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7398 send_wsc_msg(dev[0], bssid, msg)
7399 dev[0].request("WPS_CANCEL")
7400 dev[0].wait_disconnected()
7401 dev[0].flush_scan_cache()
7402
7403 def test_wps_ext_proto_ack_m3(dev, apdev):
7404 """WPS and ACK M3"""
7405 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7406 logger.debug("Send ACK to STA")
7407 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7408 send_wsc_msg(dev[0], bssid, msg)
7409 dev[0].request("WPS_CANCEL")
7410 dev[0].wait_disconnected()
7411 dev[0].flush_scan_cache()
7412
7413 def wps_to_m3_helper(dev, apdev):
7414 pin = "12345670"
7415 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7416 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7417 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7418 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7419
7420 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7421 uuid_r = 16*b'\x33'
7422 r_nonce = 16*b'\x44'
7423 own_private, e_pk = wsc_dh_init()
7424
7425 logger.debug("Receive M1 from STA")
7426 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7427 eap_id = (msg['eap_identifier'] + 1) % 256
7428
7429 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7430 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7431 r_nonce)
7432 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7433 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7434
7435 logger.debug("Send M2 to STA")
7436 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7437 m1_attrs[ATTR_ENROLLEE_NONCE],
7438 r_nonce, uuid_r, e_pk)
7439 send_wsc_msg(dev[0], bssid, m2)
7440 eap_id = (eap_id + 1) % 256
7441
7442 logger.debug("Receive M3 from STA")
7443 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7444 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7445
7446 def wps_to_m3(dev, apdev):
7447 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)
7448 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7449
7450 def wps_to_m5(dev, apdev):
7451 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)
7452
7453 logger.debug("Send M4 to STA")
7454 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7455 attrs += build_attr_msg_type(WPS_M4)
7456 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7457 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7458 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7459 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7460 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7461 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7462 raw_m4_attrs = attrs
7463 m4 = build_eap_wsc(1, eap_id, attrs)
7464 send_wsc_msg(dev[0], bssid, m4)
7465 eap_id = (eap_id + 1) % 256
7466
7467 logger.debug("Receive M5 from STA")
7468 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7469
7470 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7471
7472 def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7473 """WPS and no R-Hash1 in M4"""
7474 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7475
7476 logger.debug("Send M4 to STA")
7477 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7478 attrs += build_attr_msg_type(WPS_M4)
7479 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7480 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7481 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7482 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7483 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7484 attrs += build_attr_authenticator(authkey, m3, attrs)
7485 m4 = build_eap_wsc(1, eap_id, attrs)
7486 send_wsc_msg(dev[0], bssid, m4)
7487 eap_id = (eap_id + 1) % 256
7488
7489 logger.debug("Receive M5 (NACK) from STA")
7490 msg = get_wsc_msg(dev[0])
7491 if msg['wsc_opcode'] != WSC_NACK:
7492 raise Exception("Unexpected message - expected WSC_Nack")
7493
7494 dev[0].request("WPS_CANCEL")
7495 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7496 dev[0].wait_disconnected()
7497
7498 def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7499 """WPS and no R-Hash2 in M4"""
7500 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7501
7502 logger.debug("Send M4 to STA")
7503 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7504 attrs += build_attr_msg_type(WPS_M4)
7505 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7506 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7507 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7508 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7509 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7510 attrs += build_attr_authenticator(authkey, m3, attrs)
7511 m4 = build_eap_wsc(1, eap_id, attrs)
7512 send_wsc_msg(dev[0], bssid, m4)
7513 eap_id = (eap_id + 1) % 256
7514
7515 logger.debug("Receive M5 (NACK) from STA")
7516 msg = get_wsc_msg(dev[0])
7517 if msg['wsc_opcode'] != WSC_NACK:
7518 raise Exception("Unexpected message - expected WSC_Nack")
7519
7520 dev[0].request("WPS_CANCEL")
7521 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7522 dev[0].wait_disconnected()
7523
7524 def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7525 """WPS and no R-SNonce1 in M4"""
7526 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7527
7528 logger.debug("Send M4 to STA")
7529 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7530 attrs += build_attr_msg_type(WPS_M4)
7531 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7532 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7533 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7534 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7535 data = b''
7536 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7537 attrs += build_attr_authenticator(authkey, m3, attrs)
7538 m4 = build_eap_wsc(1, eap_id, attrs)
7539 send_wsc_msg(dev[0], bssid, m4)
7540 eap_id = (eap_id + 1) % 256
7541
7542 logger.debug("Receive M5 (NACK) from STA")
7543 msg = get_wsc_msg(dev[0])
7544 if msg['wsc_opcode'] != WSC_NACK:
7545 raise Exception("Unexpected message - expected WSC_Nack")
7546
7547 dev[0].request("WPS_CANCEL")
7548 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7549 dev[0].wait_disconnected()
7550
7551 def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7552 """WPS and invalid pad string in M4"""
7553 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7554
7555 logger.debug("Send M4 to STA")
7556 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7557 attrs += build_attr_msg_type(WPS_M4)
7558 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7559 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7560 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7561 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7562
7563 m = hmac.new(authkey, data, hashlib.sha256)
7564 kwa = m.digest()[0:8]
7565 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7566 iv = 16*b'\x99'
7567 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7568 pad_len = 16 - len(data) % 16
7569 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7570 data += ps
7571 wrapped = aes.encrypt(data)
7572 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7573
7574 attrs += build_attr_authenticator(authkey, m3, attrs)
7575 m4 = build_eap_wsc(1, eap_id, attrs)
7576 send_wsc_msg(dev[0], bssid, m4)
7577 eap_id = (eap_id + 1) % 256
7578
7579 logger.debug("Receive M5 (NACK) from STA")
7580 msg = get_wsc_msg(dev[0])
7581 if msg['wsc_opcode'] != WSC_NACK:
7582 raise Exception("Unexpected message - expected WSC_Nack")
7583
7584 dev[0].request("WPS_CANCEL")
7585 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7586 dev[0].wait_disconnected()
7587
7588 def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7589 """WPS and invalid pad value in M4"""
7590 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7591
7592 logger.debug("Send M4 to STA")
7593 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7594 attrs += build_attr_msg_type(WPS_M4)
7595 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7596 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7597 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7598 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7599
7600 m = hmac.new(authkey, data, hashlib.sha256)
7601 kwa = m.digest()[0:8]
7602 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7603 iv = 16*b'\x99'
7604 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7605 pad_len = 16 - len(data) % 16
7606 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7607 data += ps
7608 wrapped = aes.encrypt(data)
7609 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7610
7611 attrs += build_attr_authenticator(authkey, m3, attrs)
7612 m4 = build_eap_wsc(1, eap_id, attrs)
7613 send_wsc_msg(dev[0], bssid, m4)
7614 eap_id = (eap_id + 1) % 256
7615
7616 logger.debug("Receive M5 (NACK) from STA")
7617 msg = get_wsc_msg(dev[0])
7618 if msg['wsc_opcode'] != WSC_NACK:
7619 raise Exception("Unexpected message - expected WSC_Nack")
7620
7621 dev[0].request("WPS_CANCEL")
7622 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7623 dev[0].wait_disconnected()
7624
7625 def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7626 """WPS and no Encr Settings in M4"""
7627 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7628
7629 logger.debug("Send M4 to STA")
7630 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7631 attrs += build_attr_msg_type(WPS_M4)
7632 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7633 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7634 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7635 attrs += build_attr_authenticator(authkey, m3, attrs)
7636 m4 = build_eap_wsc(1, eap_id, attrs)
7637 send_wsc_msg(dev[0], bssid, m4)
7638 eap_id = (eap_id + 1) % 256
7639
7640 logger.debug("Receive M5 (NACK) from STA")
7641 msg = get_wsc_msg(dev[0])
7642 if msg['wsc_opcode'] != WSC_NACK:
7643 raise Exception("Unexpected message - expected WSC_Nack")
7644
7645 dev[0].request("WPS_CANCEL")
7646 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7647 dev[0].wait_disconnected()
7648
7649 def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7650 """WPS and no R-SNonce2 in M6"""
7651 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7652
7653 logger.debug("Send M6 to STA")
7654 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7655 attrs += build_attr_msg_type(WPS_M6)
7656 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7657 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7658 data = b''
7659 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7660 attrs += build_attr_authenticator(authkey, m5, attrs)
7661 m6 = build_eap_wsc(1, eap_id, attrs)
7662 send_wsc_msg(dev[0], bssid, m6)
7663 eap_id = (eap_id + 1) % 256
7664
7665 logger.debug("Receive M7 (NACK) from STA")
7666 msg = get_wsc_msg(dev[0])
7667 if msg['wsc_opcode'] != WSC_NACK:
7668 raise Exception("Unexpected message - expected WSC_Nack")
7669
7670 dev[0].request("WPS_CANCEL")
7671 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7672 dev[0].wait_disconnected()
7673
7674 def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7675 """WPS and no Encr Settings in M6"""
7676 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7677
7678 logger.debug("Send M6 to STA")
7679 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7680 attrs += build_attr_msg_type(WPS_M6)
7681 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7682 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7683 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7684 attrs += build_attr_authenticator(authkey, m5, attrs)
7685 m6 = build_eap_wsc(1, eap_id, attrs)
7686 send_wsc_msg(dev[0], bssid, m6)
7687 eap_id = (eap_id + 1) % 256
7688
7689 logger.debug("Receive M7 (NACK) from STA")
7690 msg = get_wsc_msg(dev[0])
7691 if msg['wsc_opcode'] != WSC_NACK:
7692 raise Exception("Unexpected message - expected WSC_Nack")
7693
7694 dev[0].request("WPS_CANCEL")
7695 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7696 dev[0].wait_disconnected()
7697
7698 def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7699 """WPS and no Encr Settings in M6"""
7700 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7701
7702 logger.debug("Send M6 to STA")
7703 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7704 attrs += build_attr_msg_type(WPS_M6)
7705 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7706 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7707 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7708 attrs += build_attr_authenticator(authkey, m5, attrs)
7709 raw_m6_attrs = attrs
7710 m6 = build_eap_wsc(1, eap_id, attrs)
7711 send_wsc_msg(dev[0], bssid, m6)
7712 eap_id = (eap_id + 1) % 256
7713
7714 logger.debug("Receive M7 from STA")
7715 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7716
7717 logger.debug("Send M8 to STA")
7718 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7719 attrs += build_attr_msg_type(WPS_M8)
7720 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7721 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7722 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7723 raw_m8_attrs = attrs
7724 m8 = build_eap_wsc(1, eap_id, attrs)
7725 send_wsc_msg(dev[0], bssid, m8)
7726
7727 logger.debug("Receive WSC_Done (NACK) from STA")
7728 msg = get_wsc_msg(dev[0])
7729 if msg['wsc_opcode'] != WSC_NACK:
7730 raise Exception("Unexpected message - expected WSC_Nack")
7731
7732 dev[0].request("WPS_CANCEL")
7733 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7734 dev[0].wait_disconnected()
7735
7736 def wps_start_ext_reg(apdev, dev):
7737 addr = dev.own_addr()
7738 bssid = apdev['bssid']
7739 ssid = "test-wps-conf"
7740 appin = "12345670"
7741 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
7742 "wpa_passphrase": "12345678", "wpa": "2",
7743 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7744 "ap_pin": appin }
7745 hapd = hostapd.add_ap(apdev, params)
7746
7747 dev.scan_for_bss(bssid, freq="2412")
7748 hapd.request("SET ext_eapol_frame_io 1")
7749 dev.request("SET ext_eapol_frame_io 1")
7750
7751 dev.request("WPS_REG " + bssid + " " + appin)
7752
7753 return addr,bssid,hapd
7754
7755 def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7756 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7757 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7758 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7759
7760 logger.debug("Receive M1 from AP")
7761 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7762 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7763 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7764 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7765
7766 appin = '12345670'
7767 uuid_r = 16*b'\x33'
7768 r_nonce = 16*b'\x44'
7769 own_private, r_pk = wsc_dh_init()
7770 authkey,keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7771 r_nonce)
7772 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7773
7774 logger.debug("Send M2 to AP")
7775 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7776 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7777 send_wsc_msg(hapd, addr, m2)
7778
7779 logger.debug("Receive M3 from AP")
7780 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7781
7782 logger.debug("Send M4 to AP")
7783 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7784 attrs += build_attr_msg_type(WPS_M4)
7785 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7786 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7787 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7788 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7789 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7790 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7791 raw_m4_attrs = attrs
7792 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7793 send_wsc_msg(hapd, addr, m4)
7794
7795 logger.debug("Receive M5 from AP")
7796 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7797
7798 logger.debug("Send M6 to STA")
7799 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7800 attrs += build_attr_msg_type(WPS_M6)
7801 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7802 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7803 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7804 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7805 raw_m6_attrs = attrs
7806 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7807 send_wsc_msg(hapd, addr, m6)
7808
7809 logger.debug("Receive M7 from AP")
7810 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7811
7812 logger.debug("Send M8 to STA")
7813 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7814 attrs += build_attr_msg_type(WPS_M8)
7815 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7816 if ap_settings:
7817 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7818 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7819 raw_m8_attrs = attrs
7820 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7821 send_wsc_msg(hapd, addr, m8)
7822
7823 if success:
7824 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7825 if ev is None:
7826 raise Exception("New AP settings not reported")
7827 logger.debug("Receive WSC_Done from AP")
7828 msg = get_wsc_msg(hapd)
7829 if msg['wsc_opcode'] != WSC_Done:
7830 raise Exception("Unexpected message - expected WSC_Done")
7831
7832 logger.debug("Send WSC_ACK to AP")
7833 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7834 eap_code=2)
7835 send_wsc_msg(hapd, addr, ack)
7836 dev[0].wait_disconnected()
7837 else:
7838 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7839 if ev is None:
7840 raise Exception("WPS failure not reported")
7841 logger.debug("Receive WSC_NACK from AP")
7842 msg = get_wsc_msg(hapd)
7843 if msg['wsc_opcode'] != WSC_NACK:
7844 raise Exception("Unexpected message - expected WSC_NACK")
7845
7846 logger.debug("Send WSC_NACK to AP")
7847 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7848 eap_code=2)
7849 send_wsc_msg(hapd, addr, nack)
7850 dev[0].wait_disconnected()
7851
7852 def test_wps_ext_ap_settings_success(dev, apdev):
7853 """WPS and AP Settings: success"""
7854 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7855 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7856 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7857 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7858 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7859 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7860 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7861
7862 @remote_compatible
7863 def test_wps_ext_ap_settings_missing(dev, apdev):
7864 """WPS and AP Settings: missing"""
7865 wps_run_ap_settings_proto(dev, apdev, None, False)
7866
7867 @remote_compatible
7868 def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7869 """WPS and AP Settings: MAC Address mismatch"""
7870 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7871 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7872 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7873 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7874 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7875 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7876 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7877
7878 @remote_compatible
7879 def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7880 """WPS and AP Settings: missing MAC Address"""
7881 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7882 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7883 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7884 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7885 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7886 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7887
7888 @remote_compatible
7889 def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7890 """WPS and AP Settings: reject Encr Type"""
7891 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7892 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7893 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7894 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7895 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7896 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7897 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7898
7899 @remote_compatible
7900 def test_wps_ext_ap_settings_m2d(dev, apdev):
7901 """WPS and AP Settings: M2D"""
7902 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7903 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7904 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7905
7906 logger.debug("Receive M1 from AP")
7907 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7908 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7909
7910 r_nonce = 16*'\x44'
7911 uuid_r = 16*'\x33'
7912
7913 logger.debug("Send M2D to AP")
7914 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7915 e_nonce, r_nonce, uuid_r,
7916 dev_pw_id='\x00\x00', eap_code=2)
7917 send_wsc_msg(hapd, addr, m2d)
7918
7919 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7920 if ev is None:
7921 raise Exception("M2D not reported")
7922
7923 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7924
7925 def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7926 logger.debug("Receive WSC_NACK from AP")
7927 msg = get_wsc_msg(hapd)
7928 if msg['wsc_opcode'] != WSC_NACK:
7929 raise Exception("Unexpected message - expected WSC_NACK")
7930
7931 logger.debug("Send WSC_NACK to AP")
7932 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7933 eap_code=2)
7934 send_wsc_msg(hapd, dev.own_addr(), nack)
7935 dev.wait_disconnected()
7936
7937 @remote_compatible
7938 def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7939 """WPS proto: M3 missing E-Hash1"""
7940 pin = "12345670"
7941 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7942 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7943 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7944
7945 logger.debug("Receive WSC/Start from AP")
7946 msg = get_wsc_msg(hapd)
7947 if msg['wsc_opcode'] != WSC_Start:
7948 raise Exception("Unexpected Op-Code for WSC/Start")
7949
7950 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7951 uuid_e = 16*b'\x11'
7952 e_nonce = 16*b'\x22'
7953 own_private, e_pk = wsc_dh_init()
7954
7955 logger.debug("Send M1 to AP")
7956 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7957 e_nonce, e_pk)
7958 send_wsc_msg(hapd, addr, m1)
7959
7960 logger.debug("Receive M2 from AP")
7961 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7962 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7963 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7964
7965 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7966 r_nonce)
7967 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7968
7969 logger.debug("Send M3 to AP")
7970 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7971 attrs += build_attr_msg_type(WPS_M3)
7972 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7973 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7974 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7975 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7976 raw_m3_attrs = attrs
7977 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7978 send_wsc_msg(hapd, addr, m3)
7979
7980 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7981
7982 @remote_compatible
7983 def test_wps_ext_m3_missing_e_hash2(dev, apdev):
7984 """WPS proto: M3 missing E-Hash2"""
7985 pin = "12345670"
7986 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7987 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7988 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7989
7990 logger.debug("Receive WSC/Start from AP")
7991 msg = get_wsc_msg(hapd)
7992 if msg['wsc_opcode'] != WSC_Start:
7993 raise Exception("Unexpected Op-Code for WSC/Start")
7994
7995 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7996 uuid_e = 16*b'\x11'
7997 e_nonce = 16*b'\x22'
7998 own_private, e_pk = wsc_dh_init()
7999
8000 logger.debug("Send M1 to AP")
8001 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8002 e_nonce, e_pk)
8003 send_wsc_msg(hapd, addr, m1)
8004
8005 logger.debug("Receive M2 from AP")
8006 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8007 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8008 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8009
8010 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8011 r_nonce)
8012 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8013
8014 logger.debug("Send M3 to AP")
8015 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8016 attrs += build_attr_msg_type(WPS_M3)
8017 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8018 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8019 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8020 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8021 raw_m3_attrs = attrs
8022 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8023 send_wsc_msg(hapd, addr, m3)
8024
8025 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8026
8027 @remote_compatible
8028 def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
8029 """WPS proto: M5 missing E-SNonce1"""
8030 pin = "12345670"
8031 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8032 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8033 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8034
8035 logger.debug("Receive WSC/Start from AP")
8036 msg = get_wsc_msg(hapd)
8037 if msg['wsc_opcode'] != WSC_Start:
8038 raise Exception("Unexpected Op-Code for WSC/Start")
8039
8040 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8041 uuid_e = 16*b'\x11'
8042 e_nonce = 16*b'\x22'
8043 own_private, e_pk = wsc_dh_init()
8044
8045 logger.debug("Send M1 to AP")
8046 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8047 e_nonce, e_pk)
8048 send_wsc_msg(hapd, addr, m1)
8049
8050 logger.debug("Receive M2 from AP")
8051 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8052 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8053 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8054
8055 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8056 r_nonce)
8057 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8058
8059 logger.debug("Send M3 to AP")
8060 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8061 attrs += build_attr_msg_type(WPS_M3)
8062 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8063 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8064 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8065 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8066 raw_m3_attrs = attrs
8067 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8068 send_wsc_msg(hapd, addr, m3)
8069
8070 logger.debug("Receive M4 from AP")
8071 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8072
8073 logger.debug("Send M5 to AP")
8074 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8075 attrs += build_attr_msg_type(WPS_M5)
8076 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8077 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8078 data = b''
8079 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8080 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8081 raw_m5_attrs = attrs
8082 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8083 send_wsc_msg(hapd, addr, m5)
8084
8085 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8086
8087 @remote_compatible
8088 def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8089 """WPS proto: M5 E-SNonce1 mismatch"""
8090 pin = "12345670"
8091 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8092 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8093 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8094
8095 logger.debug("Receive WSC/Start from AP")
8096 msg = get_wsc_msg(hapd)
8097 if msg['wsc_opcode'] != WSC_Start:
8098 raise Exception("Unexpected Op-Code for WSC/Start")
8099
8100 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8101 uuid_e = 16*b'\x11'
8102 e_nonce = 16*b'\x22'
8103 own_private, e_pk = wsc_dh_init()
8104
8105 logger.debug("Send M1 to AP")
8106 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8107 e_nonce, e_pk)
8108 send_wsc_msg(hapd, addr, m1)
8109
8110 logger.debug("Receive M2 from AP")
8111 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8112 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8113 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8114
8115 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8116 r_nonce)
8117 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8118
8119 logger.debug("Send M3 to AP")
8120 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8121 attrs += build_attr_msg_type(WPS_M3)
8122 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8123 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8124 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8125 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8126 raw_m3_attrs = attrs
8127 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8128 send_wsc_msg(hapd, addr, m3)
8129
8130 logger.debug("Receive M4 from AP")
8131 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8132
8133 logger.debug("Send M5 to AP")
8134 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8135 attrs += build_attr_msg_type(WPS_M5)
8136 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8137 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8138 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8139 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8140 raw_m5_attrs = attrs
8141 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8142 send_wsc_msg(hapd, addr, m5)
8143
8144 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8145
8146 def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8147 """WPS proto: M7 missing E-SNonce2"""
8148 pin = "12345670"
8149 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8150 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8151 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8152
8153 logger.debug("Receive WSC/Start from AP")
8154 msg = get_wsc_msg(hapd)
8155 if msg['wsc_opcode'] != WSC_Start:
8156 raise Exception("Unexpected Op-Code for WSC/Start")
8157
8158 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8159 uuid_e = 16*b'\x11'
8160 e_nonce = 16*b'\x22'
8161 own_private, e_pk = wsc_dh_init()
8162
8163 logger.debug("Send M1 to AP")
8164 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8165 e_nonce, e_pk)
8166 send_wsc_msg(hapd, addr, m1)
8167
8168 logger.debug("Receive M2 from AP")
8169 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8170 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8171 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8172
8173 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8174 r_nonce)
8175 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8176
8177 logger.debug("Send M3 to AP")
8178 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8179 attrs += build_attr_msg_type(WPS_M3)
8180 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8181 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8182 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8183 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8184 raw_m3_attrs = attrs
8185 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8186 send_wsc_msg(hapd, addr, m3)
8187
8188 logger.debug("Receive M4 from AP")
8189 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8190
8191 logger.debug("Send M5 to AP")
8192 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8193 attrs += build_attr_msg_type(WPS_M5)
8194 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8195 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8196 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8197 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8198 raw_m5_attrs = attrs
8199 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8200 send_wsc_msg(hapd, addr, m5)
8201
8202 logger.debug("Receive M6 from AP")
8203 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8204
8205 logger.debug("Send M7 to AP")
8206 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8207 attrs += build_attr_msg_type(WPS_M7)
8208 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8209 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8210 data = b''
8211 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8212 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8213 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8214 raw_m7_attrs = attrs
8215 send_wsc_msg(hapd, addr, m7)
8216
8217 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8218
8219 @remote_compatible
8220 def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8221 """WPS proto: M7 E-SNonce2 mismatch"""
8222 pin = "12345670"
8223 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8224 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8225 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8226
8227 logger.debug("Receive WSC/Start from AP")
8228 msg = get_wsc_msg(hapd)
8229 if msg['wsc_opcode'] != WSC_Start:
8230 raise Exception("Unexpected Op-Code for WSC/Start")
8231
8232 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8233 uuid_e = 16*b'\x11'
8234 e_nonce = 16*b'\x22'
8235 own_private, e_pk = wsc_dh_init()
8236
8237 logger.debug("Send M1 to AP")
8238 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8239 e_nonce, e_pk)
8240 send_wsc_msg(hapd, addr, m1)
8241
8242 logger.debug("Receive M2 from AP")
8243 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8244 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8245 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8246
8247 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8248 r_nonce)
8249 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8250
8251 logger.debug("Send M3 to AP")
8252 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8253 attrs += build_attr_msg_type(WPS_M3)
8254 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8255 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8256 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8257 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8258 raw_m3_attrs = attrs
8259 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8260 send_wsc_msg(hapd, addr, m3)
8261
8262 logger.debug("Receive M4 from AP")
8263 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8264
8265 logger.debug("Send M5 to AP")
8266 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8267 attrs += build_attr_msg_type(WPS_M5)
8268 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8269 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8270 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8271 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8272 raw_m5_attrs = attrs
8273 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8274 send_wsc_msg(hapd, addr, m5)
8275
8276 logger.debug("Receive M6 from AP")
8277 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8278
8279 logger.debug("Send M7 to AP")
8280 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8281 attrs += build_attr_msg_type(WPS_M7)
8282 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8283 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8284 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8285 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8286 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8287 raw_m7_attrs = attrs
8288 send_wsc_msg(hapd, addr, m7)
8289
8290 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8291
8292 @remote_compatible
8293 def test_wps_ext_m1_pubkey_oom(dev, apdev):
8294 """WPS proto: M1 PubKey OOM"""
8295 pin = "12345670"
8296 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8297 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8298 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8299
8300 logger.debug("Receive WSC/Start from AP")
8301 msg = get_wsc_msg(hapd)
8302 if msg['wsc_opcode'] != WSC_Start:
8303 raise Exception("Unexpected Op-Code for WSC/Start")
8304
8305 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8306 uuid_e = 16*'\x11'
8307 e_nonce = 16*'\x22'
8308 own_private, e_pk = wsc_dh_init()
8309
8310 logger.debug("Send M1 to AP")
8311 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8312 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8313 e_nonce, e_pk)
8314 send_wsc_msg(hapd, addr, m1)
8315 wps_wait_eap_failure(hapd, dev[0])
8316
8317 def wps_wait_eap_failure(hapd, dev):
8318 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8319 if ev is None:
8320 raise Exception("EAP-Failure not reported")
8321 dev.wait_disconnected()
8322
8323 @remote_compatible
8324 def test_wps_ext_m3_m1(dev, apdev):
8325 """WPS proto: M3 replaced with M1"""
8326 pin = "12345670"
8327 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8328 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8329 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8330
8331 logger.debug("Receive WSC/Start from AP")
8332 msg = get_wsc_msg(hapd)
8333 if msg['wsc_opcode'] != WSC_Start:
8334 raise Exception("Unexpected Op-Code for WSC/Start")
8335
8336 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8337 uuid_e = 16*b'\x11'
8338 e_nonce = 16*b'\x22'
8339 own_private, e_pk = wsc_dh_init()
8340
8341 logger.debug("Send M1 to AP")
8342 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8343 e_nonce, e_pk)
8344 send_wsc_msg(hapd, addr, m1)
8345
8346 logger.debug("Receive M2 from AP")
8347 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8348 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8349 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8350
8351 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8352 r_nonce)
8353 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8354
8355 logger.debug("Send M3(M1) to AP")
8356 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8357 attrs += build_attr_msg_type(WPS_M1)
8358 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8359 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8360 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8361 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8362 raw_m3_attrs = attrs
8363 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8364 send_wsc_msg(hapd, addr, m3)
8365
8366 wps_wait_eap_failure(hapd, dev[0])
8367
8368 @remote_compatible
8369 def test_wps_ext_m5_m3(dev, apdev):
8370 """WPS proto: M5 replaced with M3"""
8371 pin = "12345670"
8372 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8373 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8374 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8375
8376 logger.debug("Receive WSC/Start from AP")
8377 msg = get_wsc_msg(hapd)
8378 if msg['wsc_opcode'] != WSC_Start:
8379 raise Exception("Unexpected Op-Code for WSC/Start")
8380
8381 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8382 uuid_e = 16*b'\x11'
8383 e_nonce = 16*b'\x22'
8384 own_private, e_pk = wsc_dh_init()
8385
8386 logger.debug("Send M1 to AP")
8387 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8388 e_nonce, e_pk)
8389 send_wsc_msg(hapd, addr, m1)
8390
8391 logger.debug("Receive M2 from AP")
8392 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8393 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8394 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8395
8396 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8397 r_nonce)
8398 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8399
8400 logger.debug("Send M3 to AP")
8401 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8402 attrs += build_attr_msg_type(WPS_M3)
8403 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8404 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8405 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8406 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8407 raw_m3_attrs = attrs
8408 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8409 send_wsc_msg(hapd, addr, m3)
8410
8411 logger.debug("Receive M4 from AP")
8412 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8413
8414 logger.debug("Send M5(M3) to AP")
8415 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8416 attrs += build_attr_msg_type(WPS_M3)
8417 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8418 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8419 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8420 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8421 raw_m5_attrs = attrs
8422 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8423 send_wsc_msg(hapd, addr, m5)
8424
8425 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8426
8427 @remote_compatible
8428 def test_wps_ext_m3_m2(dev, apdev):
8429 """WPS proto: M3 replaced with M2"""
8430 pin = "12345670"
8431 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8432 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8433 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8434
8435 logger.debug("Receive WSC/Start from AP")
8436 msg = get_wsc_msg(hapd)
8437 if msg['wsc_opcode'] != WSC_Start:
8438 raise Exception("Unexpected Op-Code for WSC/Start")
8439
8440 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8441 uuid_e = 16*b'\x11'
8442 e_nonce = 16*b'\x22'
8443 own_private, e_pk = wsc_dh_init()
8444
8445 logger.debug("Send M1 to AP")
8446 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8447 e_nonce, e_pk)
8448 send_wsc_msg(hapd, addr, m1)
8449
8450 logger.debug("Receive M2 from AP")
8451 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8452 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8453 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8454
8455 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8456 r_nonce)
8457 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8458
8459 logger.debug("Send M3(M2) to AP")
8460 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8461 attrs += build_attr_msg_type(WPS_M2)
8462 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8463 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8464 raw_m3_attrs = attrs
8465 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8466 send_wsc_msg(hapd, addr, m3)
8467
8468 wps_wait_eap_failure(hapd, dev[0])
8469
8470 @remote_compatible
8471 def test_wps_ext_m3_m5(dev, apdev):
8472 """WPS proto: M3 replaced with M5"""
8473 pin = "12345670"
8474 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8475 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8476 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8477
8478 logger.debug("Receive WSC/Start from AP")
8479 msg = get_wsc_msg(hapd)
8480 if msg['wsc_opcode'] != WSC_Start:
8481 raise Exception("Unexpected Op-Code for WSC/Start")
8482
8483 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8484 uuid_e = 16*b'\x11'
8485 e_nonce = 16*b'\x22'
8486 own_private, e_pk = wsc_dh_init()
8487
8488 logger.debug("Send M1 to AP")
8489 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8490 e_nonce, e_pk)
8491 send_wsc_msg(hapd, addr, m1)
8492
8493 logger.debug("Receive M2 from AP")
8494 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8495 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8496 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8497
8498 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8499 r_nonce)
8500 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8501
8502 logger.debug("Send M3(M5) to AP")
8503 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8504 attrs += build_attr_msg_type(WPS_M5)
8505 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8506 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8507 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8508 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8509 raw_m3_attrs = attrs
8510 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8511 send_wsc_msg(hapd, addr, m3)
8512
8513 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8514
8515 @remote_compatible
8516 def test_wps_ext_m3_m7(dev, apdev):
8517 """WPS proto: M3 replaced with M7"""
8518 pin = "12345670"
8519 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8520 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8521 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8522
8523 logger.debug("Receive WSC/Start from AP")
8524 msg = get_wsc_msg(hapd)
8525 if msg['wsc_opcode'] != WSC_Start:
8526 raise Exception("Unexpected Op-Code for WSC/Start")
8527
8528 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8529 uuid_e = 16*b'\x11'
8530 e_nonce = 16*b'\x22'
8531 own_private, e_pk = wsc_dh_init()
8532
8533 logger.debug("Send M1 to AP")
8534 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8535 e_nonce, e_pk)
8536 send_wsc_msg(hapd, addr, m1)
8537
8538 logger.debug("Receive M2 from AP")
8539 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8540 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8541 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8542
8543 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8544 r_nonce)
8545 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8546
8547 logger.debug("Send M3(M7) to AP")
8548 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8549 attrs += build_attr_msg_type(WPS_M7)
8550 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8551 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8552 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8553 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8554 raw_m3_attrs = attrs
8555 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8556 send_wsc_msg(hapd, addr, m3)
8557
8558 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8559
8560 @remote_compatible
8561 def test_wps_ext_m3_done(dev, apdev):
8562 """WPS proto: M3 replaced with WSC_Done"""
8563 pin = "12345670"
8564 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8565 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8566 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8567
8568 logger.debug("Receive WSC/Start from AP")
8569 msg = get_wsc_msg(hapd)
8570 if msg['wsc_opcode'] != WSC_Start:
8571 raise Exception("Unexpected Op-Code for WSC/Start")
8572
8573 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8574 uuid_e = 16*b'\x11'
8575 e_nonce = 16*b'\x22'
8576 own_private, e_pk = wsc_dh_init()
8577
8578 logger.debug("Send M1 to AP")
8579 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8580 e_nonce, e_pk)
8581 send_wsc_msg(hapd, addr, m1)
8582
8583 logger.debug("Receive M2 from AP")
8584 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8585 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8586 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8587
8588 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8589 r_nonce)
8590 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8591
8592 logger.debug("Send M3(WSC_Done) to AP")
8593 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8594 attrs += build_attr_msg_type(WPS_WSC_DONE)
8595 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8596 raw_m3_attrs = attrs
8597 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8598 send_wsc_msg(hapd, addr, m3)
8599
8600 wps_wait_eap_failure(hapd, dev[0])
8601
8602 @remote_compatible
8603 def test_wps_ext_m2_nack_invalid(dev, apdev):
8604 """WPS proto: M2 followed by invalid NACK"""
8605 pin = "12345670"
8606 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8607 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8608 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8609
8610 logger.debug("Receive WSC/Start from AP")
8611 msg = get_wsc_msg(hapd)
8612 if msg['wsc_opcode'] != WSC_Start:
8613 raise Exception("Unexpected Op-Code for WSC/Start")
8614
8615 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8616 uuid_e = 16*b'\x11'
8617 e_nonce = 16*b'\x22'
8618 own_private, e_pk = wsc_dh_init()
8619
8620 logger.debug("Send M1 to AP")
8621 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8622 e_nonce, e_pk)
8623 send_wsc_msg(hapd, addr, m1)
8624
8625 logger.debug("Receive M2 from AP")
8626 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8627 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8628 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8629
8630 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8631 r_nonce)
8632 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8633
8634 logger.debug("Send WSC_NACK to AP")
8635 attrs = b'\x10\x00\x00'
8636 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8637 send_wsc_msg(hapd, addr, nack)
8638
8639 wps_wait_eap_failure(hapd, dev[0])
8640
8641 @remote_compatible
8642 def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8643 """WPS proto: M2 followed by NACK without Msg Type"""
8644 pin = "12345670"
8645 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8646 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8647 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8648
8649 logger.debug("Receive WSC/Start from AP")
8650 msg = get_wsc_msg(hapd)
8651 if msg['wsc_opcode'] != WSC_Start:
8652 raise Exception("Unexpected Op-Code for WSC/Start")
8653
8654 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8655 uuid_e = 16*b'\x11'
8656 e_nonce = 16*b'\x22'
8657 own_private, e_pk = wsc_dh_init()
8658
8659 logger.debug("Send M1 to AP")
8660 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8661 e_nonce, e_pk)
8662 send_wsc_msg(hapd, addr, m1)
8663
8664 logger.debug("Receive M2 from AP")
8665 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8666 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8667 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8668
8669 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8670 r_nonce)
8671 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8672
8673 logger.debug("Send WSC_NACK to AP")
8674 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8675 msg_type=None, eap_code=2)
8676 send_wsc_msg(hapd, addr, nack)
8677
8678 wps_wait_eap_failure(hapd, dev[0])
8679
8680 @remote_compatible
8681 def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8682 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8683 pin = "12345670"
8684 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8685 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8686 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8687
8688 logger.debug("Receive WSC/Start from AP")
8689 msg = get_wsc_msg(hapd)
8690 if msg['wsc_opcode'] != WSC_Start:
8691 raise Exception("Unexpected Op-Code for WSC/Start")
8692
8693 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8694 uuid_e = 16*b'\x11'
8695 e_nonce = 16*b'\x22'
8696 own_private, e_pk = wsc_dh_init()
8697
8698 logger.debug("Send M1 to AP")
8699 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8700 e_nonce, e_pk)
8701 send_wsc_msg(hapd, addr, m1)
8702
8703 logger.debug("Receive M2 from AP")
8704 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8705 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8706 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8707
8708 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8709 r_nonce)
8710 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8711
8712 logger.debug("Send WSC_NACK to AP")
8713 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8714 msg_type=WPS_WSC_ACK, eap_code=2)
8715 send_wsc_msg(hapd, addr, nack)
8716
8717 wps_wait_eap_failure(hapd, dev[0])
8718
8719 @remote_compatible
8720 def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8721 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8722 pin = "12345670"
8723 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8724 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8725 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8726
8727 logger.debug("Receive WSC/Start from AP")
8728 msg = get_wsc_msg(hapd)
8729 if msg['wsc_opcode'] != WSC_Start:
8730 raise Exception("Unexpected Op-Code for WSC/Start")
8731
8732 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8733 uuid_e = 16*b'\x11'
8734 e_nonce = 16*b'\x22'
8735 own_private, e_pk = wsc_dh_init()
8736
8737 logger.debug("Send M1 to AP")
8738 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8739 e_nonce, e_pk)
8740 send_wsc_msg(hapd, addr, m1)
8741
8742 logger.debug("Receive M2 from AP")
8743 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8744 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8745 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8746
8747 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8748 r_nonce)
8749 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8750
8751 logger.debug("Send WSC_NACK to AP")
8752 nack,attrs = build_nack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8753 eap_code=2)
8754 send_wsc_msg(hapd, addr, nack)
8755
8756 wps_wait_eap_failure(hapd, dev[0])
8757
8758 @remote_compatible
8759 def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8760 """WPS proto: M2 followed by NACK without Config Error"""
8761 pin = "12345670"
8762 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8763 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8764 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8765
8766 logger.debug("Receive WSC/Start from AP")
8767 msg = get_wsc_msg(hapd)
8768 if msg['wsc_opcode'] != WSC_Start:
8769 raise Exception("Unexpected Op-Code for WSC/Start")
8770
8771 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8772 uuid_e = 16*b'\x11'
8773 e_nonce = 16*b'\x22'
8774 own_private, e_pk = wsc_dh_init()
8775
8776 logger.debug("Send M1 to AP")
8777 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8778 e_nonce, e_pk)
8779 send_wsc_msg(hapd, addr, m1)
8780
8781 logger.debug("Receive M2 from AP")
8782 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8783 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8784 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8785
8786 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8787 r_nonce)
8788 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8789
8790 logger.debug("Send WSC_NACK to AP")
8791 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8792 config_error=None, eap_code=2)
8793 send_wsc_msg(hapd, addr, nack)
8794
8795 wps_wait_eap_failure(hapd, dev[0])
8796
8797 @remote_compatible
8798 def test_wps_ext_m2_ack_invalid(dev, apdev):
8799 """WPS proto: M2 followed by invalid ACK"""
8800 pin = "12345670"
8801 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8802 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8803 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8804
8805 logger.debug("Receive WSC/Start from AP")
8806 msg = get_wsc_msg(hapd)
8807 if msg['wsc_opcode'] != WSC_Start:
8808 raise Exception("Unexpected Op-Code for WSC/Start")
8809
8810 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8811 uuid_e = 16*b'\x11'
8812 e_nonce = 16*b'\x22'
8813 own_private, e_pk = wsc_dh_init()
8814
8815 logger.debug("Send M1 to AP")
8816 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8817 e_nonce, e_pk)
8818 send_wsc_msg(hapd, addr, m1)
8819
8820 logger.debug("Receive M2 from AP")
8821 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8822 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8823 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8824
8825 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8826 r_nonce)
8827 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8828
8829 logger.debug("Send WSC_ACK to AP")
8830 attrs = b'\x10\x00\x00'
8831 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8832 send_wsc_msg(hapd, addr, ack)
8833
8834 wps_wait_eap_failure(hapd, dev[0])
8835
8836 @remote_compatible
8837 def test_wps_ext_m2_ack(dev, apdev):
8838 """WPS proto: M2 followed by ACK"""
8839 pin = "12345670"
8840 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8841 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8842 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8843
8844 logger.debug("Receive WSC/Start from AP")
8845 msg = get_wsc_msg(hapd)
8846 if msg['wsc_opcode'] != WSC_Start:
8847 raise Exception("Unexpected Op-Code for WSC/Start")
8848
8849 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8850 uuid_e = 16*b'\x11'
8851 e_nonce = 16*b'\x22'
8852 own_private, e_pk = wsc_dh_init()
8853
8854 logger.debug("Send M1 to AP")
8855 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8856 e_nonce, e_pk)
8857 send_wsc_msg(hapd, addr, m1)
8858
8859 logger.debug("Receive M2 from AP")
8860 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8861 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8862 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8863
8864 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8865 r_nonce)
8866 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8867
8868 logger.debug("Send WSC_ACK to AP")
8869 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8870 send_wsc_msg(hapd, addr, ack)
8871
8872 wps_wait_eap_failure(hapd, dev[0])
8873
8874 @remote_compatible
8875 def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8876 """WPS proto: M2 followed by ACK missing Msg Type"""
8877 pin = "12345670"
8878 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8879 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8880 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8881
8882 logger.debug("Receive WSC/Start from AP")
8883 msg = get_wsc_msg(hapd)
8884 if msg['wsc_opcode'] != WSC_Start:
8885 raise Exception("Unexpected Op-Code for WSC/Start")
8886
8887 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8888 uuid_e = 16*b'\x11'
8889 e_nonce = 16*b'\x22'
8890 own_private, e_pk = wsc_dh_init()
8891
8892 logger.debug("Send M1 to AP")
8893 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8894 e_nonce, e_pk)
8895 send_wsc_msg(hapd, addr, m1)
8896
8897 logger.debug("Receive M2 from AP")
8898 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8899 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8900 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8901
8902 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8903 r_nonce)
8904 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8905
8906 logger.debug("Send WSC_ACK to AP")
8907 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8908 msg_type=None, eap_code=2)
8909 send_wsc_msg(hapd, addr, ack)
8910
8911 wps_wait_eap_failure(hapd, dev[0])
8912
8913 @remote_compatible
8914 def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8915 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8916 pin = "12345670"
8917 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8918 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8919 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8920
8921 logger.debug("Receive WSC/Start from AP")
8922 msg = get_wsc_msg(hapd)
8923 if msg['wsc_opcode'] != WSC_Start:
8924 raise Exception("Unexpected Op-Code for WSC/Start")
8925
8926 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8927 uuid_e = 16*b'\x11'
8928 e_nonce = 16*b'\x22'
8929 own_private, e_pk = wsc_dh_init()
8930
8931 logger.debug("Send M1 to AP")
8932 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8933 e_nonce, e_pk)
8934 send_wsc_msg(hapd, addr, m1)
8935
8936 logger.debug("Receive M2 from AP")
8937 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8938 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8939 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8940
8941 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8942 r_nonce)
8943 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8944
8945 logger.debug("Send WSC_ACK to AP")
8946 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8947 msg_type=WPS_WSC_NACK, eap_code=2)
8948 send_wsc_msg(hapd, addr, ack)
8949
8950 wps_wait_eap_failure(hapd, dev[0])
8951
8952 @remote_compatible
8953 def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8954 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8955 pin = "12345670"
8956 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8957 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8958 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8959
8960 logger.debug("Receive WSC/Start from AP")
8961 msg = get_wsc_msg(hapd)
8962 if msg['wsc_opcode'] != WSC_Start:
8963 raise Exception("Unexpected Op-Code for WSC/Start")
8964
8965 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8966 uuid_e = 16*b'\x11'
8967 e_nonce = 16*b'\x22'
8968 own_private, e_pk = wsc_dh_init()
8969
8970 logger.debug("Send M1 to AP")
8971 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8972 e_nonce, e_pk)
8973 send_wsc_msg(hapd, addr, m1)
8974
8975 logger.debug("Receive M2 from AP")
8976 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8977 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8978 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8979
8980 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8981 r_nonce)
8982 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8983
8984 logger.debug("Send WSC_ACK to AP")
8985 ack,attrs = build_ack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8986 eap_code=2)
8987 send_wsc_msg(hapd, addr, ack)
8988
8989 wps_wait_eap_failure(hapd, dev[0])
8990
8991 @remote_compatible
8992 def test_wps_ext_m1_invalid(dev, apdev):
8993 """WPS proto: M1 failing parsing"""
8994 pin = "12345670"
8995 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8996 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8997 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8998
8999 logger.debug("Receive WSC/Start from AP")
9000 msg = get_wsc_msg(hapd)
9001 if msg['wsc_opcode'] != WSC_Start:
9002 raise Exception("Unexpected Op-Code for WSC/Start")
9003
9004 logger.debug("Send M1 to AP")
9005 attrs = b'\x10\x00\x00'
9006 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9007 send_wsc_msg(hapd, addr, m1)
9008
9009 wps_wait_eap_failure(hapd, dev[0])
9010
9011 def test_wps_ext_m1_missing_msg_type(dev, apdev):
9012 """WPS proto: M1 missing Msg Type"""
9013 pin = "12345670"
9014 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9015 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9016 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9017
9018 logger.debug("Receive WSC/Start from AP")
9019 msg = get_wsc_msg(hapd)
9020 if msg['wsc_opcode'] != WSC_Start:
9021 raise Exception("Unexpected Op-Code for WSC/Start")
9022
9023 logger.debug("Send M1 to AP")
9024 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9025 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9026 send_wsc_msg(hapd, addr, m1)
9027
9028 wps_wait_ap_nack(hapd, dev[0], 16*b'\x00', 16*b'\x00')
9029
9030 def wps_ext_wsc_done(dev, apdev):
9031 pin = "12345670"
9032 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9033 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9034 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9035
9036 logger.debug("Receive WSC/Start from AP")
9037 msg = get_wsc_msg(hapd)
9038 if msg['wsc_opcode'] != WSC_Start:
9039 raise Exception("Unexpected Op-Code for WSC/Start")
9040
9041 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9042 uuid_e = 16*b'\x11'
9043 e_nonce = 16*b'\x22'
9044 own_private, e_pk = wsc_dh_init()
9045
9046 logger.debug("Send M1 to AP")
9047 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9048 e_nonce, e_pk)
9049 send_wsc_msg(hapd, addr, m1)
9050
9051 logger.debug("Receive M2 from AP")
9052 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9053 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9054 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9055
9056 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9057 r_nonce)
9058 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9059
9060 logger.debug("Send M3 to AP")
9061 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9062 attrs += build_attr_msg_type(WPS_M3)
9063 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9064 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9065 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9066 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9067 raw_m3_attrs = attrs
9068 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9069 send_wsc_msg(hapd, addr, m3)
9070
9071 logger.debug("Receive M4 from AP")
9072 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9073
9074 logger.debug("Send M5 to AP")
9075 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9076 attrs += build_attr_msg_type(WPS_M5)
9077 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9078 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9079 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9080 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9081 raw_m5_attrs = attrs
9082 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9083 send_wsc_msg(hapd, addr, m5)
9084
9085 logger.debug("Receive M6 from AP")
9086 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9087
9088 logger.debug("Send M7 to AP")
9089 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9090 attrs += build_attr_msg_type(WPS_M7)
9091 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9092 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9093 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9094 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9095 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9096 raw_m7_attrs = attrs
9097 send_wsc_msg(hapd, addr, m7)
9098
9099 logger.debug("Receive M8 from AP")
9100 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9101 return hapd, msg, e_nonce, r_nonce
9102
9103 @remote_compatible
9104 def test_wps_ext_wsc_done_invalid(dev, apdev):
9105 """WPS proto: invalid WSC_Done"""
9106 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9107
9108 logger.debug("Send WSC_Done to AP")
9109 attrs = b'\x10\x00\x00'
9110 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9111 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9112
9113 wps_wait_eap_failure(hapd, dev[0])
9114
9115 @remote_compatible
9116 def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9117 """WPS proto: invalid WSC_Done"""
9118 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9119
9120 logger.debug("Send WSC_Done to AP")
9121 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9122 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9123 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9124 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9125 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9126 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9127
9128 wps_wait_eap_failure(hapd, dev[0])
9129
9130 @remote_compatible
9131 def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9132 """WPS proto: WSC_Done with wrong Msg Type"""
9133 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9134
9135 logger.debug("Send WSC_Done to AP")
9136 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9137 attrs += build_attr_msg_type(WPS_WSC_ACK)
9138 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9139 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9140 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9141 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9142
9143 wps_wait_eap_failure(hapd, dev[0])
9144
9145 @remote_compatible
9146 def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9147 """WPS proto: WSC_Done without e_nonce"""
9148 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9149
9150 logger.debug("Send WSC_Done to AP")
9151 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9152 attrs += build_attr_msg_type(WPS_WSC_DONE)
9153 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9154 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9155 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9156 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9157
9158 wps_wait_eap_failure(hapd, dev[0])
9159
9160 def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9161 """WPS proto: WSC_Done without r_nonce"""
9162 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9163
9164 logger.debug("Send WSC_Done to AP")
9165 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9166 attrs += build_attr_msg_type(WPS_WSC_DONE)
9167 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9168 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9169 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9170 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9171
9172 wps_wait_eap_failure(hapd, dev[0])
9173
9174 @remote_compatible
9175 def test_wps_ext_m7_no_encr_settings(dev, apdev):
9176 """WPS proto: M7 without Encr Settings"""
9177 pin = "12345670"
9178 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9179 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9180 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9181
9182 logger.debug("Receive WSC/Start from AP")
9183 msg = get_wsc_msg(hapd)
9184 if msg['wsc_opcode'] != WSC_Start:
9185 raise Exception("Unexpected Op-Code for WSC/Start")
9186
9187 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9188 uuid_e = 16*b'\x11'
9189 e_nonce = 16*b'\x22'
9190 own_private, e_pk = wsc_dh_init()
9191
9192 logger.debug("Send M1 to AP")
9193 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9194 e_nonce, e_pk)
9195 send_wsc_msg(hapd, addr, m1)
9196
9197 logger.debug("Receive M2 from AP")
9198 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9199 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9200 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9201
9202 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9203 r_nonce)
9204 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9205
9206 logger.debug("Send M3 to AP")
9207 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9208 attrs += build_attr_msg_type(WPS_M3)
9209 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9210 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9211 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9212 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9213 raw_m3_attrs = attrs
9214 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9215 send_wsc_msg(hapd, addr, m3)
9216
9217 logger.debug("Receive M4 from AP")
9218 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9219
9220 logger.debug("Send M5 to AP")
9221 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9222 attrs += build_attr_msg_type(WPS_M5)
9223 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9224 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9225 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9226 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9227 raw_m5_attrs = attrs
9228 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9229 send_wsc_msg(hapd, addr, m5)
9230
9231 logger.debug("Receive M6 from AP")
9232 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9233
9234 logger.debug("Send M7 to AP")
9235 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9236 attrs += build_attr_msg_type(WPS_M7)
9237 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9238 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9239 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9240 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9241 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9242 raw_m7_attrs = attrs
9243 send_wsc_msg(hapd, addr, m7)
9244
9245 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9246
9247 @remote_compatible
9248 def test_wps_ext_m1_workaround(dev, apdev):
9249 """WPS proto: M1 Manufacturer/Model workaround"""
9250 pin = "12345670"
9251 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9252 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9253 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9254
9255 logger.debug("Receive WSC/Start from AP")
9256 msg = get_wsc_msg(hapd)
9257 if msg['wsc_opcode'] != WSC_Start:
9258 raise Exception("Unexpected Op-Code for WSC/Start")
9259
9260 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9261 uuid_e = 16*b'\x11'
9262 e_nonce = 16*b'\x22'
9263 own_private, e_pk = wsc_dh_init()
9264
9265 logger.debug("Send M1 to AP")
9266 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9267 e_nonce, e_pk, manufacturer='Apple TEST',
9268 model_name='AirPort', config_methods=b'\xff\xff')
9269 send_wsc_msg(hapd, addr, m1)
9270
9271 logger.debug("Receive M2 from AP")
9272 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9273
9274 @remote_compatible
9275 def test_ap_wps_disable_enable(dev, apdev):
9276 """WPS and DISABLE/ENABLE AP"""
9277 hapd = wps_start_ap(apdev[0])
9278 hapd.disable()
9279 hapd.enable()
9280 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9281
9282 def test_ap_wps_upnp_web_oom(dev, apdev, params):
9283 """hostapd WPS UPnP web OOM"""
9284 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9285 hapd = add_ssdp_ap(apdev[0], ap_uuid)
9286
9287 location = ssdp_get_location(ap_uuid)
9288 url = urlparse(location)
9289 urls = upnp_get_urls(location)
9290 eventurl = urlparse(urls['event_sub_url'])
9291 ctrlurl = urlparse(urls['control_url'])
9292
9293 conn = HTTPConnection(url.netloc)
9294 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9295 conn.request("GET", "/wps_device.xml")
9296 try:
9297 resp = conn.getresponse()
9298 except:
9299 pass
9300
9301 conn = HTTPConnection(url.netloc)
9302 conn.request("GET", "/unknown")
9303 resp = conn.getresponse()
9304 if resp.status != 404:
9305 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9306
9307 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9308 conn.request("GET", "/unknown")
9309 try:
9310 resp = conn.getresponse()
9311 print(resp.status)
9312 except:
9313 pass
9314
9315 conn = HTTPConnection(url.netloc)
9316 conn.request("GET", "/wps_device.xml")
9317 resp = conn.getresponse()
9318 if resp.status != 200:
9319 raise Exception("GET /wps_device.xml failed")
9320
9321 conn = HTTPConnection(url.netloc)
9322 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9323 if resp.status != 200:
9324 raise Exception("GetDeviceInfo failed")
9325
9326 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9327 conn = HTTPConnection(url.netloc)
9328 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9329 if resp.status != 500:
9330 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9331
9332 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9333 conn = HTTPConnection(url.netloc)
9334 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9335 if resp.status != 500:
9336 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9337
9338 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9339 conn = HTTPConnection(url.netloc)
9340 try:
9341 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9342 except:
9343 pass
9344
9345 conn = HTTPConnection(url.netloc)
9346 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9347 if resp.status != 200:
9348 raise Exception("GetDeviceInfo failed")
9349
9350 # No NewWLANEventType in PutWLANResponse NewMessage
9351 conn = HTTPConnection(url.netloc)
9352 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9353 if resp.status != 600:
9354 raise Exception("Unexpected HTTP response: %d" % resp.status)
9355
9356 # No NewWLANEventMAC in PutWLANResponse NewMessage
9357 conn = HTTPConnection(url.netloc)
9358 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9359 newmsg="foo", neweventtype="1")
9360 if resp.status != 600:
9361 raise Exception("Unexpected HTTP response: %d" % resp.status)
9362
9363 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9364 conn = HTTPConnection(url.netloc)
9365 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9366 newmsg="foo", neweventtype="1",
9367 neweventmac="foo")
9368 if resp.status != 600:
9369 raise Exception("Unexpected HTTP response: %d" % resp.status)
9370
9371 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9372 # Ignored unexpected PutWLANResponse WLANEventType 1
9373 conn = HTTPConnection(url.netloc)
9374 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9375 newmsg="foo", neweventtype="1",
9376 neweventmac="00.11.22.33.44.55")
9377 if resp.status != 500:
9378 raise Exception("Unexpected HTTP response: %d" % resp.status)
9379
9380 # PutWLANResponse NewMessage with invalid EAP message
9381 conn = HTTPConnection(url.netloc)
9382 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9383 newmsg="foo", neweventtype="2",
9384 neweventmac="00:11:22:33:44:55")
9385 if resp.status != 200:
9386 raise Exception("Unexpected HTTP response: %d" % resp.status)
9387
9388 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9389 conn = HTTPConnection(url.netloc)
9390 headers = { "callback": '<http://127.0.0.1:12345/event>',
9391 "NT": "upnp:event",
9392 "timeout": "Second-1234" }
9393 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9394 try:
9395 resp = conn.getresponse()
9396 except:
9397 pass
9398
9399 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9400 conn = HTTPConnection(url.netloc)
9401 headers = { "callback": '<http://127.0.0.1:12345/event>',
9402 "NT": "upnp:event",
9403 "timeout": "Second-1234" }
9404 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9405 resp = conn.getresponse()
9406 if resp.status != 500:
9407 raise Exception("Unexpected HTTP response: %d" % resp.status)
9408
9409 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9410 conn = HTTPConnection(url.netloc)
9411 headers = { "callback": '<http://127.0.0.1:12345/event>',
9412 "NT": "upnp:event",
9413 "timeout": "Second-1234" }
9414 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9415 try:
9416 resp = conn.getresponse()
9417 except:
9418 pass
9419
9420 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9421 conn = HTTPConnection(url.netloc)
9422 conn.request("HEAD", "/wps_device.xml")
9423 try:
9424 resp = conn.getresponse()
9425 except:
9426 pass
9427
9428 def test_ap_wps_frag_ack_oom(dev, apdev):
9429 """WPS and fragment ack OOM"""
9430 dev[0].request("SET wps_fragment_size 50")
9431 hapd = wps_start_ap(apdev[0])
9432 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9433 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
9434
9435 def wait_scan_stopped(dev):
9436 dev.request("ABORT_SCAN")
9437 for i in range(50):
9438 res = dev.get_driver_status_field("scan_state")
9439 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9440 break
9441 logger.debug("Waiting for scan to complete")
9442 time.sleep(0.1)
9443
9444 @remote_compatible
9445 def test_ap_wps_eap_wsc_errors(dev, apdev):
9446 """WPS and EAP-WSC error cases"""
9447 ssid = "test-wps-conf-pin"
9448 appin = "12345670"
9449 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9450 "wpa_passphrase": "12345678", "wpa": "2",
9451 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9452 "fragment_size": "300", "ap_pin": appin }
9453 hapd = hostapd.add_ap(apdev[0], params)
9454 bssid = apdev[0]['bssid']
9455
9456 pin = dev[0].wps_read_pin()
9457 hapd.request("WPS_PIN any " + pin)
9458 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9459 dev[0].dump_monitor()
9460
9461 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9462 "new passphrase", no_wait=True)
9463 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9464 if ev is None:
9465 raise Exception("WPS-FAIL not reported")
9466 dev[0].request("WPS_CANCEL")
9467 dev[0].wait_disconnected()
9468 wait_scan_stopped(dev[0])
9469 dev[0].dump_monitor()
9470
9471 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9472 "new passphrase", no_wait=True)
9473 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9474 if ev is None:
9475 raise Exception("WPS-FAIL not reported")
9476 dev[0].request("WPS_CANCEL")
9477 dev[0].wait_disconnected()
9478 wait_scan_stopped(dev[0])
9479 dev[0].dump_monitor()
9480
9481 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9482 "new passphrase", no_wait=True)
9483 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9484 if ev is None:
9485 raise Exception("WPS-FAIL not reported")
9486 dev[0].request("WPS_CANCEL")
9487 dev[0].wait_disconnected()
9488 wait_scan_stopped(dev[0])
9489 dev[0].dump_monitor()
9490
9491 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9492 "new passphrase", no_wait=True)
9493 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9494 if ev is None:
9495 raise Exception("WPS-FAIL not reported")
9496 dev[0].request("WPS_CANCEL")
9497 dev[0].wait_disconnected()
9498 wait_scan_stopped(dev[0])
9499 dev[0].dump_monitor()
9500
9501 tests = [ "eap_wsc_init",
9502 "eap_msg_alloc;eap_wsc_build_msg",
9503 "wpabuf_alloc;eap_wsc_process_fragment" ]
9504 for func in tests:
9505 with alloc_fail(dev[0], 1, func):
9506 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9507 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9508 dev[0].request("WPS_CANCEL")
9509 dev[0].wait_disconnected()
9510 wait_scan_stopped(dev[0])
9511 dev[0].dump_monitor()
9512
9513 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9514 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9515 "CCMP", "new passphrase", no_wait=True)
9516 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9517 dev[0].request("WPS_CANCEL")
9518 dev[0].wait_disconnected()
9519 wait_scan_stopped(dev[0])
9520 dev[0].dump_monitor()
9521
9522 def test_ap_wps_eap_wsc(dev, apdev):
9523 """WPS and EAP-WSC in network profile"""
9524 params = int_eap_server_params()
9525 params["wps_state"] = "2"
9526 hapd = hostapd.add_ap(apdev[0], params)
9527 bssid = apdev[0]['bssid']
9528
9529 logger.info("Unexpected identity")
9530 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9531 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9532 wait_connect=False)
9533 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9534 if ev is None:
9535 raise Exception("No EAP-Failure seen")
9536 dev[0].request("REMOVE_NETWORK all")
9537 dev[0].wait_disconnected()
9538
9539 logger.info("No phase1 parameter")
9540 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9541 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9542 wait_connect=False)
9543 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9544 if ev is None:
9545 raise Exception("Timeout on EAP method start")
9546 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9547 if ev is None:
9548 raise Exception("No EAP-Failure seen")
9549 dev[0].request("REMOVE_NETWORK all")
9550 dev[0].wait_disconnected()
9551
9552 logger.info("No PIN/PBC in phase1")
9553 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9554 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9555 phase1="foo", wait_connect=False)
9556 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9557 if ev is None:
9558 raise Exception("Timeout on EAP method start")
9559 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9560 if ev is None:
9561 raise Exception("No EAP-Failure seen")
9562 dev[0].request("REMOVE_NETWORK all")
9563 dev[0].wait_disconnected()
9564
9565 logger.info("Invalid pkhash in phase1")
9566 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9567 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9568 phase1="foo pkhash=q pbc=1", wait_connect=False)
9569 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9570 if ev is None:
9571 raise Exception("Timeout on EAP method start")
9572 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9573 if ev is None:
9574 raise Exception("No EAP-Failure seen")
9575 dev[0].request("REMOVE_NETWORK all")
9576 dev[0].wait_disconnected()
9577
9578 logger.info("Zero fragment_size")
9579 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9580 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9581 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9582 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9583 if ev is None:
9584 raise Exception("Timeout on EAP method start")
9585 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9586 if ev is None:
9587 raise Exception("No M2D seen")
9588 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9589 if ev is None:
9590 raise Exception("No EAP-Failure seen")
9591 dev[0].request("REMOVE_NETWORK all")
9592 dev[0].wait_disconnected()
9593
9594 logger.info("Missing new_auth")
9595 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9596 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9597 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9598 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9599 if ev is None:
9600 raise Exception("Timeout on EAP method start")
9601 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9602 if ev is None:
9603 raise Exception("No EAP-Failure seen")
9604 dev[0].request("REMOVE_NETWORK all")
9605 dev[0].wait_disconnected()
9606
9607 logger.info("Missing new_encr")
9608 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9609 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9610 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9611 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9612 if ev is None:
9613 raise Exception("Timeout on EAP method start")
9614 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9615 if ev is None:
9616 raise Exception("No EAP-Failure seen")
9617 dev[0].request("REMOVE_NETWORK all")
9618 dev[0].wait_disconnected()
9619
9620 logger.info("Missing new_key")
9621 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9622 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9623 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9624 wait_connect=False)
9625 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9626 if ev is None:
9627 raise Exception("Timeout on EAP method start")
9628 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9629 if ev is None:
9630 raise Exception("No EAP-Failure seen")
9631 dev[0].request("REMOVE_NETWORK all")
9632 dev[0].wait_disconnected()
9633
9634 def test_ap_wps_and_bss_limit(dev, apdev):
9635 """WPS and wpa_supplicant BSS entry limit"""
9636 try:
9637 _test_ap_wps_and_bss_limit(dev, apdev)
9638 finally:
9639 dev[0].request("SET bss_max_count 200")
9640 pass
9641
9642 def _test_ap_wps_and_bss_limit(dev, apdev):
9643 params = { "ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9644 "wpa_passphrase": "12345678", "wpa": "2",
9645 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
9646 hapd = hostapd.add_ap(apdev[0], params)
9647
9648 params = { "ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9649 "wpa_passphrase": "1234567890", "wpa": "2",
9650 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
9651 hapd2 = hostapd.add_ap(apdev[1], params)
9652
9653 id = dev[1].add_network()
9654 dev[1].set_network(id, "mode", "2")
9655 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9656 dev[1].set_network_quoted(id, "psk", "12345678")
9657 dev[1].set_network(id, "frequency", "2462")
9658 dev[1].set_network(id, "scan_freq", "2462")
9659 dev[1].set_network(id, "wps_disabled", "1")
9660 dev[1].select_network(id)
9661
9662 id = dev[2].add_network()
9663 dev[2].set_network(id, "mode", "2")
9664 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9665 dev[2].set_network_quoted(id, "psk", "12345678")
9666 dev[2].set_network(id, "frequency", "2437")
9667 dev[2].set_network(id, "scan_freq", "2437")
9668 dev[2].select_network(id)
9669
9670 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9671 wpas.interface_add("wlan5")
9672 id = wpas.add_network()
9673 wpas.set_network(id, "mode", "2")
9674 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9675 wpas.set_network_quoted(id, "psk", "12345678")
9676 wpas.set_network(id, "frequency", "2437")
9677 wpas.set_network(id, "scan_freq", "2437")
9678 wpas.select_network(id)
9679
9680 dev[1].wait_connected()
9681 dev[2].wait_connected()
9682 wpas.wait_connected()
9683 wpas.request("WPS_PIN any 12345670")
9684
9685 hapd.request("WPS_PBC")
9686 hapd2.request("WPS_PBC")
9687
9688 dev[0].request("SET bss_max_count 1")
9689
9690 id = dev[0].add_network()
9691 dev[0].set_network_quoted(id, "ssid", "testing")
9692
9693 id = dev[0].add_network()
9694 dev[0].set_network_quoted(id, "ssid", "testing")
9695 dev[0].set_network(id, "key_mgmt", "WPS")
9696
9697 dev[0].request("WPS_PBC")
9698 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9699 dev[0].request("WPS_CANCEL")
9700
9701 id = dev[0].add_network()
9702 dev[0].set_network_quoted(id, "ssid", "testing")
9703 dev[0].set_network(id, "key_mgmt", "WPS")
9704
9705 dev[0].scan(freq="2412")
9706
9707 def test_ap_wps_pbc_2ap(dev, apdev):
9708 """WPS PBC with two APs advertising same SSID"""
9709 params = { "ssid": "wps", "eap_server": "1", "wps_state": "2",
9710 "wpa_passphrase": "12345678", "wpa": "2",
9711 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9712 "wps_independent": "1"}
9713 hapd = hostapd.add_ap(apdev[0], params)
9714 params = { "ssid": "wps", "eap_server": "1", "wps_state": "2",
9715 "wpa_passphrase": "123456789", "wpa": "2",
9716 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9717 "wps_independent": "1"}
9718 hapd2 = hostapd.add_ap(apdev[1], params)
9719 hapd.request("WPS_PBC")
9720
9721 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9722 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9723 wpas.dump_monitor()
9724
9725 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9726 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9727 wpas.request("WPS_PBC")
9728 wpas.wait_connected()
9729 wpas.request("DISCONNECT")
9730 hapd.request("DISABLE")
9731 hapd2.request("DISABLE")
9732 wpas.flush_scan_cache()
9733
9734 def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9735 """WPS ER enrolling a new device to a configured AP"""
9736 try:
9737 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9738 finally:
9739 dev[0].request("WPS_ER_STOP")
9740
9741 def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9742 ssid = "wps-er-enrollee-to-conf-ap"
9743 ap_pin = "12345670"
9744 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9745 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9746 "wpa_passphrase": "12345678", "wpa": "2",
9747 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9748 "device_name": "Wireless AP", "manufacturer": "Company",
9749 "model_name": "WAP", "model_number": "123",
9750 "serial_number": "12345", "device_type": "6-0050F204-1",
9751 "os_version": "01020300",
9752 "config_methods": "label push_button",
9753 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9754 hapd = hostapd.add_ap(apdev[0], params)
9755 bssid = hapd.own_addr()
9756
9757 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9758 dev[0].dump_monitor()
9759
9760 dev[0].request("WPS_ER_START ifname=lo")
9761 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9762 if ev is None:
9763 raise Exception("AP discovery timed out")
9764 if ap_uuid not in ev:
9765 raise Exception("Expected AP UUID not found")
9766
9767 pin = dev[2].wps_read_pin()
9768 addr2 = dev[2].own_addr()
9769 dev[0].dump_monitor()
9770 dev[2].scan_for_bss(bssid, freq=2412)
9771 dev[2].dump_monitor()
9772 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9773
9774 for i in range(3):
9775 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9776 if ev is None:
9777 raise Exception("Enrollee not seen")
9778 if addr2 in ev:
9779 break
9780 if addr2 not in ev:
9781 raise Exception("Unexpected Enrollee MAC address")
9782 dev[0].dump_monitor()
9783
9784 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9785 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9786 dev[2].wait_connected(timeout=30)
9787 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9788 if ev is None:
9789 raise Exception("WPS ER did not report success")
9790
9791 def test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9792 """WPS ER enrolling a new device to a configured AP (2)"""
9793 try:
9794 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9795 finally:
9796 dev[0].request("WPS_ER_STOP")
9797
9798 def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9799 ssid = "wps-er-enrollee-to-conf-ap"
9800 ap_pin = "12345670"
9801 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9802 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9803 "wpa_passphrase": "12345678", "wpa": "2",
9804 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9805 "device_name": "Wireless AP", "manufacturer": "Company",
9806 "model_name": "WAP", "model_number": "123",
9807 "serial_number": "12345", "device_type": "6-0050F204-1",
9808 "os_version": "01020300",
9809 "config_methods": "label push_button",
9810 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9811 hapd = hostapd.add_ap(apdev[0], params)
9812 bssid = hapd.own_addr()
9813
9814 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9815 dev[0].dump_monitor()
9816
9817 dev[0].request("WPS_ER_START ifname=lo")
9818 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9819 if ev is None:
9820 raise Exception("AP discovery timed out")
9821 if ap_uuid not in ev:
9822 raise Exception("Expected AP UUID not found")
9823
9824 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
9825 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
9826 if ev is None:
9827 raise Exception("AP learn timed out")
9828 if ap_uuid not in ev:
9829 raise Exception("Expected AP UUID not in settings")
9830 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
9831 if ev is None:
9832 raise Exception("WPS-FAIL after AP learn timed out")
9833 time.sleep(0.1)
9834
9835 pin = dev[1].wps_read_pin()
9836 addr1 = dev[1].own_addr()
9837 dev[0].dump_monitor()
9838 dev[0].request("WPS_ER_PIN any " + pin)
9839 time.sleep(0.1)
9840 dev[1].scan_for_bss(bssid, freq=2412)
9841 dev[1].request("WPS_PIN any %s" % pin)
9842 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
9843 if ev is None:
9844 raise Exception("Enrollee did not report success")
9845 dev[1].wait_connected(timeout=15)
9846 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9847 if ev is None:
9848 raise Exception("WPS ER did not report success")
9849
9850 def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
9851 """WPS AP trying to ignore broadcast SSID"""
9852 ssid = "test-wps"
9853 hapd = hostapd.add_ap(apdev[0],
9854 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9855 "ignore_broadcast_ssid": "1" })
9856 if "FAIL" not in hapd.request("WPS_PBC"):
9857 raise Exception("WPS unexpectedly enabled")
9858
9859 def test_ap_wps_wep(dev, apdev):
9860 """WPS AP trying to enable WEP"""
9861 ssid = "test-wps"
9862 hapd = hostapd.add_ap(apdev[0],
9863 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9864 "ieee80211n": "0", "wep_key0": '"hello"' })
9865 if "FAIL" not in hapd.request("WPS_PBC"):
9866 raise Exception("WPS unexpectedly enabled")
9867
9868 def test_ap_wps_tkip(dev, apdev):
9869 """WPS AP trying to enable TKIP"""
9870 ssid = "test-wps"
9871 hapd = hostapd.add_ap(apdev[0],
9872 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9873 "ieee80211n": "0", "wpa": '1',
9874 "wpa_key_mgmt": "WPA-PSK",
9875 "wpa_passphrase": "12345678" })
9876 if "FAIL" not in hapd.request("WPS_PBC"):
9877 raise Exception("WPS unexpectedly enabled")
9878
9879 def test_ap_wps_conf_dummy_cred(dev, apdev):
9880 """WPS PIN provisioning with configured AP using dummy cred"""
9881 ssid = "test-wps-conf"
9882 hapd = hostapd.add_ap(apdev[0],
9883 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9884 "wpa_passphrase": "12345678", "wpa": "2",
9885 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9886 hapd.request("WPS_PIN any 12345670")
9887 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9888 dev[0].dump_monitor()
9889 try:
9890 hapd.set("wps_testing_dummy_cred", "1")
9891 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
9892 for i in range(1, 3):
9893 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
9894 if ev is None:
9895 raise Exception("WPS credential %d not received" % i)
9896 dev[0].wait_connected(timeout=30)
9897 finally:
9898 hapd.set("wps_testing_dummy_cred", "0")
9899
9900 def test_ap_wps_rf_bands(dev, apdev):
9901 """WPS and wps_rf_bands configuration"""
9902 ssid = "test-wps-conf"
9903 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9904 "wpa_passphrase": "12345678", "wpa": "2",
9905 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9906 "wps_rf_bands": "ag" }
9907
9908 hapd = hostapd.add_ap(apdev[0], params)
9909 bssid = hapd.own_addr()
9910 hapd.request("WPS_PBC")
9911 dev[0].scan_for_bss(bssid, freq="2412")
9912 dev[0].dump_monitor()
9913 dev[0].request("WPS_PBC " + bssid)
9914 dev[0].wait_connected(timeout=30)
9915 bss = dev[0].get_bss(bssid)
9916 logger.info("BSS: " + str(bss))
9917 if "103c000103" not in bss['ie']:
9918 raise Exception("RF Bands attribute with expected values not found")
9919 dev[0].request("DISCONNECT")
9920 dev[0].wait_disconnected()
9921 hapd.set("wps_rf_bands", "ad")
9922 hapd.set("wps_rf_bands", "a")
9923 hapd.set("wps_rf_bands", "g")
9924 hapd.set("wps_rf_bands", "b")
9925 hapd.set("wps_rf_bands", "ga")
9926 hapd.disable()
9927 dev[0].dump_monitor()
9928 dev[0].flush_scan_cache()
9929
9930 def test_ap_wps_pbc_in_m1(dev, apdev):
9931 """WPS and pbc_in_m1"""
9932 ssid = "test-wps-conf"
9933 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9934 "wpa_passphrase": "12345678", "wpa": "2",
9935 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9936 "config_methods": "virtual_push_button virtual_display",
9937 "pbc_in_m1": "1" }
9938
9939 hapd = hostapd.add_ap(apdev[0], params)
9940 bssid = hapd.own_addr()
9941 hapd.request("WPS_PBC")
9942 dev[0].scan_for_bss(bssid, freq="2412")
9943 dev[0].dump_monitor()
9944 dev[0].request("WPS_PBC " + bssid)
9945 dev[0].wait_connected(timeout=30)
9946 dev[0].request("DISCONNECT")
9947 dev[0].wait_disconnected()
9948 hapd.disable()
9949 dev[0].dump_monitor()
9950 dev[0].flush_scan_cache()
9951
9952 def test_ap_wps_pin_start_failure(dev, apdev):
9953 """WPS_PIN start failure"""
9954 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
9955 if "FAIL" not in dev[0].request("WPS_PIN any 12345670"):
9956 raise Exception("WPS_PIN not rejected during OOM")
9957 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
9958 if "FAIL" not in dev[0].request("WPS_PIN any"):
9959 raise Exception("WPS_PIN not rejected during OOM")
9960
9961 def test_ap_wps_ap_pin_failure(dev, apdev):
9962 """WPS_AP_PIN failure"""
9963 id = dev[0].add_network()
9964 dev[0].set_network(id, "mode", "2")
9965 dev[0].set_network_quoted(id, "ssid", "wpas-ap-wps")
9966 dev[0].set_network_quoted(id, "psk", "1234567890")
9967 dev[0].set_network(id, "frequency", "2412")
9968 dev[0].set_network(id, "scan_freq", "2412")
9969 dev[0].select_network(id)
9970 dev[0].wait_connected()
9971
9972 with fail_test(dev[0], 1,
9973 "os_get_random;wpa_supplicant_ctrl_iface_wps_ap_pin"):
9974 if "FAIL" not in dev[0].request("WPS_AP_PIN random"):
9975 raise Exception("WPS_AP_PIN random accepted")
9976 with alloc_fail(dev[0], 1, "wpas_wps_ap_pin_set"):
9977 if "FAIL" not in dev[0].request("WPS_AP_PIN set 12345670"):
9978 raise Exception("WPS_AP_PIN set accepted")
9979
9980 dev[0].request("DISCONNECT")
9981 dev[0].wait_disconnected()
9982
9983 def test_ap_wps_random_uuid(dev, apdev, params):
9984 """WPS and random UUID on Enrollee"""
9985 ssid = "test-wps-conf"
9986 hapd = hostapd.add_ap(apdev[0],
9987 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9988 "wpa_passphrase": "12345678", "wpa": "2",
9989 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9990
9991 config = os.path.join(params['logdir'], 'ap_wps_random_uuid.conf')
9992 with open(config, "w") as f:
9993 f.write("auto_uuid=1\n")
9994
9995 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9996
9997 uuid = []
9998 for i in range(3):
9999 wpas.interface_add("wlan5", config=config)
10000
10001 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
10002 wpas.dump_monitor()
10003 wpas.request("WPS_PBC " + apdev[0]['bssid'])
10004
10005 ev = hapd.wait_event(["WPS-ENROLLEE-SEEN"], timeout=10)
10006 if ev is None:
10007 raise Exception("Enrollee not seen")
10008 uuid.append(ev.split(' ')[2])
10009 wpas.request("WPS_CANCEL")
10010 wpas.dump_monitor()
10011
10012 wpas.interface_remove("wlan5")
10013
10014 hapd.dump_monitor()
10015
10016 logger.info("Seen UUIDs: " + str(uuid))
10017 if uuid[0] == uuid[1] or uuid[0] == uuid[2] or uuid[1] == uuid[2]:
10018 raise Exception("Same UUID used multiple times")
10019
10020 def test_ap_wps_conf_pin_gcmp_128(dev, apdev):
10021 """WPS PIN provisioning with configured AP using GCMP-128"""
10022 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP")
10023
10024 def test_ap_wps_conf_pin_gcmp_256(dev, apdev):
10025 """WPS PIN provisioning with configured AP using GCMP-256"""
10026 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP-256")
10027
10028 def test_ap_wps_conf_pin_ccmp_256(dev, apdev):
10029 """WPS PIN provisioning with configured AP using CCMP-256"""
10030 run_ap_wps_conf_pin_cipher(dev, apdev, "CCMP-256")
10031
10032 def run_ap_wps_conf_pin_cipher(dev, apdev, cipher):
10033 if cipher not in dev[0].get_capability("pairwise"):
10034 raise HwsimSkip("Cipher %s not supported" % cipher)
10035 ssid = "test-wps-conf-pin"
10036 hapd = hostapd.add_ap(apdev[0],
10037 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
10038 "wpa_passphrase": "12345678", "wpa": "2",
10039 "wpa_key_mgmt": "WPA-PSK",
10040 "rsn_pairwise": cipher })
10041 logger.info("WPS provisioning step")
10042 pin = dev[0].wps_read_pin()
10043 hapd.request("WPS_PIN any " + pin)
10044 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10045 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10046 dev[0].wait_connected(timeout=15)