]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/test_ap_wps.py
tests: Encode/decode base64 operations for python3
[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])
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 return struct.pack('>HH', attr, len(payload)) + payload
6231
6232 def build_attr_msg_type(msg_type):
6233 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6234
6235 def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6236 length = 4 + 8 + 2 + len(payload)
6237 # EAPOL header
6238 msg = struct.pack('>BBH', 2, 0, length)
6239 # EAP header
6240 msg += struct.pack('>BBH', eap_code, eap_id, length)
6241 # EAP expanded header for EAP-WSC
6242 msg += struct.pack('B', 254)
6243 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6244 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6245 # EAP-WSC header
6246 msg += struct.pack('BB', opcode, 0)
6247 # WSC attributes
6248 msg += payload
6249 return msg
6250
6251 def build_eap_success(eap_id):
6252 length = 4
6253 # EAPOL header
6254 msg = struct.pack('>BBH', 2, 0, length)
6255 # EAP header
6256 msg += struct.pack('>BBH', 3, eap_id, length)
6257 return msg
6258
6259 def build_eap_failure(eap_id):
6260 length = 4
6261 # EAPOL header
6262 msg = struct.pack('>BBH', 2, 0, length)
6263 # EAP header
6264 msg += struct.pack('>BBH', 4, eap_id, length)
6265 return msg
6266
6267 def send_wsc_msg(dev, src, msg):
6268 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg).decode())
6269 if "OK" not in res:
6270 raise Exception("EAPOL_RX failed")
6271
6272 group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6273 group_5_generator = 2
6274
6275 def wsc_kdf(key, label, bits):
6276 result = b''
6277 i = 1
6278 while len(result) * 8 < bits:
6279 data = struct.pack('>L', i) + label.encode() + struct.pack('>L', bits)
6280 m = hmac.new(key, data, hashlib.sha256)
6281 result += m.digest()
6282 i += 1
6283 return result[0:bits // 8]
6284
6285 def wsc_keys(kdk):
6286 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6287 authkey = keys[0:32]
6288 keywrapkey = keys[32:48]
6289 emsk = keys[48:80]
6290 return authkey,keywrapkey,emsk
6291
6292 def wsc_dev_pw_half_psk(authkey, dev_pw):
6293 m = hmac.new(authkey, dev_pw.encode(), hashlib.sha256)
6294 return m.digest()[0:16]
6295
6296 def wsc_dev_pw_psk(authkey, dev_pw):
6297 dev_pw_1 = dev_pw[0:len(dev_pw) // 2]
6298 dev_pw_2 = dev_pw[len(dev_pw) // 2:]
6299 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6300 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6301 return psk1,psk2
6302
6303 def build_attr_authenticator(authkey, prev_msg, curr_msg):
6304 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6305 auth = m.digest()[0:8]
6306 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6307
6308 def build_attr_encr_settings(authkey, keywrapkey, data):
6309 m = hmac.new(authkey, data, hashlib.sha256)
6310 kwa = m.digest()[0:8]
6311 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6312 iv = 16*b'\x99'
6313 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6314 pad_len = 16 - len(data) % 16
6315 ps = pad_len * struct.pack('B', pad_len)
6316 data += ps
6317 wrapped = aes.encrypt(data)
6318 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6319
6320 def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6321 if len(data) < 32 or len(data) % 16 != 0:
6322 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6323 iv = data[0:16]
6324 encr = data[16:]
6325 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6326 decrypted = aes.decrypt(encr)
6327 pad_len, = struct.unpack('B', decrypted[-1])
6328 if pad_len > len(decrypted):
6329 raise Exception("Invalid padding in Encrypted Settings")
6330 for i in range(-pad_len, -1):
6331 if decrypted[i] != decrypted[-1]:
6332 raise Exception("Invalid PS value in Encrypted Settings")
6333
6334 decrypted = decrypted[0:len(decrypted) - pad_len]
6335 if len(decrypted) < 12:
6336 raise Exception("Truncated Encrypted Settings plaintext")
6337 kwa = decrypted[-12:]
6338 attr,length = struct.unpack(">HH", kwa[0:4])
6339 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6340 raise Exception("Invalid KWA header")
6341 kwa = kwa[4:]
6342 decrypted = decrypted[0:len(decrypted) - 12]
6343
6344 m = hmac.new(authkey, decrypted, hashlib.sha256)
6345 calc_kwa = m.digest()[0:8]
6346 if kwa != calc_kwa:
6347 raise Exception("KWA mismatch")
6348
6349 return decrypted
6350
6351 def zeropad_str(val, pad_len):
6352 while len(val) < pad_len * 2:
6353 val = '0' + val
6354 return val
6355
6356 def wsc_dh_init():
6357 # For now, use a hardcoded private key. In theory, this is supposed to be
6358 # randomly selected.
6359 own_private = 0x123456789
6360 own_public = pow(group_5_generator, own_private, group_5_prime)
6361 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6362 return own_private, pk
6363
6364 def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6365 peer_public = int(binascii.hexlify(peer_pk), 16)
6366 if peer_public < 2 or peer_public >= group_5_prime:
6367 raise Exception("Invalid peer public key")
6368 if pow(peer_public, (group_5_prime - 1) // 2, group_5_prime) != 1:
6369 raise Exception("Unexpected Legendre symbol for peer public key")
6370
6371 shared_secret = pow(peer_public, own_private, group_5_prime)
6372 ss = zeropad_str(format(shared_secret, "02x"), 192)
6373 logger.debug("DH shared secret: " + ss)
6374
6375 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6376 logger.debug("DHKey: " + binascii.hexlify(dhkey).decode())
6377
6378 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6379 kdk = m.digest()
6380 logger.debug("KDK: " + binascii.hexlify(kdk).decode())
6381 authkey,keywrapkey,emsk = wsc_keys(kdk)
6382 logger.debug("AuthKey: " + binascii.hexlify(authkey).decode())
6383 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey).decode())
6384 logger.debug("EMSK: " + binascii.hexlify(emsk).decode())
6385 return authkey,keywrapkey
6386
6387 def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6388 psk1,psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6389 logger.debug("PSK1: " + binascii.hexlify(psk1).decode())
6390 logger.debug("PSK2: " + binascii.hexlify(psk2).decode())
6391
6392 # Note: Secret values are supposed to be random, but hardcoded values are
6393 # fine for testing.
6394 s1 = 16*b'\x77'
6395 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6396 hash1 = m.digest()
6397 logger.debug("Hash1: " + binascii.hexlify(hash1).decode())
6398
6399 s2 = 16*b'\x88'
6400 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6401 hash2 = m.digest()
6402 logger.debug("Hash2: " + binascii.hexlify(hash2).decode())
6403 return s1,s2,hash1,hash2
6404
6405 def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6406 manufacturer='', model_name='', config_methods='\x00\x00'):
6407 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6408 attrs += build_attr_msg_type(WPS_M1)
6409 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6410 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6411 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6412 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6413 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6414 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6415 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6416 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6417 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6418 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6419 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6420 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6421 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6422 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6423 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6424 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6425 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6426 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6427 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6428 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6429 m1 = build_eap_wsc(2, eap_id, attrs)
6430 return m1, attrs
6431
6432 def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6433 dev_pw_id='\x00\x00', eap_code=1):
6434 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6435 attrs += build_attr_msg_type(WPS_M2)
6436 if e_nonce:
6437 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6438 if r_nonce:
6439 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6440 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6441 if r_pk:
6442 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6443 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6444 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6445 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6446 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6447 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6448 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6449 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6450 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6451 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6452 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6453 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6454 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6455 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6456 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6457 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6458 attrs += build_attr_authenticator(authkey, m1, attrs)
6459 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6460 return m2, attrs
6461
6462 def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6463 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6464 attrs += build_attr_msg_type(WPS_M2D)
6465 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6466 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6467 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6468 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6469 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6470 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6471 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6472 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6473 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6474 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6475 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6476 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6477 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6478 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6479 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6480 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6481 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6482 if dev_pw_id:
6483 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6484 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6485 return m2d, attrs
6486
6487 def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6488 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6489 if msg_type is not None:
6490 attrs += build_attr_msg_type(msg_type)
6491 if e_nonce:
6492 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6493 if r_nonce:
6494 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6495 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6496 return msg, attrs
6497
6498 def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6499 msg_type=WPS_WSC_NACK, eap_code=1):
6500 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6501 if msg_type is not None:
6502 attrs += build_attr_msg_type(msg_type)
6503 if e_nonce:
6504 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6505 if r_nonce:
6506 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6507 if config_error:
6508 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6509 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6510 return msg, attrs
6511
6512 def test_wps_ext(dev, apdev):
6513 """WPS against external implementation"""
6514 pin = "12345670"
6515 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6516 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6517 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6518
6519 logger.debug("Receive WSC/Start from AP")
6520 msg = get_wsc_msg(hapd)
6521 if msg['wsc_opcode'] != WSC_Start:
6522 raise Exception("Unexpected Op-Code for WSC/Start")
6523 wsc_start_id = msg['eap_identifier']
6524
6525 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6526 uuid_e = 16*b'\x11'
6527 e_nonce = 16*b'\x22'
6528 own_private, e_pk = wsc_dh_init()
6529
6530 logger.debug("Send M1 to AP")
6531 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6532 e_nonce, e_pk)
6533 send_wsc_msg(hapd, addr, m1)
6534
6535 logger.debug("Receive M2 from AP")
6536 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6537
6538 authkey,keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6539 mac_addr, e_nonce,
6540 m2_attrs[ATTR_REGISTRAR_NONCE])
6541 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6542 m2_attrs[ATTR_PUBLIC_KEY])
6543
6544 logger.debug("Send M3 to AP")
6545 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6546 attrs += build_attr_msg_type(WPS_M3)
6547 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6548 m2_attrs[ATTR_REGISTRAR_NONCE])
6549 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6550 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6551 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6552 raw_m3_attrs = attrs
6553 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6554 send_wsc_msg(hapd, addr, m3)
6555
6556 logger.debug("Receive M4 from AP")
6557 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6558
6559 logger.debug("Send M5 to AP")
6560 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6561 attrs += build_attr_msg_type(WPS_M5)
6562 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6563 m2_attrs[ATTR_REGISTRAR_NONCE])
6564 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6565 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6566 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6567 raw_m5_attrs = attrs
6568 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6569 send_wsc_msg(hapd, addr, m5)
6570
6571 logger.debug("Receive M6 from AP")
6572 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6573
6574 logger.debug("Send M7 to AP")
6575 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6576 attrs += build_attr_msg_type(WPS_M7)
6577 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6578 m2_attrs[ATTR_REGISTRAR_NONCE])
6579 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6580 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6581 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6582 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6583 raw_m7_attrs = attrs
6584 send_wsc_msg(hapd, addr, m7)
6585
6586 logger.debug("Receive M8 from AP")
6587 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6588 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6589 m8_attrs[ATTR_ENCR_SETTINGS])
6590 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred).decode())
6591
6592 logger.debug("Prepare WSC_Done")
6593 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6594 attrs += build_attr_msg_type(WPS_WSC_DONE)
6595 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6596 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6597 m2_attrs[ATTR_REGISTRAR_NONCE])
6598 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6599 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6600 # AP disconnects.
6601
6602 uuid_r = 16*b'\x33'
6603 r_nonce = 16*b'\x44'
6604
6605 eap_id = wsc_start_id
6606 logger.debug("Send WSC/Start to STA")
6607 wsc_start = build_eap_wsc(1, eap_id, b'', opcode=WSC_Start)
6608 send_wsc_msg(dev[0], bssid, wsc_start)
6609 eap_id = (eap_id + 1) % 256
6610
6611 logger.debug("Receive M1 from STA")
6612 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6613
6614 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6615 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6616 r_nonce)
6617 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6618 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6619
6620 logger.debug("Send M2 to STA")
6621 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6622 m1_attrs[ATTR_ENROLLEE_NONCE],
6623 r_nonce, uuid_r, e_pk)
6624 send_wsc_msg(dev[0], bssid, m2)
6625 eap_id = (eap_id + 1) % 256
6626
6627 logger.debug("Receive M3 from STA")
6628 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6629
6630 logger.debug("Send M4 to STA")
6631 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6632 attrs += build_attr_msg_type(WPS_M4)
6633 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6634 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6635 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6636 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6637 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6638 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6639 raw_m4_attrs = attrs
6640 m4 = build_eap_wsc(1, eap_id, attrs)
6641 send_wsc_msg(dev[0], bssid, m4)
6642 eap_id = (eap_id + 1) % 256
6643
6644 logger.debug("Receive M5 from STA")
6645 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6646
6647 logger.debug("Send M6 to STA")
6648 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6649 attrs += build_attr_msg_type(WPS_M6)
6650 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6651 m1_attrs[ATTR_ENROLLEE_NONCE])
6652 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6653 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6654 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6655 raw_m6_attrs = attrs
6656 m6 = build_eap_wsc(1, eap_id, attrs)
6657 send_wsc_msg(dev[0], bssid, m6)
6658 eap_id = (eap_id + 1) % 256
6659
6660 logger.debug("Receive M7 from STA")
6661 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6662
6663 logger.debug("Send M8 to STA")
6664 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6665 attrs += build_attr_msg_type(WPS_M8)
6666 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6667 m1_attrs[ATTR_ENROLLEE_NONCE])
6668 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6669 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6670 raw_m8_attrs = attrs
6671 m8 = build_eap_wsc(1, eap_id, attrs)
6672 send_wsc_msg(dev[0], bssid, m8)
6673 eap_id = (eap_id + 1) % 256
6674
6675 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6676 if ev is None:
6677 raise Exception("wpa_supplicant did not report credential")
6678
6679 logger.debug("Receive WSC_Done from STA")
6680 msg = get_wsc_msg(dev[0])
6681 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6682 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6683
6684 logger.debug("Send WSC_Done to AP")
6685 hapd.request("SET ext_eapol_frame_io 0")
6686 dev[0].request("SET ext_eapol_frame_io 0")
6687 send_wsc_msg(hapd, addr, wsc_done)
6688
6689 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6690 if ev is None:
6691 raise Exception("hostapd did not report WPS success")
6692
6693 dev[0].wait_connected()
6694
6695 def wps_start_kwa(dev, apdev):
6696 pin = "12345670"
6697 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6698 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6699 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6700 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6701
6702 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6703 uuid_r = 16*b'\x33'
6704 r_nonce = 16*b'\x44'
6705 own_private, e_pk = wsc_dh_init()
6706
6707 logger.debug("Receive M1 from STA")
6708 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6709 eap_id = (msg['eap_identifier'] + 1) % 256
6710
6711 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6712 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6713 r_nonce)
6714 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6715 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6716
6717 logger.debug("Send M2 to STA")
6718 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6719 m1_attrs[ATTR_ENROLLEE_NONCE],
6720 r_nonce, uuid_r, e_pk)
6721 send_wsc_msg(dev[0], bssid, m2)
6722 eap_id = (eap_id + 1) % 256
6723
6724 logger.debug("Receive M3 from STA")
6725 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6726
6727 logger.debug("Send M4 to STA")
6728 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6729 attrs += build_attr_msg_type(WPS_M4)
6730 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6731 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6732 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6733
6734 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6735
6736 def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6737 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6738 m4 = build_eap_wsc(1, eap_id, attrs)
6739 send_wsc_msg(dev[0], bssid, m4)
6740 eap_id = (eap_id + 1) % 256
6741
6742 logger.debug("Receive M5 from STA")
6743 msg = get_wsc_msg(dev[0])
6744 if msg['wsc_opcode'] != WSC_NACK:
6745 raise Exception("Unexpected message - expected WSC_Nack")
6746
6747 dev[0].request("WPS_CANCEL")
6748 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6749 dev[0].wait_disconnected()
6750
6751 def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6752 """WPS and KWA error: No KWA attribute"""
6753 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6754 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6755 # Encrypted Settings without KWA
6756 iv = 16*b'\x99'
6757 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6758 pad_len = 16 - len(data) % 16
6759 ps = pad_len * struct.pack('B', pad_len)
6760 data += ps
6761 wrapped = aes.encrypt(data)
6762 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6763 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6764
6765 def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6766 """WPS and KWA error: Data after KWA"""
6767 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6768 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6769 # Encrypted Settings and data after KWA
6770 m = hmac.new(authkey, data, hashlib.sha256)
6771 kwa = m.digest()[0:8]
6772 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6773 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6774 iv = 16*b'\x99'
6775 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6776 pad_len = 16 - len(data) % 16
6777 ps = pad_len * struct.pack('B', pad_len)
6778 data += ps
6779 wrapped = aes.encrypt(data)
6780 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6781 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6782
6783 def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6784 """WPS and KWA error: KWA mismatch"""
6785 r_s1,keywrapkey,authkey,raw_m3_attrs,eap_id,bssid,attrs = wps_start_kwa(dev, apdev)
6786 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6787 # Encrypted Settings and KWA with incorrect value
6788 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6789 iv = 16*b'\x99'
6790 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6791 pad_len = 16 - len(data) % 16
6792 ps = pad_len * struct.pack('B', pad_len)
6793 data += ps
6794 wrapped = aes.encrypt(data)
6795 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6796 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6797
6798 def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6799 pin = "12345670"
6800 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6801 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6802 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6803 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6804
6805 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6806 uuid_r = 16*b'\x33'
6807 r_nonce = 16*b'\x44'
6808 own_private, e_pk = wsc_dh_init()
6809
6810 logger.debug("Receive M1 from STA")
6811 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6812 eap_id = (msg['eap_identifier'] + 1) % 256
6813
6814 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6815 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6816 r_nonce)
6817 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
6818 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
6819
6820 logger.debug("Send M2 to STA")
6821 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6822 m1_attrs[ATTR_ENROLLEE_NONCE],
6823 r_nonce, uuid_r, e_pk)
6824 send_wsc_msg(dev[0], bssid, m2)
6825 eap_id = (eap_id + 1) % 256
6826
6827 logger.debug("Receive M3 from STA")
6828 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6829
6830 logger.debug("Send M4 to STA")
6831 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6832 attrs += build_attr_msg_type(WPS_M4)
6833 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6834 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6835 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6836 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6837 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6838 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6839 raw_m4_attrs = attrs
6840 m4 = build_eap_wsc(1, eap_id, attrs)
6841 send_wsc_msg(dev[0], bssid, m4)
6842 eap_id = (eap_id + 1) % 256
6843
6844 logger.debug("Receive M5 from STA")
6845 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6846
6847 logger.debug("Send M6 to STA")
6848 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6849 attrs += build_attr_msg_type(WPS_M6)
6850 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6851 m1_attrs[ATTR_ENROLLEE_NONCE])
6852 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6853 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6854 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6855 raw_m6_attrs = attrs
6856 m6 = build_eap_wsc(1, eap_id, attrs)
6857 send_wsc_msg(dev[0], bssid, m6)
6858 eap_id = (eap_id + 1) % 256
6859
6860 logger.debug("Receive M7 from STA")
6861 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6862
6863 logger.debug("Send M8 to STA")
6864 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6865 attrs += build_attr_msg_type(WPS_M8)
6866 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6867 m1_attrs[ATTR_ENROLLEE_NONCE])
6868 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6869 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6870 raw_m8_attrs = attrs
6871 m8 = build_eap_wsc(1, eap_id, attrs)
6872 send_wsc_msg(dev[0], bssid, m8)
6873 eap_id = (eap_id + 1) % 256
6874
6875 if no_connect:
6876 logger.debug("Receive WSC_Done from STA")
6877 msg = get_wsc_msg(dev[0])
6878 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6879 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6880
6881 hapd.request("SET ext_eapol_frame_io 0")
6882 dev[0].request("SET ext_eapol_frame_io 0")
6883
6884 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6885
6886 dev[0].wait_disconnected()
6887 dev[0].request("REMOVE_NETWORK all")
6888 elif connect:
6889 logger.debug("Receive WSC_Done from STA")
6890 msg = get_wsc_msg(dev[0])
6891 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6892 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6893
6894 hapd.request("SET ext_eapol_frame_io 0")
6895 dev[0].request("SET ext_eapol_frame_io 0")
6896
6897 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6898
6899 dev[0].wait_connected()
6900 else:
6901 # Verify STA NACK's the credential
6902 msg = get_wsc_msg(dev[0])
6903 if msg['wsc_opcode'] != WSC_NACK:
6904 raise Exception("Unexpected message - expected WSC_Nack")
6905 dev[0].request("WPS_CANCEL")
6906 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6907 dev[0].wait_disconnected()
6908
6909 def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6910 encr_type='\x00\x08', nw_key="12345678",
6911 mac_addr='\x00\x00\x00\x00\x00\x00'):
6912 attrs = b''
6913 if nw_idx is not None:
6914 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6915 if ssid is not None:
6916 attrs += build_wsc_attr(ATTR_SSID, ssid)
6917 if auth_type is not None:
6918 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6919 if encr_type is not None:
6920 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6921 if nw_key is not None:
6922 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6923 if mac_addr is not None:
6924 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6925 return build_wsc_attr(ATTR_CRED, attrs)
6926
6927 def test_wps_ext_cred_proto_success(dev, apdev):
6928 """WPS and Credential: success"""
6929 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6930 m8_cred = build_cred(mac_addr=mac_addr)
6931 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6932
6933 def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6934 """WPS and Credential: MAC Address mismatch"""
6935 m8_cred = build_cred()
6936 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6937
6938 def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6939 """WPS and Credential: zeropadded attributes"""
6940 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6941 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6942 nw_key="12345678\x00")
6943 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6944
6945 def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6946 """WPS and Credential: SSID missing"""
6947 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6948 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6949 wps_run_cred_proto(dev, apdev, m8_cred)
6950
6951 def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6952 """WPS and Credential: Zero-length SSID"""
6953 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6954 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6955 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6956
6957 def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6958 """WPS and Credential: Auth Type missing"""
6959 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6960 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
6961 wps_run_cred_proto(dev, apdev, m8_cred)
6962
6963 def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
6964 """WPS and Credential: Encr Type missing"""
6965 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6966 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
6967 wps_run_cred_proto(dev, apdev, m8_cred)
6968
6969 def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
6970 """WPS and Credential: Network Key missing"""
6971 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6972 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
6973 wps_run_cred_proto(dev, apdev, m8_cred)
6974
6975 def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
6976 """WPS and Credential: Network Key missing (open)"""
6977 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6978 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
6979 encr_type='\x00\x01', nw_key=None, ssid="foo")
6980 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6981
6982 def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
6983 """WPS and Credential: MAC Address missing"""
6984 m8_cred = build_cred(mac_addr=None)
6985 wps_run_cred_proto(dev, apdev, m8_cred)
6986
6987 def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
6988 """WPS and Credential: Invalid Encr Type"""
6989 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6990 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
6991 wps_run_cred_proto(dev, apdev, m8_cred)
6992
6993 def test_wps_ext_cred_proto_missing_cred(dev, apdev):
6994 """WPS and Credential: Missing Credential"""
6995 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6996 m8_cred = b''
6997 wps_run_cred_proto(dev, apdev, m8_cred)
6998
6999 def test_wps_ext_proto_m2_no_public_key(dev, apdev):
7000 """WPS and no Public Key in M2"""
7001 pin = "12345670"
7002 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7003 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7004 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7005 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7006
7007 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7008 uuid_r = 16*b'\x33'
7009 r_nonce = 16*b'\x44'
7010 own_private, e_pk = wsc_dh_init()
7011
7012 logger.debug("Receive M1 from STA")
7013 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7014 eap_id = (msg['eap_identifier'] + 1) % 256
7015
7016 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7017 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7018 r_nonce)
7019 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7020 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7021
7022 logger.debug("Send M2 to STA")
7023 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7024 m1_attrs[ATTR_ENROLLEE_NONCE],
7025 r_nonce, uuid_r, None)
7026 send_wsc_msg(dev[0], bssid, m2)
7027 eap_id = (eap_id + 1) % 256
7028
7029 # Verify STA NACK's the credential
7030 msg = get_wsc_msg(dev[0])
7031 if msg['wsc_opcode'] != WSC_NACK:
7032 raise Exception("Unexpected message - expected WSC_Nack")
7033 dev[0].request("WPS_CANCEL")
7034 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7035 dev[0].wait_disconnected()
7036
7037 def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
7038 """WPS and invalid Public Key in M2"""
7039 pin = "12345670"
7040 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7041 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7042 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7043 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7044
7045 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7046 uuid_r = 16*b'\x33'
7047 r_nonce = 16*b'\x44'
7048 own_private, e_pk = wsc_dh_init()
7049
7050 logger.debug("Receive M1 from STA")
7051 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7052 eap_id = (msg['eap_identifier'] + 1) % 256
7053
7054 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7055 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7056 r_nonce)
7057 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7058 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7059
7060 logger.debug("Send M2 to STA")
7061 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7062 m1_attrs[ATTR_ENROLLEE_NONCE],
7063 r_nonce, uuid_r, 192*b'\xff')
7064 send_wsc_msg(dev[0], bssid, m2)
7065 eap_id = (eap_id + 1) % 256
7066
7067 # Verify STA NACK's the credential
7068 msg = get_wsc_msg(dev[0])
7069 if msg['wsc_opcode'] != WSC_NACK:
7070 raise Exception("Unexpected message - expected WSC_Nack")
7071 dev[0].request("WPS_CANCEL")
7072 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7073 dev[0].wait_disconnected()
7074
7075 def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7076 """WPS and Public Key OOM in M2"""
7077 pin = "12345670"
7078 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7079 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7080 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7081 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7082
7083 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7084 uuid_r = 16*b'\x33'
7085 r_nonce = 16*b'\x44'
7086 own_private, e_pk = wsc_dh_init()
7087
7088 logger.debug("Receive M1 from STA")
7089 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7090 eap_id = (msg['eap_identifier'] + 1) % 256
7091
7092 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7093 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7094 r_nonce)
7095 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7096 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7097
7098 logger.debug("Send M2 to STA")
7099 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7100 m1_attrs[ATTR_ENROLLEE_NONCE],
7101 r_nonce, uuid_r, e_pk)
7102 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7103 send_wsc_msg(dev[0], bssid, m2)
7104 eap_id = (eap_id + 1) % 256
7105
7106 # Verify STA NACK's the credential
7107 msg = get_wsc_msg(dev[0])
7108 if msg['wsc_opcode'] != WSC_NACK:
7109 raise Exception("Unexpected message - expected WSC_Nack")
7110 dev[0].request("WPS_CANCEL")
7111 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7112 dev[0].wait_disconnected()
7113
7114 def test_wps_ext_proto_nack_m3(dev, apdev):
7115 """WPS and NACK M3"""
7116 pin = "12345670"
7117 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7118 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7119 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7120 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7121
7122 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7123 uuid_r = 16*b'\x33'
7124 r_nonce = 16*b'\x44'
7125 own_private, e_pk = wsc_dh_init()
7126
7127 logger.debug("Receive M1 from STA")
7128 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7129 eap_id = (msg['eap_identifier'] + 1) % 256
7130
7131 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7132 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7133 r_nonce)
7134 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7135 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7136
7137 logger.debug("Send M2 to STA")
7138 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7139 m1_attrs[ATTR_ENROLLEE_NONCE],
7140 r_nonce, uuid_r, e_pk)
7141 send_wsc_msg(dev[0], bssid, m2)
7142 eap_id = (eap_id + 1) % 256
7143
7144 logger.debug("Receive M3 from STA")
7145 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7146
7147 logger.debug("Send NACK to STA")
7148 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7149 r_nonce, config_error='\x01\x23')
7150 send_wsc_msg(dev[0], bssid, msg)
7151 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7152 if ev is None:
7153 raise Exception("Failure not reported")
7154 if "msg=7 config_error=291" not in ev:
7155 raise Exception("Unexpected failure reason: " + ev)
7156
7157 def test_wps_ext_proto_nack_m5(dev, apdev):
7158 """WPS and NACK M5"""
7159 pin = "12345670"
7160 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7161 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7162 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7163 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7164
7165 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7166 uuid_r = 16*b'\x33'
7167 r_nonce = 16*b'\x44'
7168 own_private, e_pk = wsc_dh_init()
7169
7170 logger.debug("Receive M1 from STA")
7171 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7172 eap_id = (msg['eap_identifier'] + 1) % 256
7173
7174 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7175 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7176 r_nonce)
7177 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7178 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7179
7180 logger.debug("Send M2 to STA")
7181 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7182 m1_attrs[ATTR_ENROLLEE_NONCE],
7183 r_nonce, uuid_r, e_pk)
7184 send_wsc_msg(dev[0], bssid, m2)
7185 eap_id = (eap_id + 1) % 256
7186
7187 logger.debug("Receive M3 from STA")
7188 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7189
7190 logger.debug("Send M4 to STA")
7191 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7192 attrs += build_attr_msg_type(WPS_M4)
7193 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7194 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7195 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7196 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7197 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7198 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7199 raw_m4_attrs = attrs
7200 m4 = build_eap_wsc(1, eap_id, attrs)
7201 send_wsc_msg(dev[0], bssid, m4)
7202 eap_id = (eap_id + 1) % 256
7203
7204 logger.debug("Receive M5 from STA")
7205 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7206
7207 logger.debug("Send NACK to STA")
7208 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7209 r_nonce, config_error='\x01\x24')
7210 send_wsc_msg(dev[0], bssid, msg)
7211 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7212 if ev is None:
7213 raise Exception("Failure not reported")
7214 if "msg=9 config_error=292" not in ev:
7215 raise Exception("Unexpected failure reason: " + ev)
7216
7217 def wps_nack_m3(dev, apdev):
7218 pin = "00000000"
7219 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7220 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7221 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7222 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7223
7224 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7225 uuid_r = 16*b'\x33'
7226 r_nonce = 16*b'\x44'
7227 own_private, e_pk = wsc_dh_init()
7228
7229 logger.debug("Receive M1 from STA")
7230 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7231 eap_id = (msg['eap_identifier'] + 1) % 256
7232
7233 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7234 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7235 r_nonce)
7236 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7237 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7238
7239 logger.debug("Send M2 to STA")
7240 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7241 m1_attrs[ATTR_ENROLLEE_NONCE],
7242 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7243 send_wsc_msg(dev[0], bssid, m2)
7244 eap_id = (eap_id + 1) % 256
7245
7246 logger.debug("Receive M3 from STA")
7247 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7248 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7249
7250 def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7251 """WPS and NACK M3 missing Config Error"""
7252 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7253 logger.debug("Send NACK to STA")
7254 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7255 send_wsc_msg(dev[0], bssid, msg)
7256 dev[0].request("WPS_CANCEL")
7257 dev[0].wait_disconnected()
7258 dev[0].flush_scan_cache()
7259
7260 def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7261 """WPS and NACK M3 missing E-Nonce"""
7262 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7263 logger.debug("Send NACK to STA")
7264 msg, attrs = build_nack(eap_id, None, r_nonce)
7265 send_wsc_msg(dev[0], bssid, msg)
7266 dev[0].request("WPS_CANCEL")
7267 dev[0].wait_disconnected()
7268 dev[0].flush_scan_cache()
7269
7270 def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7271 """WPS and NACK M3 E-Nonce mismatch"""
7272 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7273 logger.debug("Send NACK to STA")
7274 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7275 send_wsc_msg(dev[0], bssid, msg)
7276 dev[0].request("WPS_CANCEL")
7277 dev[0].wait_disconnected()
7278 dev[0].flush_scan_cache()
7279
7280 def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7281 """WPS and NACK M3 missing R-Nonce"""
7282 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7283 logger.debug("Send NACK to STA")
7284 msg, attrs = build_nack(eap_id, e_nonce, None)
7285 send_wsc_msg(dev[0], bssid, msg)
7286 dev[0].request("WPS_CANCEL")
7287 dev[0].wait_disconnected()
7288 dev[0].flush_scan_cache()
7289
7290 def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7291 """WPS and NACK M3 R-Nonce mismatch"""
7292 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7293 logger.debug("Send NACK to STA")
7294 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7295 send_wsc_msg(dev[0], bssid, msg)
7296 dev[0].request("WPS_CANCEL")
7297 dev[0].wait_disconnected()
7298 dev[0].flush_scan_cache()
7299
7300 def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7301 """WPS and NACK M3 no Message Type"""
7302 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7303 logger.debug("Send NACK to STA")
7304 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7305 send_wsc_msg(dev[0], bssid, msg)
7306 dev[0].request("WPS_CANCEL")
7307 dev[0].wait_disconnected()
7308 dev[0].flush_scan_cache()
7309
7310 def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7311 """WPS and NACK M3 invalid Message Type"""
7312 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7313 logger.debug("Send NACK to STA")
7314 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7315 send_wsc_msg(dev[0], bssid, msg)
7316 dev[0].request("WPS_CANCEL")
7317 dev[0].wait_disconnected()
7318 dev[0].flush_scan_cache()
7319
7320 def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7321 """WPS and NACK M3 invalid attribute"""
7322 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7323 logger.debug("Send NACK to STA")
7324 attrs = b'\x10\x10\x00'
7325 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7326 send_wsc_msg(dev[0], bssid, msg)
7327 dev[0].request("WPS_CANCEL")
7328 dev[0].wait_disconnected()
7329 dev[0].flush_scan_cache()
7330
7331 def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7332 """WPS and ACK M3 missing E-Nonce"""
7333 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7334 logger.debug("Send NACK to STA")
7335 msg, attrs = build_ack(eap_id, None, r_nonce)
7336 send_wsc_msg(dev[0], bssid, msg)
7337 dev[0].request("WPS_CANCEL")
7338 dev[0].wait_disconnected()
7339 dev[0].flush_scan_cache()
7340
7341 def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7342 """WPS and ACK M3 E-Nonce mismatch"""
7343 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7344 logger.debug("Send NACK to STA")
7345 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7346 send_wsc_msg(dev[0], bssid, msg)
7347 dev[0].request("WPS_CANCEL")
7348 dev[0].wait_disconnected()
7349 dev[0].flush_scan_cache()
7350
7351 def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7352 """WPS and ACK M3 missing R-Nonce"""
7353 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7354 logger.debug("Send NACK to STA")
7355 msg, attrs = build_ack(eap_id, e_nonce, None)
7356 send_wsc_msg(dev[0], bssid, msg)
7357 dev[0].request("WPS_CANCEL")
7358 dev[0].wait_disconnected()
7359 dev[0].flush_scan_cache()
7360
7361 def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7362 """WPS and ACK M3 R-Nonce mismatch"""
7363 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7364 logger.debug("Send NACK to STA")
7365 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7366 send_wsc_msg(dev[0], bssid, msg)
7367 dev[0].request("WPS_CANCEL")
7368 dev[0].wait_disconnected()
7369 dev[0].flush_scan_cache()
7370
7371 def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7372 """WPS and ACK M3 no Message Type"""
7373 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7374 logger.debug("Send NACK to STA")
7375 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7376 send_wsc_msg(dev[0], bssid, msg)
7377 dev[0].request("WPS_CANCEL")
7378 dev[0].wait_disconnected()
7379 dev[0].flush_scan_cache()
7380
7381 def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7382 """WPS and ACK M3 invalid Message Type"""
7383 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7384 logger.debug("Send NACK to STA")
7385 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7386 send_wsc_msg(dev[0], bssid, msg)
7387 dev[0].request("WPS_CANCEL")
7388 dev[0].wait_disconnected()
7389 dev[0].flush_scan_cache()
7390
7391 def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7392 """WPS and ACK M3 invalid attribute"""
7393 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7394 logger.debug("Send ACK to STA")
7395 attrs = b'\x10\x10\x00'
7396 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7397 send_wsc_msg(dev[0], bssid, msg)
7398 dev[0].request("WPS_CANCEL")
7399 dev[0].wait_disconnected()
7400 dev[0].flush_scan_cache()
7401
7402 def test_wps_ext_proto_ack_m3(dev, apdev):
7403 """WPS and ACK M3"""
7404 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7405 logger.debug("Send ACK to STA")
7406 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7407 send_wsc_msg(dev[0], bssid, msg)
7408 dev[0].request("WPS_CANCEL")
7409 dev[0].wait_disconnected()
7410 dev[0].flush_scan_cache()
7411
7412 def wps_to_m3_helper(dev, apdev):
7413 pin = "12345670"
7414 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7415 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7416 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7417 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7418
7419 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7420 uuid_r = 16*b'\x33'
7421 r_nonce = 16*b'\x44'
7422 own_private, e_pk = wsc_dh_init()
7423
7424 logger.debug("Receive M1 from STA")
7425 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7426 eap_id = (msg['eap_identifier'] + 1) % 256
7427
7428 authkey,keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7429 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7430 r_nonce)
7431 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, pin,
7432 m1_attrs[ATTR_PUBLIC_KEY], e_pk)
7433
7434 logger.debug("Send M2 to STA")
7435 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7436 m1_attrs[ATTR_ENROLLEE_NONCE],
7437 r_nonce, uuid_r, e_pk)
7438 send_wsc_msg(dev[0], bssid, m2)
7439 eap_id = (eap_id + 1) % 256
7440
7441 logger.debug("Receive M3 from STA")
7442 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7443 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7444
7445 def wps_to_m3(dev, apdev):
7446 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)
7447 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7448
7449 def wps_to_m5(dev, apdev):
7450 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)
7451
7452 logger.debug("Send M4 to STA")
7453 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7454 attrs += build_attr_msg_type(WPS_M4)
7455 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7456 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7457 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7458 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7459 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7460 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7461 raw_m4_attrs = attrs
7462 m4 = build_eap_wsc(1, eap_id, attrs)
7463 send_wsc_msg(dev[0], bssid, m4)
7464 eap_id = (eap_id + 1) % 256
7465
7466 logger.debug("Receive M5 from STA")
7467 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7468
7469 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7470
7471 def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7472 """WPS and no R-Hash1 in M4"""
7473 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7474
7475 logger.debug("Send M4 to STA")
7476 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7477 attrs += build_attr_msg_type(WPS_M4)
7478 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7479 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7480 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7481 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7482 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7483 attrs += build_attr_authenticator(authkey, m3, attrs)
7484 m4 = build_eap_wsc(1, eap_id, attrs)
7485 send_wsc_msg(dev[0], bssid, m4)
7486 eap_id = (eap_id + 1) % 256
7487
7488 logger.debug("Receive M5 (NACK) from STA")
7489 msg = get_wsc_msg(dev[0])
7490 if msg['wsc_opcode'] != WSC_NACK:
7491 raise Exception("Unexpected message - expected WSC_Nack")
7492
7493 dev[0].request("WPS_CANCEL")
7494 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7495 dev[0].wait_disconnected()
7496
7497 def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7498 """WPS and no R-Hash2 in M4"""
7499 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7500
7501 logger.debug("Send M4 to STA")
7502 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7503 attrs += build_attr_msg_type(WPS_M4)
7504 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7505 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7506 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7507 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7508 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7509 attrs += build_attr_authenticator(authkey, m3, attrs)
7510 m4 = build_eap_wsc(1, eap_id, attrs)
7511 send_wsc_msg(dev[0], bssid, m4)
7512 eap_id = (eap_id + 1) % 256
7513
7514 logger.debug("Receive M5 (NACK) from STA")
7515 msg = get_wsc_msg(dev[0])
7516 if msg['wsc_opcode'] != WSC_NACK:
7517 raise Exception("Unexpected message - expected WSC_Nack")
7518
7519 dev[0].request("WPS_CANCEL")
7520 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7521 dev[0].wait_disconnected()
7522
7523 def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7524 """WPS and no R-SNonce1 in M4"""
7525 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7526
7527 logger.debug("Send M4 to STA")
7528 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7529 attrs += build_attr_msg_type(WPS_M4)
7530 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7531 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7532 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7533 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7534 data = b''
7535 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7536 attrs += build_attr_authenticator(authkey, m3, attrs)
7537 m4 = build_eap_wsc(1, eap_id, attrs)
7538 send_wsc_msg(dev[0], bssid, m4)
7539 eap_id = (eap_id + 1) % 256
7540
7541 logger.debug("Receive M5 (NACK) from STA")
7542 msg = get_wsc_msg(dev[0])
7543 if msg['wsc_opcode'] != WSC_NACK:
7544 raise Exception("Unexpected message - expected WSC_Nack")
7545
7546 dev[0].request("WPS_CANCEL")
7547 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7548 dev[0].wait_disconnected()
7549
7550 def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7551 """WPS and invalid pad string in M4"""
7552 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7553
7554 logger.debug("Send M4 to STA")
7555 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7556 attrs += build_attr_msg_type(WPS_M4)
7557 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7558 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7559 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7560 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7561
7562 m = hmac.new(authkey, data, hashlib.sha256)
7563 kwa = m.digest()[0:8]
7564 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7565 iv = 16*b'\x99'
7566 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7567 pad_len = 16 - len(data) % 16
7568 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7569 data += ps
7570 wrapped = aes.encrypt(data)
7571 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7572
7573 attrs += build_attr_authenticator(authkey, m3, attrs)
7574 m4 = build_eap_wsc(1, eap_id, attrs)
7575 send_wsc_msg(dev[0], bssid, m4)
7576 eap_id = (eap_id + 1) % 256
7577
7578 logger.debug("Receive M5 (NACK) from STA")
7579 msg = get_wsc_msg(dev[0])
7580 if msg['wsc_opcode'] != WSC_NACK:
7581 raise Exception("Unexpected message - expected WSC_Nack")
7582
7583 dev[0].request("WPS_CANCEL")
7584 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7585 dev[0].wait_disconnected()
7586
7587 def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7588 """WPS and invalid pad value in M4"""
7589 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7590
7591 logger.debug("Send M4 to STA")
7592 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7593 attrs += build_attr_msg_type(WPS_M4)
7594 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7595 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7596 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7597 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7598
7599 m = hmac.new(authkey, data, hashlib.sha256)
7600 kwa = m.digest()[0:8]
7601 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7602 iv = 16*b'\x99'
7603 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7604 pad_len = 16 - len(data) % 16
7605 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7606 data += ps
7607 wrapped = aes.encrypt(data)
7608 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7609
7610 attrs += build_attr_authenticator(authkey, m3, attrs)
7611 m4 = build_eap_wsc(1, eap_id, attrs)
7612 send_wsc_msg(dev[0], bssid, m4)
7613 eap_id = (eap_id + 1) % 256
7614
7615 logger.debug("Receive M5 (NACK) from STA")
7616 msg = get_wsc_msg(dev[0])
7617 if msg['wsc_opcode'] != WSC_NACK:
7618 raise Exception("Unexpected message - expected WSC_Nack")
7619
7620 dev[0].request("WPS_CANCEL")
7621 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7622 dev[0].wait_disconnected()
7623
7624 def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7625 """WPS and no Encr Settings in M4"""
7626 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7627
7628 logger.debug("Send M4 to STA")
7629 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7630 attrs += build_attr_msg_type(WPS_M4)
7631 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7632 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7633 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7634 attrs += build_attr_authenticator(authkey, m3, attrs)
7635 m4 = build_eap_wsc(1, eap_id, attrs)
7636 send_wsc_msg(dev[0], bssid, m4)
7637 eap_id = (eap_id + 1) % 256
7638
7639 logger.debug("Receive M5 (NACK) from STA")
7640 msg = get_wsc_msg(dev[0])
7641 if msg['wsc_opcode'] != WSC_NACK:
7642 raise Exception("Unexpected message - expected WSC_Nack")
7643
7644 dev[0].request("WPS_CANCEL")
7645 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7646 dev[0].wait_disconnected()
7647
7648 def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7649 """WPS and no R-SNonce2 in M6"""
7650 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7651
7652 logger.debug("Send M6 to STA")
7653 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7654 attrs += build_attr_msg_type(WPS_M6)
7655 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7656 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7657 data = b''
7658 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7659 attrs += build_attr_authenticator(authkey, m5, attrs)
7660 m6 = build_eap_wsc(1, eap_id, attrs)
7661 send_wsc_msg(dev[0], bssid, m6)
7662 eap_id = (eap_id + 1) % 256
7663
7664 logger.debug("Receive M7 (NACK) from STA")
7665 msg = get_wsc_msg(dev[0])
7666 if msg['wsc_opcode'] != WSC_NACK:
7667 raise Exception("Unexpected message - expected WSC_Nack")
7668
7669 dev[0].request("WPS_CANCEL")
7670 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7671 dev[0].wait_disconnected()
7672
7673 def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7674 """WPS and no Encr Settings in M6"""
7675 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7676
7677 logger.debug("Send M6 to STA")
7678 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7679 attrs += build_attr_msg_type(WPS_M6)
7680 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7681 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7682 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7683 attrs += build_attr_authenticator(authkey, m5, attrs)
7684 m6 = build_eap_wsc(1, eap_id, attrs)
7685 send_wsc_msg(dev[0], bssid, m6)
7686 eap_id = (eap_id + 1) % 256
7687
7688 logger.debug("Receive M7 (NACK) from STA")
7689 msg = get_wsc_msg(dev[0])
7690 if msg['wsc_opcode'] != WSC_NACK:
7691 raise Exception("Unexpected message - expected WSC_Nack")
7692
7693 dev[0].request("WPS_CANCEL")
7694 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7695 dev[0].wait_disconnected()
7696
7697 def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7698 """WPS and no Encr Settings in M6"""
7699 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7700
7701 logger.debug("Send M6 to STA")
7702 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7703 attrs += build_attr_msg_type(WPS_M6)
7704 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7705 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7706 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7707 attrs += build_attr_authenticator(authkey, m5, attrs)
7708 raw_m6_attrs = attrs
7709 m6 = build_eap_wsc(1, eap_id, attrs)
7710 send_wsc_msg(dev[0], bssid, m6)
7711 eap_id = (eap_id + 1) % 256
7712
7713 logger.debug("Receive M7 from STA")
7714 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7715
7716 logger.debug("Send M8 to STA")
7717 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7718 attrs += build_attr_msg_type(WPS_M8)
7719 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7720 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7721 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7722 raw_m8_attrs = attrs
7723 m8 = build_eap_wsc(1, eap_id, attrs)
7724 send_wsc_msg(dev[0], bssid, m8)
7725
7726 logger.debug("Receive WSC_Done (NACK) from STA")
7727 msg = get_wsc_msg(dev[0])
7728 if msg['wsc_opcode'] != WSC_NACK:
7729 raise Exception("Unexpected message - expected WSC_Nack")
7730
7731 dev[0].request("WPS_CANCEL")
7732 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7733 dev[0].wait_disconnected()
7734
7735 def wps_start_ext_reg(apdev, dev):
7736 addr = dev.own_addr()
7737 bssid = apdev['bssid']
7738 ssid = "test-wps-conf"
7739 appin = "12345670"
7740 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
7741 "wpa_passphrase": "12345678", "wpa": "2",
7742 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7743 "ap_pin": appin }
7744 hapd = hostapd.add_ap(apdev, params)
7745
7746 dev.scan_for_bss(bssid, freq="2412")
7747 hapd.request("SET ext_eapol_frame_io 1")
7748 dev.request("SET ext_eapol_frame_io 1")
7749
7750 dev.request("WPS_REG " + bssid + " " + appin)
7751
7752 return addr,bssid,hapd
7753
7754 def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7755 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7756 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7757 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7758
7759 logger.debug("Receive M1 from AP")
7760 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7761 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7762 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7763 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7764
7765 appin = '12345670'
7766 uuid_r = 16*b'\x33'
7767 r_nonce = 16*b'\x44'
7768 own_private, r_pk = wsc_dh_init()
7769 authkey,keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7770 r_nonce)
7771 r_s1,r_s2,r_hash1,r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7772
7773 logger.debug("Send M2 to AP")
7774 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7775 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7776 send_wsc_msg(hapd, addr, m2)
7777
7778 logger.debug("Receive M3 from AP")
7779 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7780
7781 logger.debug("Send M4 to AP")
7782 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7783 attrs += build_attr_msg_type(WPS_M4)
7784 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7785 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7786 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7787 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7788 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7789 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7790 raw_m4_attrs = attrs
7791 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7792 send_wsc_msg(hapd, addr, m4)
7793
7794 logger.debug("Receive M5 from AP")
7795 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7796
7797 logger.debug("Send M6 to STA")
7798 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7799 attrs += build_attr_msg_type(WPS_M6)
7800 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7801 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7802 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7803 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7804 raw_m6_attrs = attrs
7805 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7806 send_wsc_msg(hapd, addr, m6)
7807
7808 logger.debug("Receive M7 from AP")
7809 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7810
7811 logger.debug("Send M8 to STA")
7812 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7813 attrs += build_attr_msg_type(WPS_M8)
7814 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7815 if ap_settings:
7816 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7817 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7818 raw_m8_attrs = attrs
7819 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7820 send_wsc_msg(hapd, addr, m8)
7821
7822 if success:
7823 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7824 if ev is None:
7825 raise Exception("New AP settings not reported")
7826 logger.debug("Receive WSC_Done from AP")
7827 msg = get_wsc_msg(hapd)
7828 if msg['wsc_opcode'] != WSC_Done:
7829 raise Exception("Unexpected message - expected WSC_Done")
7830
7831 logger.debug("Send WSC_ACK to AP")
7832 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7833 eap_code=2)
7834 send_wsc_msg(hapd, addr, ack)
7835 dev[0].wait_disconnected()
7836 else:
7837 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7838 if ev is None:
7839 raise Exception("WPS failure not reported")
7840 logger.debug("Receive WSC_NACK from AP")
7841 msg = get_wsc_msg(hapd)
7842 if msg['wsc_opcode'] != WSC_NACK:
7843 raise Exception("Unexpected message - expected WSC_NACK")
7844
7845 logger.debug("Send WSC_NACK to AP")
7846 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7847 eap_code=2)
7848 send_wsc_msg(hapd, addr, nack)
7849 dev[0].wait_disconnected()
7850
7851 def test_wps_ext_ap_settings_success(dev, apdev):
7852 """WPS and AP Settings: success"""
7853 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7854 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7855 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7856 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7857 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7858 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7859 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7860
7861 @remote_compatible
7862 def test_wps_ext_ap_settings_missing(dev, apdev):
7863 """WPS and AP Settings: missing"""
7864 wps_run_ap_settings_proto(dev, apdev, None, False)
7865
7866 @remote_compatible
7867 def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7868 """WPS and AP Settings: MAC Address mismatch"""
7869 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7870 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7871 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7872 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7873 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7874 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7875 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7876
7877 @remote_compatible
7878 def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7879 """WPS and AP Settings: missing MAC Address"""
7880 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7881 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7882 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7883 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7884 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7885 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7886
7887 @remote_compatible
7888 def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7889 """WPS and AP Settings: reject Encr Type"""
7890 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7891 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7892 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7893 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7894 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7895 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7896 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7897
7898 @remote_compatible
7899 def test_wps_ext_ap_settings_m2d(dev, apdev):
7900 """WPS and AP Settings: M2D"""
7901 addr,bssid,hapd = wps_start_ext_reg(apdev[0], dev[0])
7902 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7903 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7904
7905 logger.debug("Receive M1 from AP")
7906 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7907 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7908
7909 r_nonce = 16*'\x44'
7910 uuid_r = 16*'\x33'
7911
7912 logger.debug("Send M2D to AP")
7913 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7914 e_nonce, r_nonce, uuid_r,
7915 dev_pw_id='\x00\x00', eap_code=2)
7916 send_wsc_msg(hapd, addr, m2d)
7917
7918 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7919 if ev is None:
7920 raise Exception("M2D not reported")
7921
7922 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7923
7924 def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7925 logger.debug("Receive WSC_NACK from AP")
7926 msg = get_wsc_msg(hapd)
7927 if msg['wsc_opcode'] != WSC_NACK:
7928 raise Exception("Unexpected message - expected WSC_NACK")
7929
7930 logger.debug("Send WSC_NACK to AP")
7931 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7932 eap_code=2)
7933 send_wsc_msg(hapd, dev.own_addr(), nack)
7934 dev.wait_disconnected()
7935
7936 @remote_compatible
7937 def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7938 """WPS proto: M3 missing E-Hash1"""
7939 pin = "12345670"
7940 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7941 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7942 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7943
7944 logger.debug("Receive WSC/Start from AP")
7945 msg = get_wsc_msg(hapd)
7946 if msg['wsc_opcode'] != WSC_Start:
7947 raise Exception("Unexpected Op-Code for WSC/Start")
7948
7949 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7950 uuid_e = 16*b'\x11'
7951 e_nonce = 16*b'\x22'
7952 own_private, e_pk = wsc_dh_init()
7953
7954 logger.debug("Send M1 to AP")
7955 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
7956 e_nonce, e_pk)
7957 send_wsc_msg(hapd, addr, m1)
7958
7959 logger.debug("Receive M2 from AP")
7960 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
7961 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
7962 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
7963
7964 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
7965 r_nonce)
7966 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
7967
7968 logger.debug("Send M3 to AP")
7969 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7970 attrs += build_attr_msg_type(WPS_M3)
7971 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
7972 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
7973 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
7974 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
7975 raw_m3_attrs = attrs
7976 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7977 send_wsc_msg(hapd, addr, m3)
7978
7979 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7980
7981 @remote_compatible
7982 def test_wps_ext_m3_missing_e_hash2(dev, apdev):
7983 """WPS proto: M3 missing E-Hash2"""
7984 pin = "12345670"
7985 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7986 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7987 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7988
7989 logger.debug("Receive WSC/Start from AP")
7990 msg = get_wsc_msg(hapd)
7991 if msg['wsc_opcode'] != WSC_Start:
7992 raise Exception("Unexpected Op-Code for WSC/Start")
7993
7994 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7995 uuid_e = 16*b'\x11'
7996 e_nonce = 16*b'\x22'
7997 own_private, e_pk = wsc_dh_init()
7998
7999 logger.debug("Send M1 to AP")
8000 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8001 e_nonce, e_pk)
8002 send_wsc_msg(hapd, addr, m1)
8003
8004 logger.debug("Receive M2 from AP")
8005 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8006 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8007 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8008
8009 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8010 r_nonce)
8011 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8012
8013 logger.debug("Send M3 to AP")
8014 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8015 attrs += build_attr_msg_type(WPS_M3)
8016 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8017 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8018 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8019 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8020 raw_m3_attrs = attrs
8021 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8022 send_wsc_msg(hapd, addr, m3)
8023
8024 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8025
8026 @remote_compatible
8027 def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
8028 """WPS proto: M5 missing E-SNonce1"""
8029 pin = "12345670"
8030 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8031 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8032 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8033
8034 logger.debug("Receive WSC/Start from AP")
8035 msg = get_wsc_msg(hapd)
8036 if msg['wsc_opcode'] != WSC_Start:
8037 raise Exception("Unexpected Op-Code for WSC/Start")
8038
8039 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8040 uuid_e = 16*b'\x11'
8041 e_nonce = 16*b'\x22'
8042 own_private, e_pk = wsc_dh_init()
8043
8044 logger.debug("Send M1 to AP")
8045 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8046 e_nonce, e_pk)
8047 send_wsc_msg(hapd, addr, m1)
8048
8049 logger.debug("Receive M2 from AP")
8050 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8051 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8052 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8053
8054 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8055 r_nonce)
8056 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8057
8058 logger.debug("Send M3 to AP")
8059 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8060 attrs += build_attr_msg_type(WPS_M3)
8061 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8062 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8063 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8064 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8065 raw_m3_attrs = attrs
8066 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8067 send_wsc_msg(hapd, addr, m3)
8068
8069 logger.debug("Receive M4 from AP")
8070 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8071
8072 logger.debug("Send M5 to AP")
8073 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8074 attrs += build_attr_msg_type(WPS_M5)
8075 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8076 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8077 data = b''
8078 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8079 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8080 raw_m5_attrs = attrs
8081 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8082 send_wsc_msg(hapd, addr, m5)
8083
8084 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8085
8086 @remote_compatible
8087 def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8088 """WPS proto: M5 E-SNonce1 mismatch"""
8089 pin = "12345670"
8090 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8091 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8092 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8093
8094 logger.debug("Receive WSC/Start from AP")
8095 msg = get_wsc_msg(hapd)
8096 if msg['wsc_opcode'] != WSC_Start:
8097 raise Exception("Unexpected Op-Code for WSC/Start")
8098
8099 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8100 uuid_e = 16*b'\x11'
8101 e_nonce = 16*b'\x22'
8102 own_private, e_pk = wsc_dh_init()
8103
8104 logger.debug("Send M1 to AP")
8105 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8106 e_nonce, e_pk)
8107 send_wsc_msg(hapd, addr, m1)
8108
8109 logger.debug("Receive M2 from AP")
8110 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8111 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8112 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8113
8114 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8115 r_nonce)
8116 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8117
8118 logger.debug("Send M3 to AP")
8119 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8120 attrs += build_attr_msg_type(WPS_M3)
8121 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8122 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8123 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8124 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8125 raw_m3_attrs = attrs
8126 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8127 send_wsc_msg(hapd, addr, m3)
8128
8129 logger.debug("Receive M4 from AP")
8130 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8131
8132 logger.debug("Send M5 to AP")
8133 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8134 attrs += build_attr_msg_type(WPS_M5)
8135 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8136 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8137 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8138 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8139 raw_m5_attrs = attrs
8140 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8141 send_wsc_msg(hapd, addr, m5)
8142
8143 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8144
8145 def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8146 """WPS proto: M7 missing E-SNonce2"""
8147 pin = "12345670"
8148 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8149 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8150 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8151
8152 logger.debug("Receive WSC/Start from AP")
8153 msg = get_wsc_msg(hapd)
8154 if msg['wsc_opcode'] != WSC_Start:
8155 raise Exception("Unexpected Op-Code for WSC/Start")
8156
8157 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8158 uuid_e = 16*b'\x11'
8159 e_nonce = 16*b'\x22'
8160 own_private, e_pk = wsc_dh_init()
8161
8162 logger.debug("Send M1 to AP")
8163 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8164 e_nonce, e_pk)
8165 send_wsc_msg(hapd, addr, m1)
8166
8167 logger.debug("Receive M2 from AP")
8168 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8169 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8170 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8171
8172 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8173 r_nonce)
8174 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8175
8176 logger.debug("Send M3 to AP")
8177 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8178 attrs += build_attr_msg_type(WPS_M3)
8179 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8180 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8181 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8182 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8183 raw_m3_attrs = attrs
8184 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8185 send_wsc_msg(hapd, addr, m3)
8186
8187 logger.debug("Receive M4 from AP")
8188 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8189
8190 logger.debug("Send M5 to AP")
8191 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8192 attrs += build_attr_msg_type(WPS_M5)
8193 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8194 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8195 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8196 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8197 raw_m5_attrs = attrs
8198 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8199 send_wsc_msg(hapd, addr, m5)
8200
8201 logger.debug("Receive M6 from AP")
8202 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8203
8204 logger.debug("Send M7 to AP")
8205 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8206 attrs += build_attr_msg_type(WPS_M7)
8207 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8208 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8209 data = b''
8210 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8211 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8212 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8213 raw_m7_attrs = attrs
8214 send_wsc_msg(hapd, addr, m7)
8215
8216 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8217
8218 @remote_compatible
8219 def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8220 """WPS proto: M7 E-SNonce2 mismatch"""
8221 pin = "12345670"
8222 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8223 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8224 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8225
8226 logger.debug("Receive WSC/Start from AP")
8227 msg = get_wsc_msg(hapd)
8228 if msg['wsc_opcode'] != WSC_Start:
8229 raise Exception("Unexpected Op-Code for WSC/Start")
8230
8231 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8232 uuid_e = 16*b'\x11'
8233 e_nonce = 16*b'\x22'
8234 own_private, e_pk = wsc_dh_init()
8235
8236 logger.debug("Send M1 to AP")
8237 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8238 e_nonce, e_pk)
8239 send_wsc_msg(hapd, addr, m1)
8240
8241 logger.debug("Receive M2 from AP")
8242 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8243 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8244 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8245
8246 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8247 r_nonce)
8248 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8249
8250 logger.debug("Send M3 to AP")
8251 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8252 attrs += build_attr_msg_type(WPS_M3)
8253 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8254 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8255 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8256 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8257 raw_m3_attrs = attrs
8258 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8259 send_wsc_msg(hapd, addr, m3)
8260
8261 logger.debug("Receive M4 from AP")
8262 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8263
8264 logger.debug("Send M5 to AP")
8265 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8266 attrs += build_attr_msg_type(WPS_M5)
8267 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8268 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8269 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8270 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8271 raw_m5_attrs = attrs
8272 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8273 send_wsc_msg(hapd, addr, m5)
8274
8275 logger.debug("Receive M6 from AP")
8276 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8277
8278 logger.debug("Send M7 to AP")
8279 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8280 attrs += build_attr_msg_type(WPS_M7)
8281 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8282 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8283 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8284 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8285 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8286 raw_m7_attrs = attrs
8287 send_wsc_msg(hapd, addr, m7)
8288
8289 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8290
8291 @remote_compatible
8292 def test_wps_ext_m1_pubkey_oom(dev, apdev):
8293 """WPS proto: M1 PubKey OOM"""
8294 pin = "12345670"
8295 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8296 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8297 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8298
8299 logger.debug("Receive WSC/Start from AP")
8300 msg = get_wsc_msg(hapd)
8301 if msg['wsc_opcode'] != WSC_Start:
8302 raise Exception("Unexpected Op-Code for WSC/Start")
8303
8304 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8305 uuid_e = 16*'\x11'
8306 e_nonce = 16*'\x22'
8307 own_private, e_pk = wsc_dh_init()
8308
8309 logger.debug("Send M1 to AP")
8310 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8311 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8312 e_nonce, e_pk)
8313 send_wsc_msg(hapd, addr, m1)
8314 wps_wait_eap_failure(hapd, dev[0])
8315
8316 def wps_wait_eap_failure(hapd, dev):
8317 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8318 if ev is None:
8319 raise Exception("EAP-Failure not reported")
8320 dev.wait_disconnected()
8321
8322 @remote_compatible
8323 def test_wps_ext_m3_m1(dev, apdev):
8324 """WPS proto: M3 replaced with M1"""
8325 pin = "12345670"
8326 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8327 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8328 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8329
8330 logger.debug("Receive WSC/Start from AP")
8331 msg = get_wsc_msg(hapd)
8332 if msg['wsc_opcode'] != WSC_Start:
8333 raise Exception("Unexpected Op-Code for WSC/Start")
8334
8335 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8336 uuid_e = 16*b'\x11'
8337 e_nonce = 16*b'\x22'
8338 own_private, e_pk = wsc_dh_init()
8339
8340 logger.debug("Send M1 to AP")
8341 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8342 e_nonce, e_pk)
8343 send_wsc_msg(hapd, addr, m1)
8344
8345 logger.debug("Receive M2 from AP")
8346 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8347 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8348 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8349
8350 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8351 r_nonce)
8352 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8353
8354 logger.debug("Send M3(M1) to AP")
8355 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8356 attrs += build_attr_msg_type(WPS_M1)
8357 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8358 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8359 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8360 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8361 raw_m3_attrs = attrs
8362 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8363 send_wsc_msg(hapd, addr, m3)
8364
8365 wps_wait_eap_failure(hapd, dev[0])
8366
8367 @remote_compatible
8368 def test_wps_ext_m5_m3(dev, apdev):
8369 """WPS proto: M5 replaced with M3"""
8370 pin = "12345670"
8371 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8372 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8373 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8374
8375 logger.debug("Receive WSC/Start from AP")
8376 msg = get_wsc_msg(hapd)
8377 if msg['wsc_opcode'] != WSC_Start:
8378 raise Exception("Unexpected Op-Code for WSC/Start")
8379
8380 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8381 uuid_e = 16*b'\x11'
8382 e_nonce = 16*b'\x22'
8383 own_private, e_pk = wsc_dh_init()
8384
8385 logger.debug("Send M1 to AP")
8386 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8387 e_nonce, e_pk)
8388 send_wsc_msg(hapd, addr, m1)
8389
8390 logger.debug("Receive M2 from AP")
8391 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8392 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8393 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8394
8395 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8396 r_nonce)
8397 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8398
8399 logger.debug("Send M3 to AP")
8400 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8401 attrs += build_attr_msg_type(WPS_M3)
8402 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8403 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8404 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8405 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8406 raw_m3_attrs = attrs
8407 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8408 send_wsc_msg(hapd, addr, m3)
8409
8410 logger.debug("Receive M4 from AP")
8411 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8412
8413 logger.debug("Send M5(M3) to AP")
8414 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8415 attrs += build_attr_msg_type(WPS_M3)
8416 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8417 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8418 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8419 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8420 raw_m5_attrs = attrs
8421 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8422 send_wsc_msg(hapd, addr, m5)
8423
8424 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8425
8426 @remote_compatible
8427 def test_wps_ext_m3_m2(dev, apdev):
8428 """WPS proto: M3 replaced with M2"""
8429 pin = "12345670"
8430 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8431 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8432 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8433
8434 logger.debug("Receive WSC/Start from AP")
8435 msg = get_wsc_msg(hapd)
8436 if msg['wsc_opcode'] != WSC_Start:
8437 raise Exception("Unexpected Op-Code for WSC/Start")
8438
8439 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8440 uuid_e = 16*b'\x11'
8441 e_nonce = 16*b'\x22'
8442 own_private, e_pk = wsc_dh_init()
8443
8444 logger.debug("Send M1 to AP")
8445 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8446 e_nonce, e_pk)
8447 send_wsc_msg(hapd, addr, m1)
8448
8449 logger.debug("Receive M2 from AP")
8450 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8451 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8452 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8453
8454 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8455 r_nonce)
8456 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8457
8458 logger.debug("Send M3(M2) to AP")
8459 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8460 attrs += build_attr_msg_type(WPS_M2)
8461 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8462 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8463 raw_m3_attrs = attrs
8464 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8465 send_wsc_msg(hapd, addr, m3)
8466
8467 wps_wait_eap_failure(hapd, dev[0])
8468
8469 @remote_compatible
8470 def test_wps_ext_m3_m5(dev, apdev):
8471 """WPS proto: M3 replaced with M5"""
8472 pin = "12345670"
8473 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8474 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8475 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8476
8477 logger.debug("Receive WSC/Start from AP")
8478 msg = get_wsc_msg(hapd)
8479 if msg['wsc_opcode'] != WSC_Start:
8480 raise Exception("Unexpected Op-Code for WSC/Start")
8481
8482 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8483 uuid_e = 16*b'\x11'
8484 e_nonce = 16*b'\x22'
8485 own_private, e_pk = wsc_dh_init()
8486
8487 logger.debug("Send M1 to AP")
8488 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8489 e_nonce, e_pk)
8490 send_wsc_msg(hapd, addr, m1)
8491
8492 logger.debug("Receive M2 from AP")
8493 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8494 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8495 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8496
8497 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8498 r_nonce)
8499 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8500
8501 logger.debug("Send M3(M5) to AP")
8502 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8503 attrs += build_attr_msg_type(WPS_M5)
8504 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8505 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8506 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8507 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8508 raw_m3_attrs = attrs
8509 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8510 send_wsc_msg(hapd, addr, m3)
8511
8512 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8513
8514 @remote_compatible
8515 def test_wps_ext_m3_m7(dev, apdev):
8516 """WPS proto: M3 replaced with M7"""
8517 pin = "12345670"
8518 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8519 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8520 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8521
8522 logger.debug("Receive WSC/Start from AP")
8523 msg = get_wsc_msg(hapd)
8524 if msg['wsc_opcode'] != WSC_Start:
8525 raise Exception("Unexpected Op-Code for WSC/Start")
8526
8527 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8528 uuid_e = 16*b'\x11'
8529 e_nonce = 16*b'\x22'
8530 own_private, e_pk = wsc_dh_init()
8531
8532 logger.debug("Send M1 to AP")
8533 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8534 e_nonce, e_pk)
8535 send_wsc_msg(hapd, addr, m1)
8536
8537 logger.debug("Receive M2 from AP")
8538 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8539 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8540 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8541
8542 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8543 r_nonce)
8544 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8545
8546 logger.debug("Send M3(M7) to AP")
8547 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8548 attrs += build_attr_msg_type(WPS_M7)
8549 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8550 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8551 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8552 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8553 raw_m3_attrs = attrs
8554 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8555 send_wsc_msg(hapd, addr, m3)
8556
8557 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8558
8559 @remote_compatible
8560 def test_wps_ext_m3_done(dev, apdev):
8561 """WPS proto: M3 replaced with WSC_Done"""
8562 pin = "12345670"
8563 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8564 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8565 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8566
8567 logger.debug("Receive WSC/Start from AP")
8568 msg = get_wsc_msg(hapd)
8569 if msg['wsc_opcode'] != WSC_Start:
8570 raise Exception("Unexpected Op-Code for WSC/Start")
8571
8572 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8573 uuid_e = 16*b'\x11'
8574 e_nonce = 16*b'\x22'
8575 own_private, e_pk = wsc_dh_init()
8576
8577 logger.debug("Send M1 to AP")
8578 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8579 e_nonce, e_pk)
8580 send_wsc_msg(hapd, addr, m1)
8581
8582 logger.debug("Receive M2 from AP")
8583 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8584 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8585 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8586
8587 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8588 r_nonce)
8589 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8590
8591 logger.debug("Send M3(WSC_Done) to AP")
8592 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8593 attrs += build_attr_msg_type(WPS_WSC_DONE)
8594 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8595 raw_m3_attrs = attrs
8596 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8597 send_wsc_msg(hapd, addr, m3)
8598
8599 wps_wait_eap_failure(hapd, dev[0])
8600
8601 @remote_compatible
8602 def test_wps_ext_m2_nack_invalid(dev, apdev):
8603 """WPS proto: M2 followed by invalid NACK"""
8604 pin = "12345670"
8605 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8606 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8607 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8608
8609 logger.debug("Receive WSC/Start from AP")
8610 msg = get_wsc_msg(hapd)
8611 if msg['wsc_opcode'] != WSC_Start:
8612 raise Exception("Unexpected Op-Code for WSC/Start")
8613
8614 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8615 uuid_e = 16*b'\x11'
8616 e_nonce = 16*b'\x22'
8617 own_private, e_pk = wsc_dh_init()
8618
8619 logger.debug("Send M1 to AP")
8620 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8621 e_nonce, e_pk)
8622 send_wsc_msg(hapd, addr, m1)
8623
8624 logger.debug("Receive M2 from AP")
8625 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8626 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8627 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8628
8629 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8630 r_nonce)
8631 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8632
8633 logger.debug("Send WSC_NACK to AP")
8634 attrs = b'\x10\x00\x00'
8635 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8636 send_wsc_msg(hapd, addr, nack)
8637
8638 wps_wait_eap_failure(hapd, dev[0])
8639
8640 @remote_compatible
8641 def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8642 """WPS proto: M2 followed by NACK without Msg Type"""
8643 pin = "12345670"
8644 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8645 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8646 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8647
8648 logger.debug("Receive WSC/Start from AP")
8649 msg = get_wsc_msg(hapd)
8650 if msg['wsc_opcode'] != WSC_Start:
8651 raise Exception("Unexpected Op-Code for WSC/Start")
8652
8653 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8654 uuid_e = 16*b'\x11'
8655 e_nonce = 16*b'\x22'
8656 own_private, e_pk = wsc_dh_init()
8657
8658 logger.debug("Send M1 to AP")
8659 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8660 e_nonce, e_pk)
8661 send_wsc_msg(hapd, addr, m1)
8662
8663 logger.debug("Receive M2 from AP")
8664 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8665 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8666 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8667
8668 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8669 r_nonce)
8670 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8671
8672 logger.debug("Send WSC_NACK to AP")
8673 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8674 msg_type=None, eap_code=2)
8675 send_wsc_msg(hapd, addr, nack)
8676
8677 wps_wait_eap_failure(hapd, dev[0])
8678
8679 @remote_compatible
8680 def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8681 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8682 pin = "12345670"
8683 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8684 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8685 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8686
8687 logger.debug("Receive WSC/Start from AP")
8688 msg = get_wsc_msg(hapd)
8689 if msg['wsc_opcode'] != WSC_Start:
8690 raise Exception("Unexpected Op-Code for WSC/Start")
8691
8692 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8693 uuid_e = 16*b'\x11'
8694 e_nonce = 16*b'\x22'
8695 own_private, e_pk = wsc_dh_init()
8696
8697 logger.debug("Send M1 to AP")
8698 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8699 e_nonce, e_pk)
8700 send_wsc_msg(hapd, addr, m1)
8701
8702 logger.debug("Receive M2 from AP")
8703 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8704 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8705 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8706
8707 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8708 r_nonce)
8709 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8710
8711 logger.debug("Send WSC_NACK to AP")
8712 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8713 msg_type=WPS_WSC_ACK, eap_code=2)
8714 send_wsc_msg(hapd, addr, nack)
8715
8716 wps_wait_eap_failure(hapd, dev[0])
8717
8718 @remote_compatible
8719 def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8720 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8721 pin = "12345670"
8722 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8723 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8724 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8725
8726 logger.debug("Receive WSC/Start from AP")
8727 msg = get_wsc_msg(hapd)
8728 if msg['wsc_opcode'] != WSC_Start:
8729 raise Exception("Unexpected Op-Code for WSC/Start")
8730
8731 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8732 uuid_e = 16*b'\x11'
8733 e_nonce = 16*b'\x22'
8734 own_private, e_pk = wsc_dh_init()
8735
8736 logger.debug("Send M1 to AP")
8737 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8738 e_nonce, e_pk)
8739 send_wsc_msg(hapd, addr, m1)
8740
8741 logger.debug("Receive M2 from AP")
8742 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8743 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8744 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8745
8746 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8747 r_nonce)
8748 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8749
8750 logger.debug("Send WSC_NACK to AP")
8751 nack,attrs = build_nack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8752 eap_code=2)
8753 send_wsc_msg(hapd, addr, nack)
8754
8755 wps_wait_eap_failure(hapd, dev[0])
8756
8757 @remote_compatible
8758 def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8759 """WPS proto: M2 followed by NACK without Config Error"""
8760 pin = "12345670"
8761 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8762 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8763 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8764
8765 logger.debug("Receive WSC/Start from AP")
8766 msg = get_wsc_msg(hapd)
8767 if msg['wsc_opcode'] != WSC_Start:
8768 raise Exception("Unexpected Op-Code for WSC/Start")
8769
8770 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8771 uuid_e = 16*b'\x11'
8772 e_nonce = 16*b'\x22'
8773 own_private, e_pk = wsc_dh_init()
8774
8775 logger.debug("Send M1 to AP")
8776 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8777 e_nonce, e_pk)
8778 send_wsc_msg(hapd, addr, m1)
8779
8780 logger.debug("Receive M2 from AP")
8781 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8782 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8783 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8784
8785 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8786 r_nonce)
8787 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8788
8789 logger.debug("Send WSC_NACK to AP")
8790 nack,attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8791 config_error=None, eap_code=2)
8792 send_wsc_msg(hapd, addr, nack)
8793
8794 wps_wait_eap_failure(hapd, dev[0])
8795
8796 @remote_compatible
8797 def test_wps_ext_m2_ack_invalid(dev, apdev):
8798 """WPS proto: M2 followed by invalid ACK"""
8799 pin = "12345670"
8800 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8801 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8802 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8803
8804 logger.debug("Receive WSC/Start from AP")
8805 msg = get_wsc_msg(hapd)
8806 if msg['wsc_opcode'] != WSC_Start:
8807 raise Exception("Unexpected Op-Code for WSC/Start")
8808
8809 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8810 uuid_e = 16*b'\x11'
8811 e_nonce = 16*b'\x22'
8812 own_private, e_pk = wsc_dh_init()
8813
8814 logger.debug("Send M1 to AP")
8815 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8816 e_nonce, e_pk)
8817 send_wsc_msg(hapd, addr, m1)
8818
8819 logger.debug("Receive M2 from AP")
8820 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8821 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8822 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8823
8824 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8825 r_nonce)
8826 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8827
8828 logger.debug("Send WSC_ACK to AP")
8829 attrs = b'\x10\x00\x00'
8830 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8831 send_wsc_msg(hapd, addr, ack)
8832
8833 wps_wait_eap_failure(hapd, dev[0])
8834
8835 @remote_compatible
8836 def test_wps_ext_m2_ack(dev, apdev):
8837 """WPS proto: M2 followed by ACK"""
8838 pin = "12345670"
8839 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8840 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8841 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8842
8843 logger.debug("Receive WSC/Start from AP")
8844 msg = get_wsc_msg(hapd)
8845 if msg['wsc_opcode'] != WSC_Start:
8846 raise Exception("Unexpected Op-Code for WSC/Start")
8847
8848 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8849 uuid_e = 16*b'\x11'
8850 e_nonce = 16*b'\x22'
8851 own_private, e_pk = wsc_dh_init()
8852
8853 logger.debug("Send M1 to AP")
8854 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8855 e_nonce, e_pk)
8856 send_wsc_msg(hapd, addr, m1)
8857
8858 logger.debug("Receive M2 from AP")
8859 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8860 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8861 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8862
8863 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8864 r_nonce)
8865 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8866
8867 logger.debug("Send WSC_ACK to AP")
8868 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8869 send_wsc_msg(hapd, addr, ack)
8870
8871 wps_wait_eap_failure(hapd, dev[0])
8872
8873 @remote_compatible
8874 def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8875 """WPS proto: M2 followed by ACK missing Msg Type"""
8876 pin = "12345670"
8877 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8878 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8879 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8880
8881 logger.debug("Receive WSC/Start from AP")
8882 msg = get_wsc_msg(hapd)
8883 if msg['wsc_opcode'] != WSC_Start:
8884 raise Exception("Unexpected Op-Code for WSC/Start")
8885
8886 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8887 uuid_e = 16*b'\x11'
8888 e_nonce = 16*b'\x22'
8889 own_private, e_pk = wsc_dh_init()
8890
8891 logger.debug("Send M1 to AP")
8892 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8893 e_nonce, e_pk)
8894 send_wsc_msg(hapd, addr, m1)
8895
8896 logger.debug("Receive M2 from AP")
8897 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8898 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8899 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8900
8901 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8902 r_nonce)
8903 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8904
8905 logger.debug("Send WSC_ACK to AP")
8906 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8907 msg_type=None, eap_code=2)
8908 send_wsc_msg(hapd, addr, ack)
8909
8910 wps_wait_eap_failure(hapd, dev[0])
8911
8912 @remote_compatible
8913 def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8914 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8915 pin = "12345670"
8916 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8917 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8918 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8919
8920 logger.debug("Receive WSC/Start from AP")
8921 msg = get_wsc_msg(hapd)
8922 if msg['wsc_opcode'] != WSC_Start:
8923 raise Exception("Unexpected Op-Code for WSC/Start")
8924
8925 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8926 uuid_e = 16*b'\x11'
8927 e_nonce = 16*b'\x22'
8928 own_private, e_pk = wsc_dh_init()
8929
8930 logger.debug("Send M1 to AP")
8931 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8932 e_nonce, e_pk)
8933 send_wsc_msg(hapd, addr, m1)
8934
8935 logger.debug("Receive M2 from AP")
8936 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8937 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8938 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8939
8940 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8941 r_nonce)
8942 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8943
8944 logger.debug("Send WSC_ACK to AP")
8945 ack,attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8946 msg_type=WPS_WSC_NACK, eap_code=2)
8947 send_wsc_msg(hapd, addr, ack)
8948
8949 wps_wait_eap_failure(hapd, dev[0])
8950
8951 @remote_compatible
8952 def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8953 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
8954 pin = "12345670"
8955 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8956 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8957 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8958
8959 logger.debug("Receive WSC/Start from AP")
8960 msg = get_wsc_msg(hapd)
8961 if msg['wsc_opcode'] != WSC_Start:
8962 raise Exception("Unexpected Op-Code for WSC/Start")
8963
8964 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8965 uuid_e = 16*b'\x11'
8966 e_nonce = 16*b'\x22'
8967 own_private, e_pk = wsc_dh_init()
8968
8969 logger.debug("Send M1 to AP")
8970 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8971 e_nonce, e_pk)
8972 send_wsc_msg(hapd, addr, m1)
8973
8974 logger.debug("Receive M2 from AP")
8975 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8976 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8977 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8978
8979 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8980 r_nonce)
8981 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8982
8983 logger.debug("Send WSC_ACK to AP")
8984 ack,attrs = build_ack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8985 eap_code=2)
8986 send_wsc_msg(hapd, addr, ack)
8987
8988 wps_wait_eap_failure(hapd, dev[0])
8989
8990 @remote_compatible
8991 def test_wps_ext_m1_invalid(dev, apdev):
8992 """WPS proto: M1 failing parsing"""
8993 pin = "12345670"
8994 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8995 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8996 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8997
8998 logger.debug("Receive WSC/Start from AP")
8999 msg = get_wsc_msg(hapd)
9000 if msg['wsc_opcode'] != WSC_Start:
9001 raise Exception("Unexpected Op-Code for WSC/Start")
9002
9003 logger.debug("Send M1 to AP")
9004 attrs = b'\x10\x00\x00'
9005 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9006 send_wsc_msg(hapd, addr, m1)
9007
9008 wps_wait_eap_failure(hapd, dev[0])
9009
9010 def test_wps_ext_m1_missing_msg_type(dev, apdev):
9011 """WPS proto: M1 missing Msg Type"""
9012 pin = "12345670"
9013 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9014 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9015 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9016
9017 logger.debug("Receive WSC/Start from AP")
9018 msg = get_wsc_msg(hapd)
9019 if msg['wsc_opcode'] != WSC_Start:
9020 raise Exception("Unexpected Op-Code for WSC/Start")
9021
9022 logger.debug("Send M1 to AP")
9023 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9024 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9025 send_wsc_msg(hapd, addr, m1)
9026
9027 wps_wait_ap_nack(hapd, dev[0], 16*b'\x00', 16*b'\x00')
9028
9029 def wps_ext_wsc_done(dev, apdev):
9030 pin = "12345670"
9031 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9032 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9033 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9034
9035 logger.debug("Receive WSC/Start from AP")
9036 msg = get_wsc_msg(hapd)
9037 if msg['wsc_opcode'] != WSC_Start:
9038 raise Exception("Unexpected Op-Code for WSC/Start")
9039
9040 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9041 uuid_e = 16*b'\x11'
9042 e_nonce = 16*b'\x22'
9043 own_private, e_pk = wsc_dh_init()
9044
9045 logger.debug("Send M1 to AP")
9046 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9047 e_nonce, e_pk)
9048 send_wsc_msg(hapd, addr, m1)
9049
9050 logger.debug("Receive M2 from AP")
9051 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9052 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9053 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9054
9055 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9056 r_nonce)
9057 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9058
9059 logger.debug("Send M3 to AP")
9060 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9061 attrs += build_attr_msg_type(WPS_M3)
9062 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9063 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9064 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9065 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9066 raw_m3_attrs = attrs
9067 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9068 send_wsc_msg(hapd, addr, m3)
9069
9070 logger.debug("Receive M4 from AP")
9071 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9072
9073 logger.debug("Send M5 to AP")
9074 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9075 attrs += build_attr_msg_type(WPS_M5)
9076 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9077 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9078 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9079 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9080 raw_m5_attrs = attrs
9081 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9082 send_wsc_msg(hapd, addr, m5)
9083
9084 logger.debug("Receive M6 from AP")
9085 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9086
9087 logger.debug("Send M7 to AP")
9088 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9089 attrs += build_attr_msg_type(WPS_M7)
9090 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9091 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9092 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9093 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9094 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9095 raw_m7_attrs = attrs
9096 send_wsc_msg(hapd, addr, m7)
9097
9098 logger.debug("Receive M8 from AP")
9099 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9100 return hapd, msg, e_nonce, r_nonce
9101
9102 @remote_compatible
9103 def test_wps_ext_wsc_done_invalid(dev, apdev):
9104 """WPS proto: invalid WSC_Done"""
9105 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9106
9107 logger.debug("Send WSC_Done to AP")
9108 attrs = b'\x10\x00\x00'
9109 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9110 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9111
9112 wps_wait_eap_failure(hapd, dev[0])
9113
9114 @remote_compatible
9115 def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9116 """WPS proto: invalid WSC_Done"""
9117 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9118
9119 logger.debug("Send WSC_Done to AP")
9120 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9121 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9122 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9123 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9124 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9125 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9126
9127 wps_wait_eap_failure(hapd, dev[0])
9128
9129 @remote_compatible
9130 def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9131 """WPS proto: WSC_Done with wrong Msg Type"""
9132 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9133
9134 logger.debug("Send WSC_Done to AP")
9135 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9136 attrs += build_attr_msg_type(WPS_WSC_ACK)
9137 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9138 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9139 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9140 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9141
9142 wps_wait_eap_failure(hapd, dev[0])
9143
9144 @remote_compatible
9145 def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9146 """WPS proto: WSC_Done without e_nonce"""
9147 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9148
9149 logger.debug("Send WSC_Done to AP")
9150 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9151 attrs += build_attr_msg_type(WPS_WSC_DONE)
9152 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9153 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9154 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9155 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9156
9157 wps_wait_eap_failure(hapd, dev[0])
9158
9159 def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9160 """WPS proto: WSC_Done without r_nonce"""
9161 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9162
9163 logger.debug("Send WSC_Done to AP")
9164 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9165 attrs += build_attr_msg_type(WPS_WSC_DONE)
9166 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9167 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9168 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9169 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9170
9171 wps_wait_eap_failure(hapd, dev[0])
9172
9173 @remote_compatible
9174 def test_wps_ext_m7_no_encr_settings(dev, apdev):
9175 """WPS proto: M7 without Encr Settings"""
9176 pin = "12345670"
9177 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9178 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9179 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9180
9181 logger.debug("Receive WSC/Start from AP")
9182 msg = get_wsc_msg(hapd)
9183 if msg['wsc_opcode'] != WSC_Start:
9184 raise Exception("Unexpected Op-Code for WSC/Start")
9185
9186 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9187 uuid_e = 16*b'\x11'
9188 e_nonce = 16*b'\x22'
9189 own_private, e_pk = wsc_dh_init()
9190
9191 logger.debug("Send M1 to AP")
9192 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9193 e_nonce, e_pk)
9194 send_wsc_msg(hapd, addr, m1)
9195
9196 logger.debug("Receive M2 from AP")
9197 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9198 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9199 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9200
9201 authkey,keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9202 r_nonce)
9203 e_s1,e_s2,e_hash1,e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9204
9205 logger.debug("Send M3 to AP")
9206 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9207 attrs += build_attr_msg_type(WPS_M3)
9208 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9209 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9210 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9211 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9212 raw_m3_attrs = attrs
9213 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9214 send_wsc_msg(hapd, addr, m3)
9215
9216 logger.debug("Receive M4 from AP")
9217 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9218
9219 logger.debug("Send M5 to AP")
9220 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9221 attrs += build_attr_msg_type(WPS_M5)
9222 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9223 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9224 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9225 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9226 raw_m5_attrs = attrs
9227 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9228 send_wsc_msg(hapd, addr, m5)
9229
9230 logger.debug("Receive M6 from AP")
9231 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9232
9233 logger.debug("Send M7 to AP")
9234 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9235 attrs += build_attr_msg_type(WPS_M7)
9236 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9237 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9238 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9239 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9240 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9241 raw_m7_attrs = attrs
9242 send_wsc_msg(hapd, addr, m7)
9243
9244 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9245
9246 @remote_compatible
9247 def test_wps_ext_m1_workaround(dev, apdev):
9248 """WPS proto: M1 Manufacturer/Model workaround"""
9249 pin = "12345670"
9250 addr,bssid,hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9251 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9252 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9253
9254 logger.debug("Receive WSC/Start from AP")
9255 msg = get_wsc_msg(hapd)
9256 if msg['wsc_opcode'] != WSC_Start:
9257 raise Exception("Unexpected Op-Code for WSC/Start")
9258
9259 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9260 uuid_e = 16*b'\x11'
9261 e_nonce = 16*b'\x22'
9262 own_private, e_pk = wsc_dh_init()
9263
9264 logger.debug("Send M1 to AP")
9265 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9266 e_nonce, e_pk, manufacturer='Apple TEST',
9267 model_name='AirPort', config_methods=b'\xff\xff')
9268 send_wsc_msg(hapd, addr, m1)
9269
9270 logger.debug("Receive M2 from AP")
9271 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9272
9273 @remote_compatible
9274 def test_ap_wps_disable_enable(dev, apdev):
9275 """WPS and DISABLE/ENABLE AP"""
9276 hapd = wps_start_ap(apdev[0])
9277 hapd.disable()
9278 hapd.enable()
9279 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9280
9281 def test_ap_wps_upnp_web_oom(dev, apdev, params):
9282 """hostapd WPS UPnP web OOM"""
9283 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9284 hapd = add_ssdp_ap(apdev[0], ap_uuid)
9285
9286 location = ssdp_get_location(ap_uuid)
9287 url = urlparse(location)
9288 urls = upnp_get_urls(location)
9289 eventurl = urlparse(urls['event_sub_url'])
9290 ctrlurl = urlparse(urls['control_url'])
9291
9292 conn = HTTPConnection(url.netloc)
9293 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9294 conn.request("GET", "/wps_device.xml")
9295 try:
9296 resp = conn.getresponse()
9297 except:
9298 pass
9299
9300 conn = HTTPConnection(url.netloc)
9301 conn.request("GET", "/unknown")
9302 resp = conn.getresponse()
9303 if resp.status != 404:
9304 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9305
9306 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9307 conn.request("GET", "/unknown")
9308 try:
9309 resp = conn.getresponse()
9310 print(resp.status)
9311 except:
9312 pass
9313
9314 conn = HTTPConnection(url.netloc)
9315 conn.request("GET", "/wps_device.xml")
9316 resp = conn.getresponse()
9317 if resp.status != 200:
9318 raise Exception("GET /wps_device.xml failed")
9319
9320 conn = HTTPConnection(url.netloc)
9321 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9322 if resp.status != 200:
9323 raise Exception("GetDeviceInfo failed")
9324
9325 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9326 conn = HTTPConnection(url.netloc)
9327 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9328 if resp.status != 500:
9329 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9330
9331 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9332 conn = HTTPConnection(url.netloc)
9333 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9334 if resp.status != 500:
9335 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9336
9337 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9338 conn = HTTPConnection(url.netloc)
9339 try:
9340 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9341 except:
9342 pass
9343
9344 conn = HTTPConnection(url.netloc)
9345 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9346 if resp.status != 200:
9347 raise Exception("GetDeviceInfo failed")
9348
9349 # No NewWLANEventType in PutWLANResponse NewMessage
9350 conn = HTTPConnection(url.netloc)
9351 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9352 if resp.status != 600:
9353 raise Exception("Unexpected HTTP response: %d" % resp.status)
9354
9355 # No NewWLANEventMAC in PutWLANResponse NewMessage
9356 conn = HTTPConnection(url.netloc)
9357 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9358 newmsg="foo", neweventtype="1")
9359 if resp.status != 600:
9360 raise Exception("Unexpected HTTP response: %d" % resp.status)
9361
9362 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9363 conn = HTTPConnection(url.netloc)
9364 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9365 newmsg="foo", neweventtype="1",
9366 neweventmac="foo")
9367 if resp.status != 600:
9368 raise Exception("Unexpected HTTP response: %d" % resp.status)
9369
9370 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9371 # Ignored unexpected PutWLANResponse WLANEventType 1
9372 conn = HTTPConnection(url.netloc)
9373 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9374 newmsg="foo", neweventtype="1",
9375 neweventmac="00.11.22.33.44.55")
9376 if resp.status != 500:
9377 raise Exception("Unexpected HTTP response: %d" % resp.status)
9378
9379 # PutWLANResponse NewMessage with invalid EAP message
9380 conn = HTTPConnection(url.netloc)
9381 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9382 newmsg="foo", neweventtype="2",
9383 neweventmac="00:11:22:33:44:55")
9384 if resp.status != 200:
9385 raise Exception("Unexpected HTTP response: %d" % resp.status)
9386
9387 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9388 conn = HTTPConnection(url.netloc)
9389 headers = { "callback": '<http://127.0.0.1:12345/event>',
9390 "NT": "upnp:event",
9391 "timeout": "Second-1234" }
9392 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9393 try:
9394 resp = conn.getresponse()
9395 except:
9396 pass
9397
9398 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9399 conn = HTTPConnection(url.netloc)
9400 headers = { "callback": '<http://127.0.0.1:12345/event>',
9401 "NT": "upnp:event",
9402 "timeout": "Second-1234" }
9403 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9404 resp = conn.getresponse()
9405 if resp.status != 500:
9406 raise Exception("Unexpected HTTP response: %d" % resp.status)
9407
9408 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9409 conn = HTTPConnection(url.netloc)
9410 headers = { "callback": '<http://127.0.0.1:12345/event>',
9411 "NT": "upnp:event",
9412 "timeout": "Second-1234" }
9413 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9414 try:
9415 resp = conn.getresponse()
9416 except:
9417 pass
9418
9419 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9420 conn = HTTPConnection(url.netloc)
9421 conn.request("HEAD", "/wps_device.xml")
9422 try:
9423 resp = conn.getresponse()
9424 except:
9425 pass
9426
9427 def test_ap_wps_frag_ack_oom(dev, apdev):
9428 """WPS and fragment ack OOM"""
9429 dev[0].request("SET wps_fragment_size 50")
9430 hapd = wps_start_ap(apdev[0])
9431 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9432 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
9433
9434 def wait_scan_stopped(dev):
9435 dev.request("ABORT_SCAN")
9436 for i in range(50):
9437 res = dev.get_driver_status_field("scan_state")
9438 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9439 break
9440 logger.debug("Waiting for scan to complete")
9441 time.sleep(0.1)
9442
9443 @remote_compatible
9444 def test_ap_wps_eap_wsc_errors(dev, apdev):
9445 """WPS and EAP-WSC error cases"""
9446 ssid = "test-wps-conf-pin"
9447 appin = "12345670"
9448 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9449 "wpa_passphrase": "12345678", "wpa": "2",
9450 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9451 "fragment_size": "300", "ap_pin": appin }
9452 hapd = hostapd.add_ap(apdev[0], params)
9453 bssid = apdev[0]['bssid']
9454
9455 pin = dev[0].wps_read_pin()
9456 hapd.request("WPS_PIN any " + pin)
9457 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9458 dev[0].dump_monitor()
9459
9460 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9461 "new passphrase", no_wait=True)
9462 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9463 if ev is None:
9464 raise Exception("WPS-FAIL not reported")
9465 dev[0].request("WPS_CANCEL")
9466 dev[0].wait_disconnected()
9467 wait_scan_stopped(dev[0])
9468 dev[0].dump_monitor()
9469
9470 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9471 "new passphrase", no_wait=True)
9472 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9473 if ev is None:
9474 raise Exception("WPS-FAIL not reported")
9475 dev[0].request("WPS_CANCEL")
9476 dev[0].wait_disconnected()
9477 wait_scan_stopped(dev[0])
9478 dev[0].dump_monitor()
9479
9480 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9481 "new passphrase", no_wait=True)
9482 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9483 if ev is None:
9484 raise Exception("WPS-FAIL not reported")
9485 dev[0].request("WPS_CANCEL")
9486 dev[0].wait_disconnected()
9487 wait_scan_stopped(dev[0])
9488 dev[0].dump_monitor()
9489
9490 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9491 "new passphrase", no_wait=True)
9492 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9493 if ev is None:
9494 raise Exception("WPS-FAIL not reported")
9495 dev[0].request("WPS_CANCEL")
9496 dev[0].wait_disconnected()
9497 wait_scan_stopped(dev[0])
9498 dev[0].dump_monitor()
9499
9500 tests = [ "eap_wsc_init",
9501 "eap_msg_alloc;eap_wsc_build_msg",
9502 "wpabuf_alloc;eap_wsc_process_fragment" ]
9503 for func in tests:
9504 with alloc_fail(dev[0], 1, func):
9505 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9506 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9507 dev[0].request("WPS_CANCEL")
9508 dev[0].wait_disconnected()
9509 wait_scan_stopped(dev[0])
9510 dev[0].dump_monitor()
9511
9512 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9513 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9514 "CCMP", "new passphrase", no_wait=True)
9515 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9516 dev[0].request("WPS_CANCEL")
9517 dev[0].wait_disconnected()
9518 wait_scan_stopped(dev[0])
9519 dev[0].dump_monitor()
9520
9521 def test_ap_wps_eap_wsc(dev, apdev):
9522 """WPS and EAP-WSC in network profile"""
9523 params = int_eap_server_params()
9524 params["wps_state"] = "2"
9525 hapd = hostapd.add_ap(apdev[0], params)
9526 bssid = apdev[0]['bssid']
9527
9528 logger.info("Unexpected identity")
9529 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9530 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9531 wait_connect=False)
9532 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9533 if ev is None:
9534 raise Exception("No EAP-Failure seen")
9535 dev[0].request("REMOVE_NETWORK all")
9536 dev[0].wait_disconnected()
9537
9538 logger.info("No phase1 parameter")
9539 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9540 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9541 wait_connect=False)
9542 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9543 if ev is None:
9544 raise Exception("Timeout on EAP method start")
9545 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9546 if ev is None:
9547 raise Exception("No EAP-Failure seen")
9548 dev[0].request("REMOVE_NETWORK all")
9549 dev[0].wait_disconnected()
9550
9551 logger.info("No PIN/PBC in phase1")
9552 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9553 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9554 phase1="foo", wait_connect=False)
9555 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9556 if ev is None:
9557 raise Exception("Timeout on EAP method start")
9558 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9559 if ev is None:
9560 raise Exception("No EAP-Failure seen")
9561 dev[0].request("REMOVE_NETWORK all")
9562 dev[0].wait_disconnected()
9563
9564 logger.info("Invalid pkhash in phase1")
9565 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9566 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9567 phase1="foo pkhash=q pbc=1", wait_connect=False)
9568 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9569 if ev is None:
9570 raise Exception("Timeout on EAP method start")
9571 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9572 if ev is None:
9573 raise Exception("No EAP-Failure seen")
9574 dev[0].request("REMOVE_NETWORK all")
9575 dev[0].wait_disconnected()
9576
9577 logger.info("Zero fragment_size")
9578 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9579 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9580 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9581 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9582 if ev is None:
9583 raise Exception("Timeout on EAP method start")
9584 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9585 if ev is None:
9586 raise Exception("No M2D seen")
9587 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9588 if ev is None:
9589 raise Exception("No EAP-Failure seen")
9590 dev[0].request("REMOVE_NETWORK all")
9591 dev[0].wait_disconnected()
9592
9593 logger.info("Missing new_auth")
9594 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9595 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9596 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9597 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9598 if ev is None:
9599 raise Exception("Timeout on EAP method start")
9600 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9601 if ev is None:
9602 raise Exception("No EAP-Failure seen")
9603 dev[0].request("REMOVE_NETWORK all")
9604 dev[0].wait_disconnected()
9605
9606 logger.info("Missing new_encr")
9607 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9608 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9609 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9610 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9611 if ev is None:
9612 raise Exception("Timeout on EAP method start")
9613 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9614 if ev is None:
9615 raise Exception("No EAP-Failure seen")
9616 dev[0].request("REMOVE_NETWORK all")
9617 dev[0].wait_disconnected()
9618
9619 logger.info("Missing new_key")
9620 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9621 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9622 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9623 wait_connect=False)
9624 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9625 if ev is None:
9626 raise Exception("Timeout on EAP method start")
9627 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9628 if ev is None:
9629 raise Exception("No EAP-Failure seen")
9630 dev[0].request("REMOVE_NETWORK all")
9631 dev[0].wait_disconnected()
9632
9633 def test_ap_wps_and_bss_limit(dev, apdev):
9634 """WPS and wpa_supplicant BSS entry limit"""
9635 try:
9636 _test_ap_wps_and_bss_limit(dev, apdev)
9637 finally:
9638 dev[0].request("SET bss_max_count 200")
9639 pass
9640
9641 def _test_ap_wps_and_bss_limit(dev, apdev):
9642 params = { "ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9643 "wpa_passphrase": "12345678", "wpa": "2",
9644 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
9645 hapd = hostapd.add_ap(apdev[0], params)
9646
9647 params = { "ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9648 "wpa_passphrase": "1234567890", "wpa": "2",
9649 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" }
9650 hapd2 = hostapd.add_ap(apdev[1], params)
9651
9652 id = dev[1].add_network()
9653 dev[1].set_network(id, "mode", "2")
9654 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9655 dev[1].set_network_quoted(id, "psk", "12345678")
9656 dev[1].set_network(id, "frequency", "2462")
9657 dev[1].set_network(id, "scan_freq", "2462")
9658 dev[1].set_network(id, "wps_disabled", "1")
9659 dev[1].select_network(id)
9660
9661 id = dev[2].add_network()
9662 dev[2].set_network(id, "mode", "2")
9663 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9664 dev[2].set_network_quoted(id, "psk", "12345678")
9665 dev[2].set_network(id, "frequency", "2437")
9666 dev[2].set_network(id, "scan_freq", "2437")
9667 dev[2].select_network(id)
9668
9669 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9670 wpas.interface_add("wlan5")
9671 id = wpas.add_network()
9672 wpas.set_network(id, "mode", "2")
9673 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9674 wpas.set_network_quoted(id, "psk", "12345678")
9675 wpas.set_network(id, "frequency", "2437")
9676 wpas.set_network(id, "scan_freq", "2437")
9677 wpas.select_network(id)
9678
9679 dev[1].wait_connected()
9680 dev[2].wait_connected()
9681 wpas.wait_connected()
9682 wpas.request("WPS_PIN any 12345670")
9683
9684 hapd.request("WPS_PBC")
9685 hapd2.request("WPS_PBC")
9686
9687 dev[0].request("SET bss_max_count 1")
9688
9689 id = dev[0].add_network()
9690 dev[0].set_network_quoted(id, "ssid", "testing")
9691
9692 id = dev[0].add_network()
9693 dev[0].set_network_quoted(id, "ssid", "testing")
9694 dev[0].set_network(id, "key_mgmt", "WPS")
9695
9696 dev[0].request("WPS_PBC")
9697 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9698 dev[0].request("WPS_CANCEL")
9699
9700 id = dev[0].add_network()
9701 dev[0].set_network_quoted(id, "ssid", "testing")
9702 dev[0].set_network(id, "key_mgmt", "WPS")
9703
9704 dev[0].scan(freq="2412")
9705
9706 def test_ap_wps_pbc_2ap(dev, apdev):
9707 """WPS PBC with two APs advertising same SSID"""
9708 params = { "ssid": "wps", "eap_server": "1", "wps_state": "2",
9709 "wpa_passphrase": "12345678", "wpa": "2",
9710 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9711 "wps_independent": "1"}
9712 hapd = hostapd.add_ap(apdev[0], params)
9713 params = { "ssid": "wps", "eap_server": "1", "wps_state": "2",
9714 "wpa_passphrase": "123456789", "wpa": "2",
9715 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9716 "wps_independent": "1"}
9717 hapd2 = hostapd.add_ap(apdev[1], params)
9718 hapd.request("WPS_PBC")
9719
9720 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9721 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9722 wpas.dump_monitor()
9723
9724 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9725 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9726 wpas.request("WPS_PBC")
9727 wpas.wait_connected()
9728 wpas.request("DISCONNECT")
9729 hapd.request("DISABLE")
9730 hapd2.request("DISABLE")
9731 wpas.flush_scan_cache()
9732
9733 def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9734 """WPS ER enrolling a new device to a configured AP"""
9735 try:
9736 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9737 finally:
9738 dev[0].request("WPS_ER_STOP")
9739
9740 def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9741 ssid = "wps-er-enrollee-to-conf-ap"
9742 ap_pin = "12345670"
9743 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9744 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9745 "wpa_passphrase": "12345678", "wpa": "2",
9746 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9747 "device_name": "Wireless AP", "manufacturer": "Company",
9748 "model_name": "WAP", "model_number": "123",
9749 "serial_number": "12345", "device_type": "6-0050F204-1",
9750 "os_version": "01020300",
9751 "config_methods": "label push_button",
9752 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9753 hapd = hostapd.add_ap(apdev[0], params)
9754 bssid = hapd.own_addr()
9755
9756 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9757 dev[0].dump_monitor()
9758
9759 dev[0].request("WPS_ER_START ifname=lo")
9760 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9761 if ev is None:
9762 raise Exception("AP discovery timed out")
9763 if ap_uuid not in ev:
9764 raise Exception("Expected AP UUID not found")
9765
9766 pin = dev[2].wps_read_pin()
9767 addr2 = dev[2].own_addr()
9768 dev[0].dump_monitor()
9769 dev[2].scan_for_bss(bssid, freq=2412)
9770 dev[2].dump_monitor()
9771 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9772
9773 for i in range(3):
9774 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9775 if ev is None:
9776 raise Exception("Enrollee not seen")
9777 if addr2 in ev:
9778 break
9779 if addr2 not in ev:
9780 raise Exception("Unexpected Enrollee MAC address")
9781 dev[0].dump_monitor()
9782
9783 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9784 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9785 dev[2].wait_connected(timeout=30)
9786 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9787 if ev is None:
9788 raise Exception("WPS ER did not report success")
9789
9790 def test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9791 """WPS ER enrolling a new device to a configured AP (2)"""
9792 try:
9793 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9794 finally:
9795 dev[0].request("WPS_ER_STOP")
9796
9797 def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9798 ssid = "wps-er-enrollee-to-conf-ap"
9799 ap_pin = "12345670"
9800 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9801 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9802 "wpa_passphrase": "12345678", "wpa": "2",
9803 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9804 "device_name": "Wireless AP", "manufacturer": "Company",
9805 "model_name": "WAP", "model_number": "123",
9806 "serial_number": "12345", "device_type": "6-0050F204-1",
9807 "os_version": "01020300",
9808 "config_methods": "label push_button",
9809 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9810 hapd = hostapd.add_ap(apdev[0], params)
9811 bssid = hapd.own_addr()
9812
9813 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9814 dev[0].dump_monitor()
9815
9816 dev[0].request("WPS_ER_START ifname=lo")
9817 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9818 if ev is None:
9819 raise Exception("AP discovery timed out")
9820 if ap_uuid not in ev:
9821 raise Exception("Expected AP UUID not found")
9822
9823 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
9824 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
9825 if ev is None:
9826 raise Exception("AP learn timed out")
9827 if ap_uuid not in ev:
9828 raise Exception("Expected AP UUID not in settings")
9829 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
9830 if ev is None:
9831 raise Exception("WPS-FAIL after AP learn timed out")
9832 time.sleep(0.1)
9833
9834 pin = dev[1].wps_read_pin()
9835 addr1 = dev[1].own_addr()
9836 dev[0].dump_monitor()
9837 dev[0].request("WPS_ER_PIN any " + pin)
9838 time.sleep(0.1)
9839 dev[1].scan_for_bss(bssid, freq=2412)
9840 dev[1].request("WPS_PIN any %s" % pin)
9841 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
9842 if ev is None:
9843 raise Exception("Enrollee did not report success")
9844 dev[1].wait_connected(timeout=15)
9845 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9846 if ev is None:
9847 raise Exception("WPS ER did not report success")
9848
9849 def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
9850 """WPS AP trying to ignore broadcast SSID"""
9851 ssid = "test-wps"
9852 hapd = hostapd.add_ap(apdev[0],
9853 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9854 "ignore_broadcast_ssid": "1" })
9855 if "FAIL" not in hapd.request("WPS_PBC"):
9856 raise Exception("WPS unexpectedly enabled")
9857
9858 def test_ap_wps_wep(dev, apdev):
9859 """WPS AP trying to enable WEP"""
9860 ssid = "test-wps"
9861 hapd = hostapd.add_ap(apdev[0],
9862 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9863 "ieee80211n": "0", "wep_key0": '"hello"' })
9864 if "FAIL" not in hapd.request("WPS_PBC"):
9865 raise Exception("WPS unexpectedly enabled")
9866
9867 def test_ap_wps_tkip(dev, apdev):
9868 """WPS AP trying to enable TKIP"""
9869 ssid = "test-wps"
9870 hapd = hostapd.add_ap(apdev[0],
9871 { "ssid": ssid, "eap_server": "1", "wps_state": "1",
9872 "ieee80211n": "0", "wpa": '1',
9873 "wpa_key_mgmt": "WPA-PSK",
9874 "wpa_passphrase": "12345678" })
9875 if "FAIL" not in hapd.request("WPS_PBC"):
9876 raise Exception("WPS unexpectedly enabled")
9877
9878 def test_ap_wps_conf_dummy_cred(dev, apdev):
9879 """WPS PIN provisioning with configured AP using dummy cred"""
9880 ssid = "test-wps-conf"
9881 hapd = hostapd.add_ap(apdev[0],
9882 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9883 "wpa_passphrase": "12345678", "wpa": "2",
9884 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9885 hapd.request("WPS_PIN any 12345670")
9886 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9887 dev[0].dump_monitor()
9888 try:
9889 hapd.set("wps_testing_dummy_cred", "1")
9890 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
9891 for i in range(1, 3):
9892 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
9893 if ev is None:
9894 raise Exception("WPS credential %d not received" % i)
9895 dev[0].wait_connected(timeout=30)
9896 finally:
9897 hapd.set("wps_testing_dummy_cred", "0")
9898
9899 def test_ap_wps_rf_bands(dev, apdev):
9900 """WPS and wps_rf_bands configuration"""
9901 ssid = "test-wps-conf"
9902 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9903 "wpa_passphrase": "12345678", "wpa": "2",
9904 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9905 "wps_rf_bands": "ag" }
9906
9907 hapd = hostapd.add_ap(apdev[0], params)
9908 bssid = hapd.own_addr()
9909 hapd.request("WPS_PBC")
9910 dev[0].scan_for_bss(bssid, freq="2412")
9911 dev[0].dump_monitor()
9912 dev[0].request("WPS_PBC " + bssid)
9913 dev[0].wait_connected(timeout=30)
9914 bss = dev[0].get_bss(bssid)
9915 logger.info("BSS: " + str(bss))
9916 if "103c000103" not in bss['ie']:
9917 raise Exception("RF Bands attribute with expected values not found")
9918 dev[0].request("DISCONNECT")
9919 dev[0].wait_disconnected()
9920 hapd.set("wps_rf_bands", "ad")
9921 hapd.set("wps_rf_bands", "a")
9922 hapd.set("wps_rf_bands", "g")
9923 hapd.set("wps_rf_bands", "b")
9924 hapd.set("wps_rf_bands", "ga")
9925 hapd.disable()
9926 dev[0].dump_monitor()
9927 dev[0].flush_scan_cache()
9928
9929 def test_ap_wps_pbc_in_m1(dev, apdev):
9930 """WPS and pbc_in_m1"""
9931 ssid = "test-wps-conf"
9932 params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9933 "wpa_passphrase": "12345678", "wpa": "2",
9934 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9935 "config_methods": "virtual_push_button virtual_display",
9936 "pbc_in_m1": "1" }
9937
9938 hapd = hostapd.add_ap(apdev[0], params)
9939 bssid = hapd.own_addr()
9940 hapd.request("WPS_PBC")
9941 dev[0].scan_for_bss(bssid, freq="2412")
9942 dev[0].dump_monitor()
9943 dev[0].request("WPS_PBC " + bssid)
9944 dev[0].wait_connected(timeout=30)
9945 dev[0].request("DISCONNECT")
9946 dev[0].wait_disconnected()
9947 hapd.disable()
9948 dev[0].dump_monitor()
9949 dev[0].flush_scan_cache()
9950
9951 def test_ap_wps_pin_start_failure(dev, apdev):
9952 """WPS_PIN start failure"""
9953 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
9954 if "FAIL" not in dev[0].request("WPS_PIN any 12345670"):
9955 raise Exception("WPS_PIN not rejected during OOM")
9956 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
9957 if "FAIL" not in dev[0].request("WPS_PIN any"):
9958 raise Exception("WPS_PIN not rejected during OOM")
9959
9960 def test_ap_wps_ap_pin_failure(dev, apdev):
9961 """WPS_AP_PIN failure"""
9962 id = dev[0].add_network()
9963 dev[0].set_network(id, "mode", "2")
9964 dev[0].set_network_quoted(id, "ssid", "wpas-ap-wps")
9965 dev[0].set_network_quoted(id, "psk", "1234567890")
9966 dev[0].set_network(id, "frequency", "2412")
9967 dev[0].set_network(id, "scan_freq", "2412")
9968 dev[0].select_network(id)
9969 dev[0].wait_connected()
9970
9971 with fail_test(dev[0], 1,
9972 "os_get_random;wpa_supplicant_ctrl_iface_wps_ap_pin"):
9973 if "FAIL" not in dev[0].request("WPS_AP_PIN random"):
9974 raise Exception("WPS_AP_PIN random accepted")
9975 with alloc_fail(dev[0], 1, "wpas_wps_ap_pin_set"):
9976 if "FAIL" not in dev[0].request("WPS_AP_PIN set 12345670"):
9977 raise Exception("WPS_AP_PIN set accepted")
9978
9979 dev[0].request("DISCONNECT")
9980 dev[0].wait_disconnected()
9981
9982 def test_ap_wps_random_uuid(dev, apdev, params):
9983 """WPS and random UUID on Enrollee"""
9984 ssid = "test-wps-conf"
9985 hapd = hostapd.add_ap(apdev[0],
9986 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
9987 "wpa_passphrase": "12345678", "wpa": "2",
9988 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9989
9990 config = os.path.join(params['logdir'], 'ap_wps_random_uuid.conf')
9991 with open(config, "w") as f:
9992 f.write("auto_uuid=1\n")
9993
9994 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9995
9996 uuid = []
9997 for i in range(3):
9998 wpas.interface_add("wlan5", config=config)
9999
10000 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
10001 wpas.dump_monitor()
10002 wpas.request("WPS_PBC " + apdev[0]['bssid'])
10003
10004 ev = hapd.wait_event(["WPS-ENROLLEE-SEEN"], timeout=10)
10005 if ev is None:
10006 raise Exception("Enrollee not seen")
10007 uuid.append(ev.split(' ')[2])
10008 wpas.request("WPS_CANCEL")
10009 wpas.dump_monitor()
10010
10011 wpas.interface_remove("wlan5")
10012
10013 hapd.dump_monitor()
10014
10015 logger.info("Seen UUIDs: " + str(uuid))
10016 if uuid[0] == uuid[1] or uuid[0] == uuid[2] or uuid[1] == uuid[2]:
10017 raise Exception("Same UUID used multiple times")
10018
10019 def test_ap_wps_conf_pin_gcmp_128(dev, apdev):
10020 """WPS PIN provisioning with configured AP using GCMP-128"""
10021 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP")
10022
10023 def test_ap_wps_conf_pin_gcmp_256(dev, apdev):
10024 """WPS PIN provisioning with configured AP using GCMP-256"""
10025 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP-256")
10026
10027 def test_ap_wps_conf_pin_ccmp_256(dev, apdev):
10028 """WPS PIN provisioning with configured AP using CCMP-256"""
10029 run_ap_wps_conf_pin_cipher(dev, apdev, "CCMP-256")
10030
10031 def run_ap_wps_conf_pin_cipher(dev, apdev, cipher):
10032 if cipher not in dev[0].get_capability("pairwise"):
10033 raise HwsimSkip("Cipher %s not supported" % cipher)
10034 ssid = "test-wps-conf-pin"
10035 hapd = hostapd.add_ap(apdev[0],
10036 { "ssid": ssid, "eap_server": "1", "wps_state": "2",
10037 "wpa_passphrase": "12345678", "wpa": "2",
10038 "wpa_key_mgmt": "WPA-PSK",
10039 "rsn_pairwise": cipher })
10040 logger.info("WPS provisioning step")
10041 pin = dev[0].wps_read_pin()
10042 hapd.request("WPS_PIN any " + pin)
10043 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10044 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10045 dev[0].wait_connected(timeout=15)