]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/test_ap_wps.py
tests: Make wps_reg() test cases more robust
[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 from tshark import run_tshark
9 import base64
10 import binascii
11 from Crypto.Cipher import AES
12 import hashlib
13 import hmac
14 import os
15 import time
16 import sys
17 import stat
18 import subprocess
19 import logging
20 logger = logging.getLogger()
21 import re
22 import socket
23 import struct
24 try:
25 from http.client import HTTPConnection
26 from urllib.request import urlopen
27 from urllib.parse import urlparse, urljoin
28 from urllib.error import HTTPError
29 from io import StringIO
30 from socketserver import StreamRequestHandler, TCPServer
31 except ImportError:
32 from httplib import HTTPConnection
33 from urllib import urlopen
34 from urlparse import urlparse, urljoin
35 from urllib2 import build_opener, ProxyHandler, HTTPError
36 from StringIO import StringIO
37 from SocketServer import StreamRequestHandler, TCPServer
38 import urllib
39 import xml.etree.ElementTree as ET
40
41 import hwsim_utils
42 import hostapd
43 from wpasupplicant import WpaSupplicant
44 from utils import HwsimSkip, alloc_fail, fail_test, skip_with_fips
45 from utils import wait_fail_trigger, clear_regdom
46 from test_ap_eap import int_eap_server_params
47
48 def wps_start_ap(apdev, ssid="test-wps-conf"):
49 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
50 "wpa_passphrase": "12345678", "wpa": "2",
51 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
52 return hostapd.add_ap(apdev, params)
53
54 @remote_compatible
55 def test_ap_wps_init(dev, apdev):
56 """Initial AP configuration with first WPS Enrollee"""
57 ssid = "test-wps"
58 hapd = hostapd.add_ap(apdev[0],
59 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
60 logger.info("WPS provisioning step")
61 hapd.request("WPS_PBC")
62 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
63 raise Exception("PBC status not shown correctly")
64
65 id = dev[0].add_network()
66 dev[0].set_network_quoted(id, "ssid", "home")
67 dev[0].set_network_quoted(id, "psk", "12345678")
68 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
69
70 id = dev[0].add_network()
71 dev[0].set_network_quoted(id, "ssid", "home2")
72 dev[0].set_network(id, "bssid", "00:11:22:33:44:55")
73 dev[0].set_network(id, "key_mgmt", "NONE")
74 dev[0].request("ENABLE_NETWORK %s no-connect" % id)
75
76 dev[0].request("WPS_PBC")
77 dev[0].wait_connected(timeout=30)
78 status = dev[0].get_status()
79 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
80 raise Exception("Not fully connected")
81 if status['ssid'] != ssid:
82 raise Exception("Unexpected SSID")
83 if status['pairwise_cipher'] != 'CCMP':
84 raise Exception("Unexpected encryption configuration")
85 if status['key_mgmt'] != 'WPA2-PSK':
86 raise Exception("Unexpected key_mgmt")
87
88 status = hapd.request("WPS_GET_STATUS")
89 if "PBC Status: Disabled" not in status:
90 raise Exception("PBC status not shown correctly")
91 if "Last WPS result: Success" not in status:
92 raise Exception("Last WPS result not shown correctly")
93 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
94 raise Exception("Peer address not shown correctly")
95 conf = hapd.request("GET_CONFIG")
96 if "wps_state=configured" not in conf:
97 raise Exception("AP not in WPS configured state")
98 if "wpa=3" not in conf:
99 raise Exception("AP not in WPA+WPA2 configuration")
100 if "rsn_pairwise_cipher=CCMP TKIP" not in conf:
101 raise Exception("Unexpected rsn_pairwise_cipher")
102 if "wpa_pairwise_cipher=CCMP TKIP" not in conf:
103 raise Exception("Unexpected wpa_pairwise_cipher")
104 if "group_cipher=TKIP" not in conf:
105 raise Exception("Unexpected group_cipher")
106
107 if len(dev[0].list_networks()) != 3:
108 raise Exception("Unexpected number of network blocks")
109
110 def test_ap_wps_init_2ap_pbc(dev, apdev):
111 """Initial two-radio AP configuration with first WPS PBC Enrollee"""
112 ssid = "test-wps"
113 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
114 hapd = hostapd.add_ap(apdev[0], params)
115 hostapd.add_ap(apdev[1], params)
116 logger.info("WPS provisioning step")
117 hapd.request("WPS_PBC")
118 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
119 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
120 bss = dev[0].get_bss(apdev[0]['bssid'])
121 if "[WPS-PBC]" not in bss['flags']:
122 raise Exception("WPS-PBC flag missing from AP1")
123 bss = dev[0].get_bss(apdev[1]['bssid'])
124 if "[WPS-PBC]" not in bss['flags']:
125 raise Exception("WPS-PBC flag missing from AP2")
126 dev[0].dump_monitor()
127 dev[0].request("SET wps_cred_processing 2")
128 dev[0].request("WPS_PBC")
129 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=30)
130 dev[0].request("SET wps_cred_processing 0")
131 if ev is None:
132 raise Exception("WPS cred event not seen")
133 if "100e" not in ev:
134 raise Exception("WPS attributes not included in the cred event")
135 dev[0].wait_connected(timeout=30)
136
137 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
138 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
139 bss = dev[1].get_bss(apdev[0]['bssid'])
140 if "[WPS-PBC]" in bss['flags']:
141 raise Exception("WPS-PBC flag not cleared from AP1")
142 bss = dev[1].get_bss(apdev[1]['bssid'])
143 if "[WPS-PBC]" in bss['flags']:
144 raise Exception("WPS-PBC flag not cleared from AP2")
145
146 def test_ap_wps_init_2ap_pin(dev, apdev):
147 """Initial two-radio AP configuration with first WPS PIN Enrollee"""
148 ssid = "test-wps"
149 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
150 hapd = hostapd.add_ap(apdev[0], params)
151 hostapd.add_ap(apdev[1], params)
152 logger.info("WPS provisioning step")
153 pin = dev[0].wps_read_pin()
154 hapd.request("WPS_PIN any " + pin)
155 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
156 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
157 bss = dev[0].get_bss(apdev[0]['bssid'])
158 if "[WPS-AUTH]" not in bss['flags']:
159 raise Exception("WPS-AUTH flag missing from AP1")
160 bss = dev[0].get_bss(apdev[1]['bssid'])
161 if "[WPS-AUTH]" not in bss['flags']:
162 raise Exception("WPS-AUTH flag missing from AP2")
163 dev[0].dump_monitor()
164 dev[0].request("WPS_PIN any " + pin)
165 dev[0].wait_connected(timeout=30)
166
167 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
168 dev[1].scan_for_bss(apdev[1]['bssid'], freq="2412")
169 bss = dev[1].get_bss(apdev[0]['bssid'])
170 if "[WPS-AUTH]" in bss['flags']:
171 raise Exception("WPS-AUTH flag not cleared from AP1")
172 bss = dev[1].get_bss(apdev[1]['bssid'])
173 if "[WPS-AUTH]" in bss['flags']:
174 raise Exception("WPS-AUTH flag not cleared from AP2")
175
176 @remote_compatible
177 def test_ap_wps_init_through_wps_config(dev, apdev):
178 """Initial AP configuration using wps_config command"""
179 ssid = "test-wps-init-config"
180 hapd = hostapd.add_ap(apdev[0],
181 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
182 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
183 raise Exception("WPS_CONFIG command failed")
184 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
185 if ev is None:
186 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
187 # It takes some time for the AP to update Beacon and Probe Response frames,
188 # so wait here before requesting the scan to be started to avoid adding
189 # extra five second wait to the test due to fetching obsolete scan results.
190 hapd.ping()
191 time.sleep(0.2)
192 dev[0].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
193 pairwise="CCMP", group="CCMP")
194
195 if "FAIL" not in hapd.request("WPS_CONFIG foo"):
196 raise Exception("Invalid WPS_CONFIG accepted")
197
198 @remote_compatible
199 def test_ap_wps_init_through_wps_config_2(dev, apdev):
200 """AP configuration using wps_config and wps_cred_processing=2"""
201 ssid = "test-wps-init-config"
202 hapd = hostapd.add_ap(apdev[0],
203 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
204 "wps_cred_processing": "2"})
205 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"12345678").decode()):
206 raise Exception("WPS_CONFIG command failed")
207 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
208 if ev is None:
209 raise Exception("Timeout on WPS-NEW-AP-SETTINGS events")
210 if "100e" not in ev:
211 raise Exception("WPS-NEW-AP-SETTINGS did not include Credential")
212
213 @remote_compatible
214 def test_ap_wps_invalid_wps_config_passphrase(dev, apdev):
215 """AP configuration using wps_config command with invalid passphrase"""
216 ssid = "test-wps-init-config"
217 hapd = hostapd.add_ap(apdev[0],
218 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
219 if "FAIL" not in hapd.request("WPS_CONFIG " + binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(b"1234567").decode()):
220 raise Exception("Invalid WPS_CONFIG command accepted")
221
222 def test_ap_wps_conf(dev, apdev):
223 """WPS PBC provisioning with configured AP"""
224 ssid = "test-wps-conf"
225 hapd = hostapd.add_ap(apdev[0],
226 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
227 "wpa_passphrase": "12345678", "wpa": "2",
228 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
229 logger.info("WPS provisioning step")
230 hapd.request("WPS_PBC")
231 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
232 dev[0].dump_monitor()
233 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
234 dev[0].wait_connected(timeout=30)
235 status = dev[0].get_status()
236 if status['wpa_state'] != 'COMPLETED':
237 raise Exception("Not fully connected")
238 if status['bssid'] != apdev[0]['bssid']:
239 raise Exception("Unexpected BSSID")
240 if status['ssid'] != ssid:
241 raise Exception("Unexpected SSID")
242 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
243 raise Exception("Unexpected encryption configuration")
244 if status['key_mgmt'] != 'WPA2-PSK':
245 raise Exception("Unexpected key_mgmt")
246
247 sta = hapd.get_sta(dev[0].p2p_interface_addr())
248 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
249 raise Exception("Device name not available in STA command")
250
251 def test_ap_wps_conf_5ghz(dev, apdev):
252 """WPS PBC provisioning with configured AP on 5 GHz band"""
253 try:
254 hapd = None
255 ssid = "test-wps-conf"
256 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
257 "wpa_passphrase": "12345678", "wpa": "2",
258 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
259 "country_code": "FI", "hw_mode": "a", "channel": "36"}
260 hapd = hostapd.add_ap(apdev[0], params)
261 logger.info("WPS provisioning step")
262 hapd.request("WPS_PBC")
263 dev[0].scan_for_bss(apdev[0]['bssid'], freq="5180")
264 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
265 dev[0].wait_connected(timeout=30)
266
267 sta = hapd.get_sta(dev[0].p2p_interface_addr())
268 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
269 raise Exception("Device name not available in STA command")
270 finally:
271 dev[0].request("DISCONNECT")
272 clear_regdom(hapd, dev)
273
274 def test_ap_wps_conf_chan14(dev, apdev):
275 """WPS PBC provisioning with configured AP on channel 14"""
276 try:
277 hapd = None
278 ssid = "test-wps-conf"
279 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
280 "wpa_passphrase": "12345678", "wpa": "2",
281 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
282 "country_code": "JP", "hw_mode": "b", "channel": "14"}
283 hapd = hostapd.add_ap(apdev[0], params)
284 logger.info("WPS provisioning step")
285 hapd.request("WPS_PBC")
286 dev[0].request("WPS_PBC")
287 dev[0].wait_connected(timeout=30)
288
289 sta = hapd.get_sta(dev[0].p2p_interface_addr())
290 if 'wpsDeviceName' not in sta or sta['wpsDeviceName'] != "Device A":
291 raise Exception("Device name not available in STA command")
292 finally:
293 dev[0].request("DISCONNECT")
294 clear_regdom(hapd, dev)
295
296 @remote_compatible
297 def test_ap_wps_twice(dev, apdev):
298 """WPS provisioning with twice to change passphrase"""
299 ssid = "test-wps-twice"
300 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
301 "wpa_passphrase": "12345678", "wpa": "2",
302 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
303 hapd = hostapd.add_ap(apdev[0], params)
304 logger.info("WPS provisioning step")
305 hapd.request("WPS_PBC")
306 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
307 dev[0].dump_monitor()
308 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
309 dev[0].wait_connected(timeout=30)
310 dev[0].request("DISCONNECT")
311
312 logger.info("Restart AP with different passphrase and re-run WPS")
313 hostapd.remove_bss(apdev[0])
314 params['wpa_passphrase'] = 'another passphrase'
315 hapd = hostapd.add_ap(apdev[0], params)
316 logger.info("WPS provisioning step")
317 hapd.request("WPS_PBC")
318 dev[0].dump_monitor()
319 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
320 dev[0].wait_connected(timeout=30)
321 networks = dev[0].list_networks()
322 if len(networks) > 1:
323 raise Exception("Unexpected duplicated network block present")
324
325 @remote_compatible
326 def test_ap_wps_incorrect_pin(dev, apdev):
327 """WPS PIN provisioning with incorrect PIN"""
328 ssid = "test-wps-incorrect-pin"
329 hapd = hostapd.add_ap(apdev[0],
330 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
331 "wpa_passphrase": "12345678", "wpa": "2",
332 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
333
334 logger.info("WPS provisioning attempt 1")
335 hapd.request("WPS_PIN any 12345670")
336 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
337 dev[0].dump_monitor()
338 dev[0].request("WPS_PIN %s 55554444" % apdev[0]['bssid'])
339 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
340 if ev is None:
341 raise Exception("WPS operation timed out")
342 if "config_error=18" not in ev:
343 raise Exception("Incorrect config_error reported")
344 if "msg=8" not in ev:
345 raise Exception("PIN error detected on incorrect message")
346 dev[0].wait_disconnected(timeout=10)
347 dev[0].request("WPS_CANCEL")
348 # if a scan was in progress, wait for it to complete before trying WPS again
349 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
350
351 status = hapd.request("WPS_GET_STATUS")
352 if "Last WPS result: Failed" not in status:
353 raise Exception("WPS failure result not shown correctly")
354
355 logger.info("WPS provisioning attempt 2")
356 hapd.request("WPS_PIN any 12345670")
357 dev[0].dump_monitor()
358 dev[0].request("WPS_PIN %s 12344444" % apdev[0]['bssid'])
359 ev = dev[0].wait_event(["WPS-FAIL"], timeout=30)
360 if ev is None:
361 raise Exception("WPS operation timed out")
362 if "config_error=18" not in ev:
363 raise Exception("Incorrect config_error reported")
364 if "msg=10" not in ev:
365 raise Exception("PIN error detected on incorrect message")
366 dev[0].wait_disconnected(timeout=10)
367
368 @remote_compatible
369 def test_ap_wps_conf_pin(dev, apdev):
370 """WPS PIN provisioning with configured AP"""
371 ssid = "test-wps-conf-pin"
372 hapd = hostapd.add_ap(apdev[0],
373 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
374 "wpa_passphrase": "12345678", "wpa": "2",
375 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
376 logger.info("WPS provisioning step")
377 pin = dev[0].wps_read_pin()
378 hapd.request("WPS_PIN any " + pin)
379 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
380 dev[0].dump_monitor()
381 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
382 dev[0].wait_connected(timeout=30)
383 status = dev[0].get_status()
384 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
385 raise Exception("Not fully connected")
386 if status['ssid'] != ssid:
387 raise Exception("Unexpected SSID")
388 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
389 raise Exception("Unexpected encryption configuration")
390 if status['key_mgmt'] != 'WPA2-PSK':
391 raise Exception("Unexpected key_mgmt")
392
393 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
394 bss = dev[1].get_bss(apdev[0]['bssid'])
395 if "[WPS-AUTH]" in bss['flags']:
396 raise Exception("WPS-AUTH flag not cleared")
397 logger.info("Try to connect from another station using the same PIN")
398 pin = dev[1].request("WPS_PIN " + apdev[0]['bssid'])
399 ev = dev[1].wait_event(["WPS-M2D", "CTRL-EVENT-CONNECTED"], timeout=30)
400 if ev is None:
401 raise Exception("Operation timed out")
402 if "WPS-M2D" not in ev:
403 raise Exception("Unexpected WPS operation started")
404 hapd.request("WPS_PIN any " + pin)
405 dev[1].wait_connected(timeout=30)
406
407 def test_ap_wps_conf_pin_mixed_mode(dev, apdev):
408 """WPS PIN provisioning with configured AP (WPA+WPA2)"""
409 ssid = "test-wps-conf-pin-mixed"
410 hapd = hostapd.add_ap(apdev[0],
411 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
412 "wpa_passphrase": "12345678", "wpa": "3",
413 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
414 "wpa_pairwise": "TKIP"})
415
416 logger.info("WPS provisioning step")
417 pin = dev[0].wps_read_pin()
418 hapd.request("WPS_PIN any " + pin)
419 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
420 dev[0].dump_monitor()
421 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
422 dev[0].wait_connected(timeout=30)
423 status = dev[0].get_status()
424 dev[0].request("REMOVE_NETWORK all")
425 dev[0].wait_disconnected()
426 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
427 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
428
429 logger.info("WPS provisioning step (auth_types=0x1b)")
430 if "OK" not in dev[0].request("SET wps_force_auth_types 0x1b"):
431 raise Exception("Failed to set wps_force_auth_types 0x1b")
432 pin = dev[0].wps_read_pin()
433 hapd.request("WPS_PIN any " + pin)
434 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
435 dev[0].dump_monitor()
436 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
437 dev[0].wait_connected(timeout=30)
438 status = dev[0].get_status()
439 dev[0].request("REMOVE_NETWORK all")
440 dev[0].wait_disconnected()
441 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
442 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
443
444 logger.info("WPS provisioning step (auth_types=0 encr_types=0)")
445 if "OK" not in dev[0].request("SET wps_force_auth_types 0"):
446 raise Exception("Failed to set wps_force_auth_types 0")
447 if "OK" not in dev[0].request("SET wps_force_encr_types 0"):
448 raise Exception("Failed to set wps_force_encr_types 0")
449 pin = dev[0].wps_read_pin()
450 hapd.request("WPS_PIN any " + pin)
451 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
452 dev[0].dump_monitor()
453 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
454 dev[0].wait_connected(timeout=30)
455 status = dev[0].get_status()
456 dev[0].request("REMOVE_NETWORK all")
457 dev[0].wait_disconnected()
458 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP' or status['key_mgmt'] != 'WPA2-PSK':
459 raise Exception("Unexpected encryption/key_mgmt configuration: pairwise=%s group=%s key_mgmt=%s" % (status['pairwise_cipher'], status['group_cipher'], status['key_mgmt']))
460
461 dev[0].request("SET wps_force_auth_types ")
462 dev[0].request("SET wps_force_encr_types ")
463
464 @remote_compatible
465 def test_ap_wps_conf_pin_v1(dev, apdev):
466 """WPS PIN provisioning with configured WPS v1.0 AP"""
467 ssid = "test-wps-conf-pin-v1"
468 hapd = hostapd.add_ap(apdev[0],
469 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
470 "wpa_passphrase": "12345678", "wpa": "2",
471 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
472 logger.info("WPS provisioning step")
473 pin = dev[0].wps_read_pin()
474 hapd.request("SET wps_version_number 0x10")
475 hapd.request("WPS_PIN any " + pin)
476 found = False
477 for i in range(0, 10):
478 dev[0].scan(freq="2412")
479 if "[WPS-PIN]" in dev[0].request("SCAN_RESULTS"):
480 found = True
481 break
482 if not found:
483 hapd.request("SET wps_version_number 0x20")
484 raise Exception("WPS-PIN flag not seen in scan results")
485 dev[0].dump_monitor()
486 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
487 dev[0].wait_connected(timeout=30)
488 hapd.request("SET wps_version_number 0x20")
489
490 @remote_compatible
491 def test_ap_wps_conf_pin_2sta(dev, apdev):
492 """Two stations trying to use WPS PIN at the same time"""
493 ssid = "test-wps-conf-pin2"
494 hapd = hostapd.add_ap(apdev[0],
495 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
496 "wpa_passphrase": "12345678", "wpa": "2",
497 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
498 logger.info("WPS provisioning step")
499 pin = "12345670"
500 pin2 = "55554444"
501 hapd.request("WPS_PIN " + dev[0].get_status_field("uuid") + " " + pin)
502 hapd.request("WPS_PIN " + dev[1].get_status_field("uuid") + " " + pin)
503 dev[0].dump_monitor()
504 dev[1].dump_monitor()
505 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
506 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
507 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
508 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
509 dev[0].wait_connected(timeout=30)
510 dev[1].wait_connected(timeout=30)
511
512 @remote_compatible
513 def test_ap_wps_conf_pin_timeout(dev, apdev):
514 """WPS PIN provisioning with configured AP timing out PIN"""
515 ssid = "test-wps-conf-pin"
516 hapd = hostapd.add_ap(apdev[0],
517 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
518 "wpa_passphrase": "12345678", "wpa": "2",
519 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
520 addr = dev[0].p2p_interface_addr()
521 pin = dev[0].wps_read_pin()
522 if "FAIL" not in hapd.request("WPS_PIN "):
523 raise Exception("Unexpected success on invalid WPS_PIN")
524 hapd.request("WPS_PIN any " + pin + " 1")
525 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
526 time.sleep(1.1)
527 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
528 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=20)
529 if ev is None:
530 raise Exception("WPS-PIN-NEEDED event timed out")
531 ev = dev[0].wait_event(["WPS-M2D"])
532 if ev is None:
533 raise Exception("M2D not reported")
534 dev[0].request("WPS_CANCEL")
535
536 hapd.request("WPS_PIN any " + pin + " 20 " + addr)
537 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
538 dev[0].wait_connected(timeout=30)
539
540 def test_ap_wps_reg_connect(dev, apdev):
541 """WPS registrar using AP PIN to connect"""
542 ssid = "test-wps-reg-ap-pin"
543 appin = "12345670"
544 hostapd.add_ap(apdev[0],
545 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
546 "wpa_passphrase": "12345678", "wpa": "2",
547 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
548 "ap_pin": appin})
549 logger.info("WPS provisioning step")
550 dev[0].dump_monitor()
551 dev[0].flush_scan_cache()
552 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
553 dev[0].wps_reg(apdev[0]['bssid'], appin)
554 status = dev[0].get_status()
555 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
556 raise Exception("Not fully connected")
557 if status['ssid'] != ssid:
558 raise Exception("Unexpected SSID")
559 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
560 raise Exception("Unexpected encryption configuration")
561 if status['key_mgmt'] != 'WPA2-PSK':
562 raise Exception("Unexpected key_mgmt")
563
564 def test_ap_wps_reg_connect_zero_len_ap_pin(dev, apdev):
565 """hostapd with zero length ap_pin parameter"""
566 ssid = "test-wps-reg-ap-pin"
567 appin = ""
568 hostapd.add_ap(apdev[0],
569 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
570 "wpa_passphrase": "12345678", "wpa": "2",
571 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
572 "ap_pin": appin})
573 logger.info("WPS provisioning step")
574 dev[0].dump_monitor()
575 dev[0].flush_scan_cache()
576 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
577 dev[0].wps_reg(apdev[0]['bssid'], appin, no_wait=True)
578 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
579 if ev is None:
580 raise Exception("No WPS-FAIL reported")
581 if "msg=5 config_error=15" not in ev:
582 raise Exception("Unexpected WPS-FAIL: " + ev)
583
584 def test_ap_wps_reg_connect_mixed_mode(dev, apdev):
585 """WPS registrar using AP PIN to connect (WPA+WPA2)"""
586 ssid = "test-wps-reg-ap-pin"
587 appin = "12345670"
588 hostapd.add_ap(apdev[0],
589 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
590 "wpa_passphrase": "12345678", "wpa": "3",
591 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
592 "wpa_pairwise": "TKIP", "ap_pin": appin})
593 dev[0].flush_scan_cache()
594 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
595 dev[0].wps_reg(apdev[0]['bssid'], appin)
596 status = dev[0].get_status()
597 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
598 raise Exception("Not fully connected")
599 if status['ssid'] != ssid:
600 raise Exception("Unexpected SSID")
601 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
602 raise Exception("Unexpected encryption configuration")
603 if status['key_mgmt'] != 'WPA2-PSK':
604 raise Exception("Unexpected key_mgmt")
605
606 def test_ap_wps_reg_override_ap_settings(dev, apdev):
607 """WPS registrar and ap_settings override"""
608 ap_settings = "/tmp/ap_wps_reg_override_ap_settings"
609 try:
610 os.remove(ap_settings)
611 except:
612 pass
613 # Override AP Settings with values that point to another AP
614 data = build_wsc_attr(ATTR_NETWORK_INDEX, b'\x01')
615 data += build_wsc_attr(ATTR_SSID, b"test")
616 data += build_wsc_attr(ATTR_AUTH_TYPE, b'\x00\x01')
617 data += build_wsc_attr(ATTR_ENCR_TYPE, b'\x00\x01')
618 data += build_wsc_attr(ATTR_NETWORK_KEY, b'')
619 data += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[1]['bssid'].replace(':', '')))
620 with open(ap_settings, "wb") as f:
621 f.write(data)
622 ssid = "test-wps-reg-ap-pin"
623 appin = "12345670"
624 hostapd.add_ap(apdev[0],
625 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
626 "wpa_passphrase": "12345678", "wpa": "2",
627 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
628 "ap_pin": appin, "ap_settings": ap_settings})
629 hapd2 = hostapd.add_ap(apdev[1], {"ssid": "test"})
630 dev[0].flush_scan_cache()
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].flush_scan_cache()
670 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
671 dev[0].wps_reg(apdev[0]['bssid'], appin)
672
673 hapd.request("WPS_AP_PIN disable")
674 logger.info("WPS provisioning step with AP PIN disabled")
675 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
676 check_wps_reg_failure(dev[1], apdev[0], appin)
677
678 logger.info("WPS provisioning step with AP PIN reset")
679 appin = "12345670"
680 hapd.request("WPS_AP_PIN set " + appin)
681 dev[1].wps_reg(apdev[0]['bssid'], appin)
682 dev[0].request("REMOVE_NETWORK all")
683 dev[1].request("REMOVE_NETWORK all")
684 dev[0].wait_disconnected(timeout=10)
685 dev[1].wait_disconnected(timeout=10)
686
687 logger.info("WPS provisioning step after AP PIN timeout")
688 hapd.request("WPS_AP_PIN disable")
689 appin = hapd.request("WPS_AP_PIN random 1")
690 time.sleep(1.1)
691 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
692 raise Exception("AP PIN unexpectedly still enabled")
693 check_wps_reg_failure(dev[0], apdev[0], appin)
694
695 logger.info("WPS provisioning step after AP PIN timeout(2)")
696 hapd.request("WPS_AP_PIN disable")
697 appin = "12345670"
698 hapd.request("WPS_AP_PIN set " + appin + " 1")
699 time.sleep(1.1)
700 if "FAIL" not in hapd.request("WPS_AP_PIN get"):
701 raise Exception("AP PIN unexpectedly still enabled")
702 check_wps_reg_failure(dev[1], apdev[0], appin)
703
704 with fail_test(hapd, 1, "os_get_random;wps_generate_pin"):
705 hapd.request("WPS_AP_PIN random 1")
706 hapd.request("WPS_AP_PIN disable")
707
708 with alloc_fail(hapd, 1, "upnp_wps_set_ap_pin"):
709 hapd.request("WPS_AP_PIN set 12345670")
710 hapd.request("WPS_AP_PIN disable")
711
712 if "FAIL" not in hapd.request("WPS_AP_PIN set"):
713 raise Exception("Invalid WPS_AP_PIN accepted")
714 if "FAIL" not in hapd.request("WPS_AP_PIN foo"):
715 raise Exception("Invalid WPS_AP_PIN accepted")
716
717 def test_ap_wps_reg_config(dev, apdev):
718 """WPS registrar configuring an AP using AP PIN"""
719 ssid = "test-wps-init-ap-pin"
720 appin = "12345670"
721 hostapd.add_ap(apdev[0],
722 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
723 "ap_pin": appin})
724 logger.info("WPS configuration step")
725 dev[0].flush_scan_cache()
726 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
727 dev[0].dump_monitor()
728 new_ssid = "wps-new-ssid"
729 new_passphrase = "1234567890"
730 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
731 new_passphrase)
732 status = dev[0].get_status()
733 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
734 raise Exception("Not fully connected")
735 if status['ssid'] != new_ssid:
736 raise Exception("Unexpected SSID")
737 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
738 raise Exception("Unexpected encryption configuration")
739 if status['key_mgmt'] != 'WPA2-PSK':
740 raise Exception("Unexpected key_mgmt")
741
742 logger.info("Re-configure back to open")
743 dev[0].request("REMOVE_NETWORK all")
744 dev[0].flush_scan_cache()
745 dev[0].dump_monitor()
746 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-open", "OPEN", "NONE", "")
747 status = dev[0].get_status()
748 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
749 raise Exception("Not fully connected")
750 if status['ssid'] != "wps-open":
751 raise Exception("Unexpected SSID")
752 if status['key_mgmt'] != 'NONE':
753 raise Exception("Unexpected key_mgmt")
754
755 def test_ap_wps_reg_config_ext_processing(dev, apdev):
756 """WPS registrar configuring an AP with external config processing"""
757 ssid = "test-wps-init-ap-pin"
758 appin = "12345670"
759 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
760 "wps_cred_processing": "1", "ap_pin": appin}
761 hapd = hostapd.add_ap(apdev[0], params)
762 dev[0].flush_scan_cache()
763 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
764 new_ssid = "wps-new-ssid"
765 new_passphrase = "1234567890"
766 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
767 new_passphrase, no_wait=True)
768 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
769 if ev is None:
770 raise Exception("WPS registrar operation timed out")
771 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=15)
772 if ev is None:
773 raise Exception("WPS configuration timed out")
774 if "1026" not in ev:
775 raise Exception("AP Settings missing from event")
776 hapd.request("SET wps_cred_processing 0")
777 if "FAIL" in hapd.request("WPS_CONFIG " + binascii.hexlify(new_ssid.encode()).decode() + " WPA2PSK CCMP " + binascii.hexlify(new_passphrase.encode()).decode()):
778 raise Exception("WPS_CONFIG command failed")
779 dev[0].wait_connected(timeout=15)
780
781 def test_ap_wps_reg_config_tkip(dev, apdev):
782 """WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
783 skip_with_fips(dev[0])
784 ssid = "test-wps-init-ap"
785 appin = "12345670"
786 hostapd.add_ap(apdev[0],
787 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
788 "ap_pin": appin})
789 logger.info("WPS configuration step")
790 dev[0].flush_scan_cache()
791 dev[0].request("SET wps_version_number 0x10")
792 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
793 dev[0].dump_monitor()
794 new_ssid = "wps-new-ssid-with-tkip"
795 new_passphrase = "1234567890"
796 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPAPSK", "TKIP",
797 new_passphrase)
798 logger.info("Re-connect to verify WPA2 mixed mode")
799 dev[0].request("DISCONNECT")
800 id = 0
801 dev[0].set_network(id, "pairwise", "CCMP")
802 dev[0].set_network(id, "proto", "RSN")
803 dev[0].connect_network(id)
804 status = dev[0].get_status()
805 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
806 raise Exception("Not fully connected: wpa_state={} bssid={}".format(status['wpa_state'], status['bssid']))
807 if status['ssid'] != new_ssid:
808 raise Exception("Unexpected SSID")
809 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
810 raise Exception("Unexpected encryption configuration")
811 if status['key_mgmt'] != 'WPA2-PSK':
812 raise Exception("Unexpected key_mgmt")
813
814 def test_ap_wps_setup_locked(dev, apdev):
815 """WPS registrar locking up AP setup on AP PIN failures"""
816 ssid = "test-wps-incorrect-ap-pin"
817 appin = "12345670"
818 hapd = hostapd.add_ap(apdev[0],
819 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
820 "wpa_passphrase": "12345678", "wpa": "2",
821 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
822 "ap_pin": appin})
823 new_ssid = "wps-new-ssid-test"
824 new_passphrase = "1234567890"
825
826 dev[0].flush_scan_cache()
827 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
828 ap_setup_locked = False
829 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
830 dev[0].dump_monitor()
831 logger.info("Try incorrect AP PIN - attempt " + pin)
832 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
833 "CCMP", new_passphrase, no_wait=True)
834 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
835 if ev is None:
836 raise Exception("Timeout on receiving WPS operation failure event")
837 if "CTRL-EVENT-CONNECTED" in ev:
838 raise Exception("Unexpected connection")
839 if "config_error=15" in ev:
840 logger.info("AP Setup Locked")
841 ap_setup_locked = True
842 elif "config_error=18" not in ev:
843 raise Exception("config_error=18 not reported")
844 dev[0].wait_disconnected(timeout=10)
845 time.sleep(0.1)
846 if not ap_setup_locked:
847 raise Exception("AP setup was not locked")
848 dev[0].request("WPS_CANCEL")
849 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True,
850 only_new=True)
851 bss = dev[0].get_bss(apdev[0]['bssid'])
852 if 'wps_ap_setup_locked' not in bss or bss['wps_ap_setup_locked'] != '1':
853 logger.info("BSS: " + str(bss))
854 raise Exception("AP Setup Locked not indicated in scan results")
855
856 status = hapd.request("WPS_GET_STATUS")
857 if "Last WPS result: Failed" not in status:
858 raise Exception("WPS failure result not shown correctly")
859 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
860 raise Exception("Peer address not shown correctly")
861
862 time.sleep(0.5)
863 dev[0].dump_monitor()
864 logger.info("WPS provisioning step")
865 pin = dev[0].wps_read_pin()
866 hapd.request("WPS_PIN any " + pin)
867 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
868 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
869 if ev is None:
870 raise Exception("WPS success was not reported")
871 dev[0].wait_connected(timeout=30)
872
873 appin = hapd.request("WPS_AP_PIN random")
874 if "FAIL" in appin:
875 raise Exception("Could not generate random AP PIN")
876 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=10)
877 if ev is None:
878 raise Exception("Failed to unlock AP PIN")
879
880 def test_ap_wps_setup_locked_timeout(dev, apdev):
881 """WPS re-enabling AP PIN after timeout"""
882 ssid = "test-wps-incorrect-ap-pin"
883 appin = "12345670"
884 hapd = hostapd.add_ap(apdev[0],
885 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
886 "wpa_passphrase": "12345678", "wpa": "2",
887 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
888 "ap_pin": appin})
889 new_ssid = "wps-new-ssid-test"
890 new_passphrase = "1234567890"
891
892 dev[0].flush_scan_cache()
893 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
894 ap_setup_locked = False
895 for pin in ["55554444", "1234", "12345678", "00000000", "11111111"]:
896 dev[0].dump_monitor()
897 logger.info("Try incorrect AP PIN - attempt " + pin)
898 dev[0].wps_reg(apdev[0]['bssid'], pin, new_ssid, "WPA2PSK",
899 "CCMP", new_passphrase, no_wait=True)
900 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"], timeout=15)
901 if ev is None:
902 raise Exception("Timeout on receiving WPS operation failure event")
903 if "CTRL-EVENT-CONNECTED" in ev:
904 raise Exception("Unexpected connection")
905 if "config_error=15" in ev:
906 logger.info("AP Setup Locked")
907 ap_setup_locked = True
908 break
909 elif "config_error=18" not in ev:
910 raise Exception("config_error=18 not reported")
911 dev[0].wait_disconnected(timeout=10)
912 time.sleep(0.1)
913 if not ap_setup_locked:
914 raise Exception("AP setup was not locked")
915 ev = hapd.wait_event(["WPS-AP-SETUP-UNLOCKED"], timeout=80)
916 if ev is None:
917 raise Exception("AP PIN did not get unlocked on 60 second timeout")
918
919 def test_ap_wps_setup_locked_2(dev, apdev):
920 """WPS AP configured for special ap_setup_locked=2 mode"""
921 ssid = "test-wps-ap-pin"
922 appin = "12345670"
923 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
924 "wpa_passphrase": "12345678", "wpa": "2",
925 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
926 "ap_pin": appin, "ap_setup_locked": "2"}
927 hapd = hostapd.add_ap(apdev[0], params)
928 new_ssid = "wps-new-ssid-test"
929 new_passphrase = "1234567890"
930
931 dev[0].flush_scan_cache()
932 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
933 dev[0].wps_reg(apdev[0]['bssid'], appin)
934 dev[0].request("REMOVE_NETWORK all")
935 dev[0].wait_disconnected()
936
937 hapd.dump_monitor()
938 dev[0].dump_monitor()
939 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK",
940 "CCMP", new_passphrase, no_wait=True)
941
942 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
943 if ev is None:
944 raise Exception("hostapd did not report WPS failure")
945 if "msg=12 config_error=15" not in ev:
946 raise Exception("Unexpected failure reason (AP): " + ev)
947
948 ev = dev[0].wait_event(["WPS-FAIL", "CTRL-EVENT-CONNECTED"])
949 if ev is None:
950 raise Exception("Timeout on receiving WPS operation failure event")
951 if "CTRL-EVENT-CONNECTED" in ev:
952 raise Exception("Unexpected connection")
953 if "config_error=15" not in ev:
954 raise Exception("Unexpected failure reason (STA): " + ev)
955 dev[0].request("WPS_CANCEL")
956 dev[0].wait_disconnected()
957
958 @remote_compatible
959 def test_ap_wps_pbc_overlap_2ap(dev, apdev):
960 """WPS PBC session overlap with two active APs"""
961 params = {"ssid": "wps1", "eap_server": "1", "wps_state": "2",
962 "wpa_passphrase": "12345678", "wpa": "2",
963 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
964 "wps_independent": "1"}
965 hapd = hostapd.add_ap(apdev[0], params)
966 params = {"ssid": "wps2", "eap_server": "1", "wps_state": "2",
967 "wpa_passphrase": "123456789", "wpa": "2",
968 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
969 "wps_independent": "1"}
970 hapd2 = hostapd.add_ap(apdev[1], params)
971 hapd.request("WPS_PBC")
972 hapd2.request("WPS_PBC")
973 logger.info("WPS provisioning step")
974 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
975 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
976 dev[0].request("WPS_PBC")
977 ev = dev[0].wait_event(["WPS-OVERLAP-DETECTED"], timeout=15)
978 if ev is None:
979 raise Exception("PBC session overlap not detected")
980 hapd.request("DISABLE")
981 hapd2.request("DISABLE")
982 dev[0].flush_scan_cache()
983
984 @remote_compatible
985 def test_ap_wps_pbc_overlap_2sta(dev, apdev):
986 """WPS PBC session overlap with two active STAs"""
987 ssid = "test-wps-pbc-overlap"
988 hapd = hostapd.add_ap(apdev[0],
989 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
990 "wpa_passphrase": "12345678", "wpa": "2",
991 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
992 logger.info("WPS provisioning step")
993 hapd.request("WPS_PBC")
994 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
995 dev[0].dump_monitor()
996 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
997 dev[1].dump_monitor()
998 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
999 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1000 ev = dev[0].wait_event(["WPS-M2D"], timeout=15)
1001 if ev is None:
1002 raise Exception("PBC session overlap not detected (dev0)")
1003 if "config_error=12" not in ev:
1004 raise Exception("PBC session overlap not correctly reported (dev0)")
1005 dev[0].request("WPS_CANCEL")
1006 dev[0].request("DISCONNECT")
1007 ev = dev[1].wait_event(["WPS-M2D"], timeout=15)
1008 if ev is None:
1009 raise Exception("PBC session overlap not detected (dev1)")
1010 if "config_error=12" not in ev:
1011 raise Exception("PBC session overlap not correctly reported (dev1)")
1012 dev[1].request("WPS_CANCEL")
1013 dev[1].request("DISCONNECT")
1014 hapd.request("WPS_CANCEL")
1015 ret = hapd.request("WPS_PBC")
1016 if "FAIL" not in ret:
1017 raise Exception("PBC mode allowed to be started while PBC overlap still active")
1018 hapd.request("DISABLE")
1019 dev[0].flush_scan_cache()
1020 dev[1].flush_scan_cache()
1021
1022 @remote_compatible
1023 def test_ap_wps_cancel(dev, apdev):
1024 """WPS AP cancelling enabled config method"""
1025 ssid = "test-wps-ap-cancel"
1026 hapd = hostapd.add_ap(apdev[0],
1027 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1028 "wpa_passphrase": "12345678", "wpa": "2",
1029 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
1030 bssid = apdev[0]['bssid']
1031
1032 logger.info("Verify PBC enable/cancel")
1033 hapd.request("WPS_PBC")
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]" not in bss['flags']:
1038 raise Exception("WPS-PBC flag missing")
1039 if "FAIL" in hapd.request("WPS_CANCEL"):
1040 raise Exception("WPS_CANCEL failed")
1041 dev[0].scan(freq="2412")
1042 dev[0].scan(freq="2412")
1043 bss = dev[0].get_bss(apdev[0]['bssid'])
1044 if "[WPS-PBC]" in bss['flags']:
1045 raise Exception("WPS-PBC flag not cleared")
1046
1047 logger.info("Verify PIN enable/cancel")
1048 hapd.request("WPS_PIN any 12345670")
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]" not in bss['flags']:
1053 raise Exception("WPS-AUTH flag missing")
1054 if "FAIL" in hapd.request("WPS_CANCEL"):
1055 raise Exception("WPS_CANCEL failed")
1056 dev[0].scan(freq="2412")
1057 dev[0].scan(freq="2412")
1058 bss = dev[0].get_bss(apdev[0]['bssid'])
1059 if "[WPS-AUTH]" in bss['flags']:
1060 raise Exception("WPS-AUTH flag not cleared")
1061
1062 def test_ap_wps_er_add_enrollee(dev, apdev):
1063 """WPS ER configuring AP and adding a new enrollee using PIN"""
1064 try:
1065 _test_ap_wps_er_add_enrollee(dev, apdev)
1066 finally:
1067 dev[0].request("WPS_ER_STOP")
1068
1069 def _test_ap_wps_er_add_enrollee(dev, apdev):
1070 ssid = "wps-er-add-enrollee"
1071 ap_pin = "12345670"
1072 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1073 hostapd.add_ap(apdev[0],
1074 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
1075 "device_name": "Wireless AP", "manufacturer": "Company",
1076 "model_name": "WAP", "model_number": "123",
1077 "serial_number": "12345", "device_type": "6-0050F204-1",
1078 "os_version": "01020300",
1079 'friendly_name': "WPS AP - <>&'\" - TEST",
1080 "config_methods": "label push_button",
1081 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1082 logger.info("WPS configuration step")
1083 new_passphrase = "1234567890"
1084 dev[0].dump_monitor()
1085 dev[0].flush_scan_cache()
1086 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1087 dev[0].wps_reg(apdev[0]['bssid'], ap_pin, ssid, "WPA2PSK", "CCMP",
1088 new_passphrase)
1089 status = dev[0].get_status()
1090 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1091 raise Exception("Not fully connected")
1092 if status['ssid'] != ssid:
1093 raise Exception("Unexpected SSID")
1094 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'CCMP':
1095 raise Exception("Unexpected encryption configuration")
1096 if status['key_mgmt'] != 'WPA2-PSK':
1097 raise Exception("Unexpected key_mgmt")
1098
1099 logger.info("Start ER")
1100 dev[0].request("WPS_ER_START ifname=lo")
1101 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1102 if ev is None:
1103 raise Exception("AP discovery timed out")
1104 if ap_uuid not in ev:
1105 raise Exception("Expected AP UUID not found")
1106 if "|WPS AP - &lt;&gt;&amp;&apos;&quot; - TEST|Company|" not in ev:
1107 raise Exception("Expected friendly name not found")
1108
1109 logger.info("Learn AP configuration through UPnP")
1110 dev[0].dump_monitor()
1111 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1112 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1113 if ev is None:
1114 raise Exception("AP learn timed out")
1115 if ap_uuid not in ev:
1116 raise Exception("Expected AP UUID not in settings")
1117 if "ssid=" + ssid not in ev:
1118 raise Exception("Expected SSID not in settings")
1119 if "key=" + new_passphrase not in ev:
1120 raise Exception("Expected passphrase not in settings")
1121 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1122 if ev is None:
1123 raise Exception("WPS-FAIL after AP learn timed out")
1124 time.sleep(0.1)
1125
1126 logger.info("Add Enrollee using ER")
1127 pin = dev[1].wps_read_pin()
1128 dev[0].dump_monitor()
1129 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1130 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1131 dev[1].dump_monitor()
1132 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1133 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1134 if ev is None:
1135 raise Exception("Enrollee did not report success")
1136 dev[1].wait_connected(timeout=15)
1137 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1138 if ev is None:
1139 raise Exception("WPS ER did not report success")
1140 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1141
1142 logger.info("Add a specific Enrollee using ER")
1143 pin = dev[2].wps_read_pin()
1144 addr2 = dev[2].p2p_interface_addr()
1145 dev[0].dump_monitor()
1146 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1147 dev[2].dump_monitor()
1148 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1149 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1150 if ev is None:
1151 raise Exception("Enrollee not seen")
1152 if addr2 not in ev:
1153 raise Exception("Unexpected Enrollee MAC address")
1154 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
1155 dev[2].wait_connected(timeout=30)
1156 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1157 if ev is None:
1158 raise Exception("WPS ER did not report success")
1159
1160 logger.info("Verify registrar selection behavior")
1161 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1162 dev[1].request("DISCONNECT")
1163 dev[1].wait_disconnected(timeout=10)
1164 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1165 dev[1].scan(freq="2412")
1166 bss = dev[1].get_bss(apdev[0]['bssid'])
1167 if "[WPS-AUTH]" not in bss['flags']:
1168 # It is possible for scan to miss an update especially when running
1169 # tests under load with multiple VMs, so allow another attempt.
1170 dev[1].scan(freq="2412")
1171 bss = dev[1].get_bss(apdev[0]['bssid'])
1172 if "[WPS-AUTH]" not in bss['flags']:
1173 raise Exception("WPS-AUTH flag missing")
1174
1175 logger.info("Stop ER")
1176 dev[0].dump_monitor()
1177 dev[0].request("WPS_ER_STOP")
1178 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"])
1179 if ev is None:
1180 raise Exception("WPS ER unsubscription timed out")
1181 # It takes some time for the UPnP UNSUBSCRIBE command to go through, so wait
1182 # a bit before verifying that the scan results have changed.
1183 time.sleep(0.2)
1184
1185 for i in range(0, 10):
1186 dev[1].request("BSS_FLUSH 0")
1187 dev[1].scan(freq="2412", only_new=True)
1188 bss = dev[1].get_bss(apdev[0]['bssid'])
1189 if bss and 'flags' in bss and "[WPS-AUTH]" not in bss['flags']:
1190 break
1191 logger.debug("WPS-AUTH flag was still in place - wait a bit longer")
1192 time.sleep(0.1)
1193 if "[WPS-AUTH]" in bss['flags']:
1194 raise Exception("WPS-AUTH flag not removed")
1195
1196 def test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1197 """WPS ER adding a new enrollee identified by UUID"""
1198 try:
1199 _test_ap_wps_er_add_enrollee_uuid(dev, apdev)
1200 finally:
1201 dev[0].request("WPS_ER_STOP")
1202
1203 def _test_ap_wps_er_add_enrollee_uuid(dev, apdev):
1204 ssid = "wps-er-add-enrollee"
1205 ap_pin = "12345670"
1206 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1207 hostapd.add_ap(apdev[0],
1208 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1209 "wpa_passphrase": "12345678", "wpa": "2",
1210 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1211 "device_name": "Wireless AP", "manufacturer": "Company",
1212 "model_name": "WAP", "model_number": "123",
1213 "serial_number": "12345", "device_type": "6-0050F204-1",
1214 "os_version": "01020300",
1215 "config_methods": "label push_button",
1216 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1217 logger.info("WPS configuration step")
1218 dev[0].flush_scan_cache()
1219 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1220 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1221
1222 logger.info("Start ER")
1223 dev[0].request("WPS_ER_START ifname=lo")
1224 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1225 if ev is None:
1226 raise Exception("AP discovery timed out")
1227 if ap_uuid not in ev:
1228 raise Exception("Expected AP UUID not found")
1229
1230 logger.info("Learn AP configuration through UPnP")
1231 dev[0].dump_monitor()
1232 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1233 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1234 if ev is None:
1235 raise Exception("AP learn timed out")
1236 if ap_uuid not in ev:
1237 raise Exception("Expected AP UUID not in settings")
1238 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1239 if ev is None:
1240 raise Exception("WPS-FAIL after AP learn timed out")
1241 time.sleep(0.1)
1242
1243 logger.info("Add a specific Enrollee using ER (PBC/UUID)")
1244 addr1 = dev[1].p2p_interface_addr()
1245 dev[0].dump_monitor()
1246 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1247 dev[1].dump_monitor()
1248 dev[1].request("WPS_PBC %s" % apdev[0]['bssid'])
1249 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1250 if ev is None:
1251 raise Exception("Enrollee not seen")
1252 if addr1 not in ev:
1253 raise Exception("Unexpected Enrollee MAC address")
1254 uuid = ev.split(' ')[1]
1255 dev[0].request("WPS_ER_PBC " + uuid)
1256 dev[1].wait_connected(timeout=30)
1257 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1258 if ev is None:
1259 raise Exception("WPS ER did not report success")
1260
1261 logger.info("Add a specific Enrollee using ER (PIN/UUID)")
1262 pin = dev[2].wps_read_pin()
1263 addr2 = dev[2].p2p_interface_addr()
1264 dev[0].dump_monitor()
1265 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1266 dev[2].dump_monitor()
1267 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1268 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
1269 if ev is None:
1270 raise Exception("Enrollee not seen")
1271 if addr2 not in ev:
1272 raise Exception("Unexpected Enrollee MAC address")
1273 uuid = ev.split(' ')[1]
1274 dev[0].request("WPS_ER_PIN " + uuid + " " + pin)
1275 dev[2].wait_connected(timeout=30)
1276 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1277 if ev is None:
1278 raise Exception("WPS ER did not report success")
1279
1280 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-REMOVE"], timeout=15)
1281 if ev is None:
1282 raise Exception("No Enrollee STA entry timeout seen")
1283
1284 logger.info("Stop ER")
1285 dev[0].dump_monitor()
1286 dev[0].request("WPS_ER_STOP")
1287
1288 def test_ap_wps_er_multi_add_enrollee(dev, apdev):
1289 """Multiple WPS ERs adding a new enrollee using PIN"""
1290 try:
1291 _test_ap_wps_er_multi_add_enrollee(dev, apdev)
1292 finally:
1293 for i in range(2):
1294 dev[i].request("WPS_ER_STOP")
1295
1296 def _test_ap_wps_er_multi_add_enrollee(dev, apdev):
1297 ssid = "wps-er-add-enrollee"
1298 ap_pin = "12345670"
1299 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1300 hostapd.add_ap(apdev[0],
1301 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1302 "wpa_passphrase": "12345678", "wpa": "2",
1303 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1304 "device_name": "Wireless AP", "manufacturer": "Company",
1305 "model_name": "WAP", "model_number": "123",
1306 "serial_number": "12345", "device_type": "6-0050F204-1",
1307 "os_version": "01020300",
1308 'friendly_name': "WPS AP",
1309 "config_methods": "label push_button",
1310 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1311
1312 for i in range(2):
1313 dev[i].flush_scan_cache()
1314 dev[i].scan_for_bss(apdev[0]['bssid'], freq=2412)
1315 dev[i].wps_reg(apdev[0]['bssid'], ap_pin)
1316 for i in range(2):
1317 dev[i].request("WPS_ER_START ifname=lo")
1318 for i in range(2):
1319 ev = dev[i].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1320 if ev is None:
1321 raise Exception("AP discovery timed out")
1322 dev[i].dump_monitor()
1323 for i in range(2):
1324 dev[i].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1325 for i in range(2):
1326 ev = dev[i].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1327 if ev is None:
1328 raise Exception("AP learn timed out")
1329 ev = dev[i].wait_event(["WPS-FAIL"], timeout=15)
1330 if ev is None:
1331 raise Exception("WPS-FAIL after AP learn timed out")
1332
1333 time.sleep(0.1)
1334
1335 pin = dev[2].wps_read_pin()
1336 addr = dev[2].own_addr()
1337 dev[0].dump_monitor()
1338 dev[0].request("WPS_ER_PIN any " + pin + " " + addr)
1339 dev[1].dump_monitor()
1340 dev[1].request("WPS_ER_PIN any " + pin + " " + addr)
1341
1342 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
1343 dev[2].dump_monitor()
1344 dev[2].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1345 ev = dev[2].wait_event(["WPS-SUCCESS"], timeout=30)
1346 if ev is None:
1347 raise Exception("Enrollee did not report success")
1348 dev[2].wait_connected(timeout=15)
1349
1350 def test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1351 """WPS ER connected to AP and adding a new enrollee using PBC"""
1352 try:
1353 _test_ap_wps_er_add_enrollee_pbc(dev, apdev)
1354 finally:
1355 dev[0].request("WPS_ER_STOP")
1356
1357 def _test_ap_wps_er_add_enrollee_pbc(dev, apdev):
1358 ssid = "wps-er-add-enrollee-pbc"
1359 ap_pin = "12345670"
1360 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1361 hostapd.add_ap(apdev[0],
1362 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1363 "wpa_passphrase": "12345678", "wpa": "2",
1364 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1365 "device_name": "Wireless AP", "manufacturer": "Company",
1366 "model_name": "WAP", "model_number": "123",
1367 "serial_number": "12345", "device_type": "6-0050F204-1",
1368 "os_version": "01020300",
1369 "config_methods": "label push_button",
1370 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1371 logger.info("Learn AP configuration")
1372 dev[0].flush_scan_cache()
1373 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1374 dev[0].dump_monitor()
1375 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1376 status = dev[0].get_status()
1377 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1378 raise Exception("Not fully connected")
1379
1380 logger.info("Start ER")
1381 dev[0].request("WPS_ER_START ifname=lo")
1382 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1383 if ev is None:
1384 raise Exception("AP discovery timed out")
1385 if ap_uuid not in ev:
1386 raise Exception("Expected AP UUID not found")
1387
1388 enrollee = dev[1].p2p_interface_addr()
1389
1390 if "FAIL-UNKNOWN-UUID" not in dev[0].request("WPS_ER_PBC " + enrollee):
1391 raise Exception("Unknown UUID not reported")
1392
1393 logger.info("Add Enrollee using ER and PBC")
1394 dev[0].dump_monitor()
1395 dev[1].dump_monitor()
1396 dev[1].request("WPS_PBC")
1397
1398 for i in range(0, 2):
1399 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1400 if ev is None:
1401 raise Exception("Enrollee discovery timed out")
1402 if enrollee in ev:
1403 break
1404 if i == 1:
1405 raise Exception("Expected Enrollee not found")
1406 if "FAIL-NO-AP-SETTINGS" not in dev[0].request("WPS_ER_PBC " + enrollee):
1407 raise Exception("Unknown UUID not reported")
1408 logger.info("Use learned network configuration on ER")
1409 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1410 if "OK" not in dev[0].request("WPS_ER_PBC " + enrollee):
1411 raise Exception("WPS_ER_PBC failed")
1412
1413 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=15)
1414 if ev is None:
1415 raise Exception("Enrollee did not report success")
1416 dev[1].wait_connected(timeout=15)
1417 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1418 if ev is None:
1419 raise Exception("WPS ER did not report success")
1420 hwsim_utils.test_connectivity_sta(dev[0], dev[1])
1421
1422 def test_ap_wps_er_pbc_overlap(dev, apdev):
1423 """WPS ER connected to AP and PBC session overlap"""
1424 try:
1425 _test_ap_wps_er_pbc_overlap(dev, apdev)
1426 finally:
1427 dev[0].request("WPS_ER_STOP")
1428
1429 def _test_ap_wps_er_pbc_overlap(dev, apdev):
1430 ssid = "wps-er-add-enrollee-pbc"
1431 ap_pin = "12345670"
1432 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1433 hostapd.add_ap(apdev[0],
1434 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1435 "wpa_passphrase": "12345678", "wpa": "2",
1436 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1437 "device_name": "Wireless AP", "manufacturer": "Company",
1438 "model_name": "WAP", "model_number": "123",
1439 "serial_number": "12345", "device_type": "6-0050F204-1",
1440 "os_version": "01020300",
1441 "config_methods": "label push_button",
1442 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1443 dev[0].flush_scan_cache()
1444 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1445 dev[0].dump_monitor()
1446 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1447
1448 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412")
1449 dev[2].scan_for_bss(apdev[0]['bssid'], freq="2412")
1450 # avoid leaving dev 1 or 2 as the last Probe Request to the AP
1451 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)
1452
1453 dev[0].dump_monitor()
1454 dev[0].request("WPS_ER_START ifname=lo")
1455
1456 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1457 if ev is None:
1458 raise Exception("AP discovery timed out")
1459 if ap_uuid not in ev:
1460 raise Exception("Expected AP UUID not found")
1461
1462 # verify BSSID selection of the AP instead of UUID
1463 if "FAIL" in dev[0].request("WPS_ER_SET_CONFIG " + apdev[0]['bssid'] + " 0"):
1464 raise Exception("Could not select AP based on BSSID")
1465
1466 dev[0].dump_monitor()
1467 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
1468 dev[2].request("WPS_PBC " + apdev[0]['bssid'])
1469 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1470 if ev is None:
1471 raise Exception("PBC scan failed")
1472 ev = dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
1473 if ev is None:
1474 raise Exception("PBC scan failed")
1475 found1 = False
1476 found2 = False
1477 addr1 = dev[1].own_addr()
1478 addr2 = dev[2].own_addr()
1479 for i in range(3):
1480 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
1481 if ev is None:
1482 raise Exception("Enrollee discovery timed out")
1483 if addr1 in ev:
1484 found1 = True
1485 if found2:
1486 break
1487 if addr2 in ev:
1488 found2 = True
1489 if found1:
1490 break
1491 if dev[0].request("WPS_ER_PBC " + ap_uuid) != "FAIL-PBC-OVERLAP\n":
1492 raise Exception("PBC overlap not reported")
1493 dev[1].request("WPS_CANCEL")
1494 dev[2].request("WPS_CANCEL")
1495 if dev[0].request("WPS_ER_PBC foo") != "FAIL\n":
1496 raise Exception("Invalid WPS_ER_PBC accepted")
1497
1498 def test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1499 """WPS v1.0 ER connected to AP and adding a new enrollee using PIN"""
1500 try:
1501 _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev)
1502 finally:
1503 dev[0].request("WPS_ER_STOP")
1504
1505 def _test_ap_wps_er_v10_add_enrollee_pin(dev, apdev):
1506 ssid = "wps-er-add-enrollee-pbc"
1507 ap_pin = "12345670"
1508 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1509 hostapd.add_ap(apdev[0],
1510 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1511 "wpa_passphrase": "12345678", "wpa": "2",
1512 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1513 "device_name": "Wireless AP", "manufacturer": "Company",
1514 "model_name": "WAP", "model_number": "123",
1515 "serial_number": "12345", "device_type": "6-0050F204-1",
1516 "os_version": "01020300",
1517 "config_methods": "label push_button",
1518 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1519 logger.info("Learn AP configuration")
1520 dev[0].request("SET wps_version_number 0x10")
1521 dev[0].flush_scan_cache()
1522 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1523 dev[0].dump_monitor()
1524 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1525 status = dev[0].get_status()
1526 if status['wpa_state'] != 'COMPLETED' or status['bssid'] != apdev[0]['bssid']:
1527 raise Exception("Not fully connected")
1528
1529 logger.info("Start ER")
1530 dev[0].request("WPS_ER_START ifname=lo")
1531 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1532 if ev is None:
1533 raise Exception("AP discovery timed out")
1534 if ap_uuid not in ev:
1535 raise Exception("Expected AP UUID not found")
1536
1537 logger.info("Use learned network configuration on ER")
1538 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " 0")
1539
1540 logger.info("Add Enrollee using ER and PIN")
1541 enrollee = dev[1].p2p_interface_addr()
1542 pin = dev[1].wps_read_pin()
1543 dev[0].dump_monitor()
1544 dev[0].request("WPS_ER_PIN any " + pin + " " + enrollee)
1545 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1546 dev[1].dump_monitor()
1547 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1548 dev[1].wait_connected(timeout=30)
1549 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1550 if ev is None:
1551 raise Exception("WPS ER did not report success")
1552
1553 @remote_compatible
1554 def test_ap_wps_er_config_ap(dev, apdev):
1555 """WPS ER configuring AP over UPnP"""
1556 try:
1557 _test_ap_wps_er_config_ap(dev, apdev)
1558 finally:
1559 dev[0].request("WPS_ER_STOP")
1560
1561 def _test_ap_wps_er_config_ap(dev, apdev):
1562 ssid = "wps-er-ap-config"
1563 ap_pin = "12345670"
1564 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1565 hostapd.add_ap(apdev[0],
1566 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1567 "wpa_passphrase": "12345678", "wpa": "2",
1568 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1569 "device_name": "Wireless AP", "manufacturer": "Company",
1570 "model_name": "WAP", "model_number": "123",
1571 "serial_number": "12345", "device_type": "6-0050F204-1",
1572 "os_version": "01020300",
1573 "config_methods": "label push_button",
1574 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
1575
1576 logger.info("Connect ER to the AP")
1577 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
1578
1579 logger.info("WPS configuration step")
1580 dev[0].request("WPS_ER_START ifname=lo")
1581 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1582 if ev is None:
1583 raise Exception("AP discovery timed out")
1584 if ap_uuid not in ev:
1585 raise Exception("Expected AP UUID not found")
1586 new_passphrase = "1234567890"
1587 dev[0].request("WPS_ER_CONFIG " + apdev[0]['bssid'] + " " + ap_pin + " " +
1588 binascii.hexlify(ssid.encode()).decode() + " WPA2PSK CCMP " +
1589 binascii.hexlify(new_passphrase.encode()).decode())
1590 ev = dev[0].wait_event(["WPS-SUCCESS"])
1591 if ev is None:
1592 raise Exception("WPS ER configuration operation timed out")
1593 dev[0].wait_disconnected(timeout=10)
1594 dev[0].connect(ssid, psk="1234567890", scan_freq="2412")
1595
1596 logger.info("WPS ER restart")
1597 dev[0].request("WPS_ER_START")
1598 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1599 if ev is None:
1600 raise Exception("AP discovery timed out on ER restart")
1601 if ap_uuid not in ev:
1602 raise Exception("Expected AP UUID not found on ER restart")
1603 if "OK" not in dev[0].request("WPS_ER_STOP"):
1604 raise Exception("WPS_ER_STOP failed")
1605 if "OK" not in dev[0].request("WPS_ER_STOP"):
1606 raise Exception("WPS_ER_STOP failed")
1607
1608 @remote_compatible
1609 def test_ap_wps_er_cache_ap_settings(dev, apdev):
1610 """WPS ER caching AP settings"""
1611 try:
1612 _test_ap_wps_er_cache_ap_settings(dev, apdev)
1613 finally:
1614 dev[0].request("WPS_ER_STOP")
1615
1616 def _test_ap_wps_er_cache_ap_settings(dev, apdev):
1617 ssid = "wps-er-add-enrollee"
1618 ap_pin = "12345670"
1619 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1620 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1621 "wpa_passphrase": "12345678", "wpa": "2",
1622 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1623 "device_name": "Wireless AP", "manufacturer": "Company",
1624 "model_name": "WAP", "model_number": "123",
1625 "serial_number": "12345", "device_type": "6-0050F204-1",
1626 "os_version": "01020300",
1627 "config_methods": "label push_button",
1628 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1629 hapd = hostapd.add_ap(apdev[0], params)
1630 dev[0].flush_scan_cache()
1631 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1632 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1633 id = int(dev[0].list_networks()[0]['id'])
1634 dev[0].set_network(id, "scan_freq", "2412")
1635
1636 dev[0].request("WPS_ER_START ifname=lo")
1637 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1638 if ev is None:
1639 raise Exception("AP discovery timed out")
1640 if ap_uuid not in ev:
1641 raise Exception("Expected AP UUID not found")
1642
1643 dev[0].dump_monitor()
1644 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1645 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1646 if ev is None:
1647 raise Exception("AP learn timed out")
1648 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1649 if ev is None:
1650 raise Exception("WPS-FAIL after AP learn timed out")
1651 time.sleep(0.1)
1652
1653 hapd.disable()
1654
1655 for i in range(2):
1656 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE", "CTRL-EVENT-DISCONNECTED"],
1657 timeout=15)
1658 if ev is None:
1659 raise Exception("AP removal or disconnection timed out")
1660
1661 hapd = hostapd.add_ap(apdev[0], params)
1662 for i in range(2):
1663 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1664 timeout=15)
1665 if ev is None:
1666 raise Exception("AP discovery or connection timed out")
1667
1668 pin = dev[1].wps_read_pin()
1669 dev[0].dump_monitor()
1670 dev[0].request("WPS_ER_PIN any " + pin + " " + dev[1].p2p_interface_addr())
1671
1672 time.sleep(0.2)
1673
1674 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1675 dev[1].dump_monitor()
1676 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1677 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
1678 if ev is None:
1679 raise Exception("Enrollee did not report success")
1680 dev[1].wait_connected(timeout=15)
1681 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
1682 if ev is None:
1683 raise Exception("WPS ER did not report success")
1684
1685 dev[0].dump_monitor()
1686 dev[0].request("WPS_ER_STOP")
1687
1688 def test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1689 """WPS ER caching AP settings (OOM)"""
1690 try:
1691 _test_ap_wps_er_cache_ap_settings_oom(dev, apdev)
1692 finally:
1693 dev[0].request("WPS_ER_STOP")
1694
1695 def _test_ap_wps_er_cache_ap_settings_oom(dev, apdev):
1696 ssid = "wps-er-add-enrollee"
1697 ap_pin = "12345670"
1698 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1699 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1700 "wpa_passphrase": "12345678", "wpa": "2",
1701 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1702 "device_name": "Wireless AP", "manufacturer": "Company",
1703 "model_name": "WAP", "model_number": "123",
1704 "serial_number": "12345", "device_type": "6-0050F204-1",
1705 "os_version": "01020300",
1706 "config_methods": "label push_button",
1707 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1708 hapd = hostapd.add_ap(apdev[0], params)
1709 dev[0].flush_scan_cache()
1710 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1711 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1712 id = int(dev[0].list_networks()[0]['id'])
1713 dev[0].set_network(id, "scan_freq", "2412")
1714
1715 dev[0].request("WPS_ER_START ifname=lo")
1716 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1717 if ev is None:
1718 raise Exception("AP discovery timed out")
1719 if ap_uuid not in ev:
1720 raise Exception("Expected AP UUID not found")
1721
1722 dev[0].dump_monitor()
1723 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1724 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1725 if ev is None:
1726 raise Exception("AP learn timed out")
1727 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1728 if ev is None:
1729 raise Exception("WPS-FAIL after AP learn timed out")
1730 time.sleep(0.1)
1731
1732 with alloc_fail(dev[0], 1, "=wps_er_ap_use_cached_settings"):
1733 hapd.disable()
1734
1735 for i in range(2):
1736 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1737 "CTRL-EVENT-DISCONNECTED"],
1738 timeout=15)
1739 if ev is None:
1740 raise Exception("AP removal or disconnection timed out")
1741
1742 hapd = hostapd.add_ap(apdev[0], params)
1743 for i in range(2):
1744 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1745 timeout=15)
1746 if ev is None:
1747 raise Exception("AP discovery or connection timed out")
1748
1749 dev[0].request("WPS_ER_STOP")
1750
1751 def test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1752 """WPS ER caching AP settings (OOM 2)"""
1753 try:
1754 _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev)
1755 finally:
1756 dev[0].request("WPS_ER_STOP")
1757
1758 def _test_ap_wps_er_cache_ap_settings_oom2(dev, apdev):
1759 ssid = "wps-er-add-enrollee"
1760 ap_pin = "12345670"
1761 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1762 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1763 "wpa_passphrase": "12345678", "wpa": "2",
1764 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1765 "device_name": "Wireless AP", "manufacturer": "Company",
1766 "model_name": "WAP", "model_number": "123",
1767 "serial_number": "12345", "device_type": "6-0050F204-1",
1768 "os_version": "01020300",
1769 "config_methods": "label push_button",
1770 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1771 hapd = hostapd.add_ap(apdev[0], params)
1772 dev[0].flush_scan_cache()
1773 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1774 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1775 id = int(dev[0].list_networks()[0]['id'])
1776 dev[0].set_network(id, "scan_freq", "2412")
1777
1778 dev[0].request("WPS_ER_START ifname=lo")
1779 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
1780 if ev is None:
1781 raise Exception("AP discovery timed out")
1782 if ap_uuid not in ev:
1783 raise Exception("Expected AP UUID not found")
1784
1785 dev[0].dump_monitor()
1786 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1787 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1788 if ev is None:
1789 raise Exception("AP learn timed out")
1790 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1791 if ev is None:
1792 raise Exception("WPS-FAIL after AP learn timed out")
1793 time.sleep(0.1)
1794
1795 with alloc_fail(dev[0], 1, "=wps_er_ap_cache_settings"):
1796 hapd.disable()
1797
1798 for i in range(2):
1799 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE",
1800 "CTRL-EVENT-DISCONNECTED"],
1801 timeout=15)
1802 if ev is None:
1803 raise Exception("AP removal or disconnection timed out")
1804
1805 hapd = hostapd.add_ap(apdev[0], params)
1806 for i in range(2):
1807 ev = dev[0].wait_event(["WPS-ER-AP-ADD", "CTRL-EVENT-CONNECTED"],
1808 timeout=15)
1809 if ev is None:
1810 raise Exception("AP discovery or connection timed out")
1811
1812 dev[0].request("WPS_ER_STOP")
1813
1814 def test_ap_wps_er_subscribe_oom(dev, apdev):
1815 """WPS ER subscribe OOM"""
1816 try:
1817 _test_ap_wps_er_subscribe_oom(dev, apdev)
1818 finally:
1819 dev[0].request("WPS_ER_STOP")
1820
1821 def _test_ap_wps_er_subscribe_oom(dev, apdev):
1822 ssid = "wps-er-add-enrollee"
1823 ap_pin = "12345670"
1824 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1825 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1826 "wpa_passphrase": "12345678", "wpa": "2",
1827 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1828 "device_name": "Wireless AP", "manufacturer": "Company",
1829 "model_name": "WAP", "model_number": "123",
1830 "serial_number": "12345", "device_type": "6-0050F204-1",
1831 "os_version": "01020300",
1832 "config_methods": "label push_button",
1833 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1834 hapd = hostapd.add_ap(apdev[0], params)
1835 dev[0].flush_scan_cache()
1836 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1837 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1838 id = int(dev[0].list_networks()[0]['id'])
1839 dev[0].set_network(id, "scan_freq", "2412")
1840
1841 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_subscribe"):
1842 dev[0].request("WPS_ER_START ifname=lo")
1843 for i in range(50):
1844 res = dev[0].request("GET_ALLOC_FAIL")
1845 if res.startswith("0:"):
1846 break
1847 time.sleep(0.1)
1848 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=0)
1849 if ev:
1850 raise Exception("Unexpected AP discovery during OOM")
1851
1852 dev[0].request("WPS_ER_STOP")
1853
1854 def test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1855 """WPS ER SetSelectedRegistrar OOM"""
1856 try:
1857 _test_ap_wps_er_set_sel_reg_oom(dev, apdev)
1858 finally:
1859 dev[0].request("WPS_ER_STOP")
1860
1861 def _test_ap_wps_er_set_sel_reg_oom(dev, apdev):
1862 ssid = "wps-er-add-enrollee"
1863 ap_pin = "12345670"
1864 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1865 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1866 "wpa_passphrase": "12345678", "wpa": "2",
1867 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1868 "device_name": "Wireless AP", "manufacturer": "Company",
1869 "model_name": "WAP", "model_number": "123",
1870 "serial_number": "12345", "device_type": "6-0050F204-1",
1871 "os_version": "01020300",
1872 "config_methods": "label push_button",
1873 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1874 hapd = hostapd.add_ap(apdev[0], params)
1875 dev[0].flush_scan_cache()
1876 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1877 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1878
1879 dev[0].request("WPS_ER_START ifname=lo")
1880 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1881 if ev is None:
1882 raise Exception("AP not discovered")
1883
1884 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1885 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
1886 if ev is None:
1887 raise Exception("AP learn timed out")
1888 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
1889 if ev is None:
1890 raise Exception("WPS-FAIL timed out")
1891 time.sleep(0.1)
1892
1893 for func in ["http_client_url_parse;wps_er_send_set_sel_reg",
1894 "wps_er_soap_hdr;wps_er_send_set_sel_reg",
1895 "http_client_addr;wps_er_send_set_sel_reg",
1896 "wpabuf_alloc;wps_er_set_sel_reg"]:
1897 with alloc_fail(dev[0], 1, func):
1898 if "OK" not in dev[0].request("WPS_ER_PBC " + ap_uuid):
1899 raise Exception("WPS_ER_PBC failed")
1900 ev = dev[0].wait_event(["WPS-PBC-ACTIVE"], timeout=3)
1901 if ev is None:
1902 raise Exception("WPS-PBC-ACTIVE not seen")
1903
1904 dev[0].request("WPS_ER_STOP")
1905
1906 @remote_compatible
1907 def test_ap_wps_er_learn_oom(dev, apdev):
1908 """WPS ER learn OOM"""
1909 try:
1910 _test_ap_wps_er_learn_oom(dev, apdev)
1911 finally:
1912 dev[0].request("WPS_ER_STOP")
1913
1914 def _test_ap_wps_er_learn_oom(dev, apdev):
1915 ssid = "wps-er-add-enrollee"
1916 ap_pin = "12345670"
1917 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
1918 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1919 "wpa_passphrase": "12345678", "wpa": "2",
1920 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1921 "device_name": "Wireless AP", "manufacturer": "Company",
1922 "model_name": "WAP", "model_number": "123",
1923 "serial_number": "12345", "device_type": "6-0050F204-1",
1924 "os_version": "01020300",
1925 "config_methods": "label push_button",
1926 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
1927 hapd = hostapd.add_ap(apdev[0], params)
1928 dev[0].flush_scan_cache()
1929 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1930 dev[0].wps_reg(apdev[0]['bssid'], ap_pin)
1931
1932 dev[0].request("WPS_ER_START ifname=lo")
1933 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
1934 if ev is None:
1935 raise Exception("AP not discovered")
1936
1937 for func in ["wps_er_http_put_message_cb",
1938 "xml_get_base64_item;wps_er_http_put_message_cb",
1939 "http_client_url_parse;wps_er_ap_put_message",
1940 "wps_er_soap_hdr;wps_er_ap_put_message",
1941 "http_client_addr;wps_er_ap_put_message"]:
1942 with alloc_fail(dev[0], 1, func):
1943 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1944 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=1)
1945 if ev is not None:
1946 raise Exception("AP learn succeeded during OOM")
1947
1948 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
1949 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=10)
1950 if ev is None:
1951 raise Exception("AP learn did not succeed")
1952
1953 if "FAIL" not in dev[0].request("WPS_ER_LEARN 00000000-9e5c-4e73-bd82-f89cbcd10d7e " + ap_pin):
1954 raise Exception("WPS_ER_LEARN for unknown AP accepted")
1955
1956 dev[0].request("WPS_ER_STOP")
1957
1958 def test_ap_wps_fragmentation(dev, apdev):
1959 """WPS with fragmentation in EAP-WSC and mixed mode WPA+WPA2"""
1960 ssid = "test-wps-fragmentation"
1961 appin = "12345670"
1962 hapd = hostapd.add_ap(apdev[0],
1963 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
1964 "wpa_passphrase": "12345678", "wpa": "3",
1965 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
1966 "wpa_pairwise": "TKIP", "ap_pin": appin,
1967 "fragment_size": "50"})
1968 logger.info("WPS provisioning step (PBC)")
1969 hapd.request("WPS_PBC")
1970 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
1971 dev[0].dump_monitor()
1972 dev[0].request("SET wps_fragment_size 50")
1973 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
1974 dev[0].wait_connected(timeout=30)
1975 status = dev[0].get_status()
1976 if status['wpa_state'] != 'COMPLETED':
1977 raise Exception("Not fully connected")
1978 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1979 raise Exception("Unexpected encryption configuration")
1980 if status['key_mgmt'] != 'WPA2-PSK':
1981 raise Exception("Unexpected key_mgmt")
1982
1983 logger.info("WPS provisioning step (PIN)")
1984 pin = dev[1].wps_read_pin()
1985 hapd.request("WPS_PIN any " + pin)
1986 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
1987 dev[1].request("SET wps_fragment_size 50")
1988 dev[1].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
1989 dev[1].wait_connected(timeout=30)
1990 status = dev[1].get_status()
1991 if status['wpa_state'] != 'COMPLETED':
1992 raise Exception("Not fully connected")
1993 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
1994 raise Exception("Unexpected encryption configuration")
1995 if status['key_mgmt'] != 'WPA2-PSK':
1996 raise Exception("Unexpected key_mgmt")
1997
1998 logger.info("WPS connection as registrar")
1999 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2000 dev[2].request("SET wps_fragment_size 50")
2001 dev[2].wps_reg(apdev[0]['bssid'], appin)
2002 status = dev[2].get_status()
2003 if status['wpa_state'] != 'COMPLETED':
2004 raise Exception("Not fully connected")
2005 if status['pairwise_cipher'] != 'CCMP' or status['group_cipher'] != 'TKIP':
2006 raise Exception("Unexpected encryption configuration")
2007 if status['key_mgmt'] != 'WPA2-PSK':
2008 raise Exception("Unexpected key_mgmt")
2009
2010 @remote_compatible
2011 def test_ap_wps_new_version_sta(dev, apdev):
2012 """WPS compatibility with new version number on the station"""
2013 ssid = "test-wps-ver"
2014 hapd = hostapd.add_ap(apdev[0],
2015 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2016 "wpa_passphrase": "12345678", "wpa": "2",
2017 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2018 logger.info("WPS provisioning step")
2019 hapd.request("WPS_PBC")
2020 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2021 dev[0].dump_monitor()
2022 dev[0].request("SET wps_version_number 0x43")
2023 dev[0].request("SET wps_vendor_ext_m1 000137100100020001")
2024 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2025 dev[0].wait_connected(timeout=30)
2026
2027 @remote_compatible
2028 def test_ap_wps_new_version_ap(dev, apdev):
2029 """WPS compatibility with new version number on the AP"""
2030 ssid = "test-wps-ver"
2031 hapd = hostapd.add_ap(apdev[0],
2032 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2033 "wpa_passphrase": "12345678", "wpa": "2",
2034 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2035 logger.info("WPS provisioning step")
2036 if "FAIL" in hapd.request("SET wps_version_number 0x43"):
2037 raise Exception("Failed to enable test functionality")
2038 hapd.request("WPS_PBC")
2039 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2040 dev[0].dump_monitor()
2041 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2042 dev[0].wait_connected(timeout=30)
2043 hapd.request("SET wps_version_number 0x20")
2044
2045 @remote_compatible
2046 def test_ap_wps_check_pin(dev, apdev):
2047 """Verify PIN checking through control interface"""
2048 hapd = hostapd.add_ap(apdev[0],
2049 {"ssid": "wps", "eap_server": "1", "wps_state": "2",
2050 "wpa_passphrase": "12345678", "wpa": "2",
2051 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2052 for t in [("12345670", "12345670"),
2053 ("12345678", "FAIL-CHECKSUM"),
2054 ("12345", "FAIL"),
2055 ("123456789", "FAIL"),
2056 ("1234-5670", "12345670"),
2057 ("1234 5670", "12345670"),
2058 ("1-2.3:4 5670", "12345670")]:
2059 res = hapd.request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2060 res2 = dev[0].request("WPS_CHECK_PIN " + t[0]).rstrip('\n')
2061 if res != res2:
2062 raise Exception("Unexpected difference in WPS_CHECK_PIN responses")
2063 if res != t[1]:
2064 raise Exception("Incorrect WPS_CHECK_PIN response {} (expected {})".format(res, t[1]))
2065
2066 if "FAIL" not in hapd.request("WPS_CHECK_PIN 12345"):
2067 raise Exception("Unexpected WPS_CHECK_PIN success")
2068 if "FAIL" not in hapd.request("WPS_CHECK_PIN 123456789"):
2069 raise Exception("Unexpected WPS_CHECK_PIN success")
2070
2071 for i in range(0, 10):
2072 pin = dev[0].request("WPS_PIN get")
2073 rpin = dev[0].request("WPS_CHECK_PIN " + pin).rstrip('\n')
2074 if pin != rpin:
2075 raise Exception("Random PIN validation failed for " + pin)
2076
2077 def test_ap_wps_pin_get_failure(dev, apdev):
2078 """PIN generation failure"""
2079 with fail_test(dev[0], 1,
2080 "os_get_random;wpa_supplicant_ctrl_iface_wps_pin"):
2081 if "FAIL" not in dev[0].request("WPS_PIN get"):
2082 raise Exception("WPS_PIN did not report failure")
2083
2084 def test_ap_wps_wep_config(dev, apdev):
2085 """WPS 2.0 AP rejecting WEP configuration"""
2086 ssid = "test-wps-config"
2087 appin = "12345670"
2088 hapd = hostapd.add_ap(apdev[0],
2089 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2090 "ap_pin": appin})
2091 dev[0].flush_scan_cache()
2092 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2093 dev[0].wps_reg(apdev[0]['bssid'], appin, "wps-new-ssid-wep", "OPEN", "WEP",
2094 "hello", no_wait=True)
2095 ev = hapd.wait_event(["WPS-FAIL"], timeout=15)
2096 if ev is None:
2097 raise Exception("WPS-FAIL timed out")
2098 if "reason=2" not in ev:
2099 raise Exception("Unexpected reason code in WPS-FAIL")
2100 status = hapd.request("WPS_GET_STATUS")
2101 if "Last WPS result: Failed" not in status:
2102 raise Exception("WPS failure result not shown correctly")
2103 if "Failure Reason: WEP Prohibited" not in status:
2104 raise Exception("Failure reason not reported correctly")
2105 if "Peer Address: " + dev[0].p2p_interface_addr() not in status:
2106 raise Exception("Peer address not shown correctly")
2107
2108 def test_ap_wps_wep_enroll(dev, apdev):
2109 """WPS 2.0 STA rejecting WEP configuration"""
2110 ssid = "test-wps-wep"
2111 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2112 "skip_cred_build": "1", "extra_cred": "wps-wep-cred"}
2113 hapd = hostapd.add_ap(apdev[0], params)
2114 hapd.request("WPS_PBC")
2115 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2116 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2117 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
2118 if ev is None:
2119 raise Exception("WPS-FAIL event timed out")
2120 if "msg=12" not in ev or "reason=2 (WEP Prohibited)" not in ev:
2121 raise Exception("Unexpected WPS-FAIL event: " + ev)
2122
2123 @remote_compatible
2124 def test_ap_wps_ie_fragmentation(dev, apdev):
2125 """WPS AP using fragmented WPS IE"""
2126 ssid = "test-wps-ie-fragmentation"
2127 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2128 "wpa_passphrase": "12345678", "wpa": "2",
2129 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2130 "device_name": "1234567890abcdef1234567890abcdef",
2131 "manufacturer": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
2132 "model_name": "1234567890abcdef1234567890abcdef",
2133 "model_number": "1234567890abcdef1234567890abcdef",
2134 "serial_number": "1234567890abcdef1234567890abcdef"}
2135 hapd = hostapd.add_ap(apdev[0], params)
2136 hapd.request("WPS_PBC")
2137 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2138 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2139 dev[0].wait_connected(timeout=30)
2140 bss = dev[0].get_bss(apdev[0]['bssid'])
2141 if "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
2142 logger.info("Device Name not received correctly")
2143 logger.info(bss)
2144 # This can fail if Probe Response frame is missed and Beacon frame was
2145 # used to fill in the BSS entry. This can happen, e.g., during heavy
2146 # load every now and then and is not really an error, so try to
2147 # workaround by runnign another scan.
2148 dev[0].scan(freq="2412", only_new=True)
2149 bss = dev[0].get_bss(apdev[0]['bssid'])
2150 if not bss or "wps_device_name" not in bss or bss['wps_device_name'] != "1234567890abcdef1234567890abcdef":
2151 logger.info(bss)
2152 raise Exception("Device Name not received correctly")
2153 if len(re.findall("dd..0050f204", bss['ie'])) != 2:
2154 raise Exception("Unexpected number of WPS IEs")
2155
2156 def get_psk(pskfile):
2157 psks = {}
2158 with open(pskfile, "r") as f:
2159 lines = f.read().splitlines()
2160 for l in lines:
2161 if l == "# WPA PSKs":
2162 continue
2163 (addr, psk) = l.split(' ')
2164 psks[addr] = psk
2165 return psks
2166
2167 def test_ap_wps_per_station_psk(dev, apdev):
2168 """WPS PBC provisioning with per-station PSK"""
2169 addr0 = dev[0].own_addr()
2170 addr1 = dev[1].own_addr()
2171 addr2 = dev[2].own_addr()
2172 ssid = "wps"
2173 appin = "12345670"
2174 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2175 try:
2176 os.remove(pskfile)
2177 except:
2178 pass
2179
2180 hapd = None
2181 try:
2182 with open(pskfile, "w") as f:
2183 f.write("# WPA PSKs\n")
2184
2185 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2186 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2187 "rsn_pairwise": "CCMP", "ap_pin": appin,
2188 "wpa_psk_file": pskfile}
2189 hapd = hostapd.add_ap(apdev[0], params)
2190
2191 logger.info("First enrollee")
2192 hapd.request("WPS_PBC")
2193 dev[0].flush_scan_cache()
2194 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2195 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2196 dev[0].wait_connected(timeout=30)
2197
2198 logger.info("Second enrollee")
2199 hapd.request("WPS_PBC")
2200 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2201 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2202 dev[1].wait_connected(timeout=30)
2203
2204 logger.info("External registrar")
2205 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2206 dev[2].wps_reg(apdev[0]['bssid'], appin)
2207
2208 logger.info("Verifying PSK results")
2209 psks = get_psk(pskfile)
2210 if addr0 not in psks:
2211 raise Exception("No PSK recorded for sta0")
2212 if addr1 not in psks:
2213 raise Exception("No PSK recorded for sta1")
2214 if addr2 not in psks:
2215 raise Exception("No PSK recorded for sta2")
2216 if psks[addr0] == psks[addr1]:
2217 raise Exception("Same PSK recorded for sta0 and sta1")
2218 if psks[addr0] == psks[addr2]:
2219 raise Exception("Same PSK recorded for sta0 and sta2")
2220 if psks[addr1] == psks[addr2]:
2221 raise Exception("Same PSK recorded for sta1 and sta2")
2222
2223 dev[0].request("REMOVE_NETWORK all")
2224 logger.info("Second external registrar")
2225 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2226 dev[0].wps_reg(apdev[0]['bssid'], appin)
2227 psks2 = get_psk(pskfile)
2228 if addr0 not in psks2:
2229 raise Exception("No PSK recorded for sta0(reg)")
2230 if psks[addr0] == psks2[addr0]:
2231 raise Exception("Same PSK recorded for sta0(enrollee) and sta0(reg)")
2232 finally:
2233 os.remove(pskfile)
2234 if hapd:
2235 dev[0].request("DISCONNECT")
2236 dev[1].request("DISCONNECT")
2237 dev[2].request("DISCONNECT")
2238 hapd.disable()
2239 dev[0].flush_scan_cache()
2240 dev[1].flush_scan_cache()
2241 dev[2].flush_scan_cache()
2242
2243 def test_ap_wps_per_station_psk_failure(dev, apdev):
2244 """WPS PBC provisioning with per-station PSK (file not writable)"""
2245 addr0 = dev[0].p2p_dev_addr()
2246 addr1 = dev[1].p2p_dev_addr()
2247 addr2 = dev[2].p2p_dev_addr()
2248 ssid = "wps"
2249 appin = "12345670"
2250 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
2251 try:
2252 os.remove(pskfile)
2253 except:
2254 pass
2255
2256 hapd = None
2257 try:
2258 with open(pskfile, "w") as f:
2259 f.write("# WPA PSKs\n")
2260
2261 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2262 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
2263 "rsn_pairwise": "CCMP", "ap_pin": appin,
2264 "wpa_psk_file": pskfile}
2265 hapd = hostapd.add_ap(apdev[0], params)
2266 if "FAIL" in hapd.request("SET wpa_psk_file /tmp/does/not/exists/ap_wps_per_enrollee_psk_failure.psk_file"):
2267 raise Exception("Failed to set wpa_psk_file")
2268
2269 logger.info("First enrollee")
2270 hapd.request("WPS_PBC")
2271 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
2272 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2273 dev[0].wait_connected(timeout=30)
2274
2275 logger.info("Second enrollee")
2276 hapd.request("WPS_PBC")
2277 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
2278 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
2279 dev[1].wait_connected(timeout=30)
2280
2281 logger.info("External registrar")
2282 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
2283 dev[2].wps_reg(apdev[0]['bssid'], appin)
2284
2285 logger.info("Verifying PSK results")
2286 psks = get_psk(pskfile)
2287 if len(psks) > 0:
2288 raise Exception("PSK recorded unexpectedly")
2289 finally:
2290 if hapd:
2291 for i in range(3):
2292 dev[i].request("DISCONNECT")
2293 hapd.disable()
2294 for i in range(3):
2295 dev[i].flush_scan_cache()
2296 os.remove(pskfile)
2297
2298 def test_ap_wps_pin_request_file(dev, apdev):
2299 """WPS PIN provisioning with configured AP"""
2300 ssid = "wps"
2301 pinfile = "/tmp/ap_wps_pin_request_file.log"
2302 if os.path.exists(pinfile):
2303 os.remove(pinfile)
2304 hapd = hostapd.add_ap(apdev[0],
2305 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2306 "wps_pin_requests": pinfile,
2307 "wpa_passphrase": "12345678", "wpa": "2",
2308 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
2309 uuid = dev[0].get_status_field("uuid")
2310 pin = dev[0].wps_read_pin()
2311 try:
2312 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2313 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
2314 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=15)
2315 if ev is None:
2316 raise Exception("PIN needed event not shown")
2317 if uuid not in ev:
2318 raise Exception("UUID mismatch")
2319 dev[0].request("WPS_CANCEL")
2320 success = False
2321 with open(pinfile, "r") as f:
2322 lines = f.readlines()
2323 for l in lines:
2324 if uuid in l:
2325 success = True
2326 break
2327 if not success:
2328 raise Exception("PIN request entry not in the log file")
2329 finally:
2330 try:
2331 os.remove(pinfile)
2332 except:
2333 pass
2334
2335 def test_ap_wps_auto_setup_with_config_file(dev, apdev):
2336 """WPS auto-setup with configuration file"""
2337 conffile = "/tmp/ap_wps_auto_setup_with_config_file.conf"
2338 ifname = apdev[0]['ifname']
2339 try:
2340 with open(conffile, "w") as f:
2341 f.write("driver=nl80211\n")
2342 f.write("hw_mode=g\n")
2343 f.write("channel=1\n")
2344 f.write("ieee80211n=1\n")
2345 f.write("interface=%s\n" % ifname)
2346 f.write("ctrl_interface=/var/run/hostapd\n")
2347 f.write("ssid=wps\n")
2348 f.write("eap_server=1\n")
2349 f.write("wps_state=1\n")
2350 hapd = hostapd.add_bss(apdev[0], ifname, conffile)
2351 hapd.request("WPS_PBC")
2352 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
2353 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
2354 dev[0].wait_connected(timeout=30)
2355 with open(conffile, "r") as f:
2356 lines = f.read().splitlines()
2357 vals = dict()
2358 for l in lines:
2359 try:
2360 [name, value] = l.split('=', 1)
2361 vals[name] = value
2362 except ValueError as e:
2363 if "# WPS configuration" in l:
2364 pass
2365 else:
2366 raise Exception("Unexpected configuration line: " + l)
2367 if vals['ieee80211n'] != '1' or vals['wps_state'] != '2' or "WPA-PSK" not in vals['wpa_key_mgmt']:
2368 raise Exception("Incorrect configuration: " + str(vals))
2369 finally:
2370 try:
2371 os.remove(conffile)
2372 except:
2373 pass
2374
2375 def test_ap_wps_pbc_timeout(dev, apdev, params):
2376 """wpa_supplicant PBC walk time and WPS ER SelReg timeout [long]"""
2377 if not params['long']:
2378 raise HwsimSkip("Skip test case with long duration due to --long not specified")
2379 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2380 hapd = add_ssdp_ap(apdev[0], ap_uuid)
2381
2382 location = ssdp_get_location(ap_uuid)
2383 urls = upnp_get_urls(location)
2384 eventurl = urlparse(urls['event_sub_url'])
2385 ctrlurl = urlparse(urls['control_url'])
2386
2387 url = urlparse(location)
2388 conn = HTTPConnection(url.netloc)
2389
2390 class WPSERHTTPServer(StreamRequestHandler):
2391 def handle(self):
2392 data = self.rfile.readline().strip()
2393 logger.debug(data)
2394 self.wfile.write(gen_wps_event())
2395
2396 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
2397 server.timeout = 1
2398
2399 headers = {"callback": '<http://127.0.0.1:12345/event>',
2400 "NT": "upnp:event",
2401 "timeout": "Second-1234"}
2402 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2403 resp = conn.getresponse()
2404 if resp.status != 200:
2405 raise Exception("Unexpected HTTP response: %d" % resp.status)
2406 sid = resp.getheader("sid")
2407 logger.debug("Subscription SID " + sid)
2408
2409 msg = '''<?xml version="1.0"?>
2410 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
2411 <s:Body>
2412 <u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
2413 <NewMessage>EEoAARAQQQABARASAAIAABBTAAIxSBBJAA4ANyoAASABBv///////xBIABA2LbR7pTpRkYj7
2414 VFi5hrLk
2415 </NewMessage>
2416 </u:SetSelectedRegistrar>
2417 </s:Body>
2418 </s:Envelope>'''
2419 headers = {"Content-type": 'text/xml; charset="utf-8"'}
2420 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
2421 conn.request("POST", ctrlurl.path, msg, headers)
2422 resp = conn.getresponse()
2423 if resp.status != 200:
2424 raise Exception("Unexpected HTTP response: %d" % resp.status)
2425
2426 server.handle_request()
2427
2428 logger.info("Start WPS_PBC and wait for PBC walk time expiration")
2429 if "OK" not in dev[0].request("WPS_PBC"):
2430 raise Exception("WPS_PBC failed")
2431
2432 start = os.times()[4]
2433
2434 server.handle_request()
2435 dev[1].request("BSS_FLUSH 0")
2436 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2437 only_new=True)
2438 bss = dev[1].get_bss(apdev[0]['bssid'])
2439 logger.debug("BSS: " + str(bss))
2440 if '[WPS-AUTH]' not in bss['flags']:
2441 raise Exception("WPS not indicated authorized")
2442
2443 server.handle_request()
2444
2445 wps_timeout_seen = False
2446
2447 while True:
2448 hapd.dump_monitor()
2449 dev[1].dump_monitor()
2450 if not wps_timeout_seen:
2451 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=0)
2452 if ev is not None:
2453 logger.info("PBC timeout seen")
2454 wps_timeout_seen = True
2455 else:
2456 dev[0].dump_monitor()
2457 now = os.times()[4]
2458 if now - start > 130:
2459 raise Exception("Selected registration information not removed")
2460 dev[1].request("BSS_FLUSH 0")
2461 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True,
2462 only_new=True)
2463 bss = dev[1].get_bss(apdev[0]['bssid'])
2464 logger.debug("BSS: " + str(bss))
2465 if '[WPS-AUTH]' not in bss['flags']:
2466 break
2467 server.handle_request()
2468
2469 server.server_close()
2470
2471 if wps_timeout_seen:
2472 return
2473
2474 now = os.times()[4]
2475 if now < start + 150:
2476 dur = start + 150 - now
2477 else:
2478 dur = 1
2479 logger.info("Continue waiting for PBC timeout (%d sec)" % dur)
2480 ev = dev[0].wait_event(["WPS-TIMEOUT"], timeout=dur)
2481 if ev is None:
2482 raise Exception("WPS-TIMEOUT not reported")
2483
2484 def add_ssdp_ap(ap, ap_uuid):
2485 ssid = "wps-ssdp"
2486 ap_pin = "12345670"
2487 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
2488 "wpa_passphrase": "12345678", "wpa": "2",
2489 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
2490 "device_name": "Wireless AP", "manufacturer": "Company",
2491 "model_name": "WAP", "model_number": "123",
2492 "serial_number": "12345", "device_type": "6-0050F204-1",
2493 "os_version": "01020300",
2494 "config_methods": "label push_button",
2495 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo",
2496 "friendly_name": "WPS Access Point",
2497 "manufacturer_url": "http://www.example.com/",
2498 "model_description": "Wireless Access Point",
2499 "model_url": "http://www.example.com/model/",
2500 "upc": "123456789012"}
2501 return hostapd.add_ap(ap, params)
2502
2503 def ssdp_send(msg, no_recv=False):
2504 socket.setdefaulttimeout(1)
2505 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2506 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2507 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2508 sock.bind(("127.0.0.1", 0))
2509 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2510 if no_recv:
2511 return None
2512 return sock.recv(1000).decode()
2513
2514 def ssdp_send_msearch(st, no_recv=False):
2515 msg = '\r\n'.join([
2516 'M-SEARCH * HTTP/1.1',
2517 'HOST: 239.255.255.250:1900',
2518 'MX: 1',
2519 'MAN: "ssdp:discover"',
2520 'ST: ' + st,
2521 '', ''])
2522 return ssdp_send(msg, no_recv=no_recv)
2523
2524 def test_ap_wps_ssdp_msearch(dev, apdev):
2525 """WPS AP and SSDP M-SEARCH messages"""
2526 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2527 add_ssdp_ap(apdev[0], ap_uuid)
2528
2529 msg = '\r\n'.join([
2530 'M-SEARCH * HTTP/1.1',
2531 'Host: 239.255.255.250:1900',
2532 'Mx: 1',
2533 'Man: "ssdp:discover"',
2534 'St: urn:schemas-wifialliance-org:device:WFADevice:1',
2535 '', ''])
2536 ssdp_send(msg)
2537
2538 msg = '\r\n'.join([
2539 'M-SEARCH * HTTP/1.1',
2540 'host:\t239.255.255.250:1900\t\t\t\t \t\t',
2541 'mx: \t1\t\t ',
2542 'man: \t \t "ssdp:discover" ',
2543 'st: urn:schemas-wifialliance-org:device:WFADevice:1\t\t',
2544 '', ''])
2545 ssdp_send(msg)
2546
2547 ssdp_send_msearch("ssdp:all")
2548 ssdp_send_msearch("upnp:rootdevice")
2549 ssdp_send_msearch("uuid:" + ap_uuid)
2550 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1")
2551 ssdp_send_msearch("urn:schemas-wifialliance-org:device:WFADevice:1")
2552
2553 msg = '\r\n'.join([
2554 'M-SEARCH * HTTP/1.1',
2555 'HOST:\t239.255.255.250:1900',
2556 'MAN: "ssdp:discover"',
2557 'MX: 130',
2558 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2559 '', ''])
2560 ssdp_send(msg, no_recv=True)
2561
2562 def test_ap_wps_ssdp_invalid_msearch(dev, apdev):
2563 """WPS AP and invalid SSDP M-SEARCH messages"""
2564 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2565 add_ssdp_ap(apdev[0], ap_uuid)
2566
2567 socket.setdefaulttimeout(1)
2568 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2569 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2570 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2571 sock.bind(("127.0.0.1", 0))
2572
2573 logger.debug("Missing MX")
2574 msg = '\r\n'.join([
2575 'M-SEARCH * HTTP/1.1',
2576 'HOST: 239.255.255.250:1900',
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("Negative MX")
2583 msg = '\r\n'.join([
2584 'M-SEARCH * HTTP/1.1',
2585 'HOST: 239.255.255.250:1900',
2586 'MX: -1',
2587 'MAN: "ssdp:discover"',
2588 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2589 '', ''])
2590 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2591
2592 logger.debug("Invalid MX")
2593 msg = '\r\n'.join([
2594 'M-SEARCH * HTTP/1.1',
2595 'HOST: 239.255.255.250:1900',
2596 'MX; 1',
2597 'MAN: "ssdp:discover"',
2598 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2599 '', ''])
2600 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2601
2602 logger.debug("Missing MAN")
2603 msg = '\r\n'.join([
2604 'M-SEARCH * HTTP/1.1',
2605 'HOST: 239.255.255.250:1900',
2606 'MX: 1',
2607 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2608 '', ''])
2609 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2610
2611 logger.debug("Invalid MAN")
2612 msg = '\r\n'.join([
2613 'M-SEARCH * HTTP/1.1',
2614 'HOST: 239.255.255.250:1900',
2615 'MX: 1',
2616 'MAN: foo',
2617 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2618 '', ''])
2619 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2620 msg = '\r\n'.join([
2621 'M-SEARCH * HTTP/1.1',
2622 'HOST: 239.255.255.250:1900',
2623 'MX: 1',
2624 'MAN; "ssdp:discover"',
2625 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2626 '', ''])
2627 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2628
2629 logger.debug("Missing HOST")
2630 msg = '\r\n'.join([
2631 'M-SEARCH * HTTP/1.1',
2632 'MAN: "ssdp:discover"',
2633 'MX: 1',
2634 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2635 '', ''])
2636 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2637
2638 logger.debug("Missing ST")
2639 msg = '\r\n'.join([
2640 'M-SEARCH * HTTP/1.1',
2641 'HOST: 239.255.255.250:1900',
2642 'MAN: "ssdp:discover"',
2643 'MX: 1',
2644 '', ''])
2645 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2646
2647 logger.debug("Mismatching ST")
2648 msg = '\r\n'.join([
2649 'M-SEARCH * HTTP/1.1',
2650 'HOST: 239.255.255.250:1900',
2651 'MAN: "ssdp:discover"',
2652 'MX: 1',
2653 'ST: uuid:16d5f8a9-4ee4-4f5e-81f9-cc6e2f47f42d',
2654 '', ''])
2655 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2656 msg = '\r\n'.join([
2657 'M-SEARCH * HTTP/1.1',
2658 'HOST: 239.255.255.250:1900',
2659 'MAN: "ssdp:discover"',
2660 'MX: 1',
2661 'ST: foo:bar',
2662 '', ''])
2663 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
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: foobar',
2670 '', ''])
2671 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2672
2673 logger.debug("Invalid ST")
2674 msg = '\r\n'.join([
2675 'M-SEARCH * HTTP/1.1',
2676 'HOST: 239.255.255.250:1900',
2677 'MAN: "ssdp:discover"',
2678 'MX: 1',
2679 'ST; urn:schemas-wifialliance-org:device:WFADevice:1',
2680 '', ''])
2681 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2682
2683 logger.debug("Invalid M-SEARCH")
2684 msg = '\r\n'.join([
2685 'M+SEARCH * HTTP/1.1',
2686 'HOST: 239.255.255.250:1900',
2687 'MAN: "ssdp:discover"',
2688 'MX: 1',
2689 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2690 '', ''])
2691 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2692 msg = '\r\n'.join([
2693 'M-SEARCH-* HTTP/1.1',
2694 'HOST: 239.255.255.250:1900',
2695 'MAN: "ssdp:discover"',
2696 'MX: 1',
2697 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2698 '', ''])
2699 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2700
2701 logger.debug("Invalid message format")
2702 sock.sendto(b"NOTIFY * HTTP/1.1", ("239.255.255.250", 1900))
2703 msg = '\r'.join([
2704 'M-SEARCH * HTTP/1.1',
2705 'HOST: 239.255.255.250:1900',
2706 'MAN: "ssdp:discover"',
2707 'MX: 1',
2708 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2709 '', ''])
2710 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2711
2712 try:
2713 r = sock.recv(1000)
2714 raise Exception("Unexpected M-SEARCH response: " + r)
2715 except socket.timeout:
2716 pass
2717
2718 logger.debug("Valid M-SEARCH")
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 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2727
2728 try:
2729 r = sock.recv(1000)
2730 pass
2731 except socket.timeout:
2732 raise Exception("No SSDP response")
2733
2734 def test_ap_wps_ssdp_burst(dev, apdev):
2735 """WPS AP and SSDP burst"""
2736 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2737 add_ssdp_ap(apdev[0], ap_uuid)
2738
2739 msg = '\r\n'.join([
2740 'M-SEARCH * HTTP/1.1',
2741 'HOST: 239.255.255.250:1900',
2742 'MAN: "ssdp:discover"',
2743 'MX: 1',
2744 'ST: urn:schemas-wifialliance-org:device:WFADevice:1',
2745 '', ''])
2746 socket.setdefaulttimeout(1)
2747 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2748 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2749 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2750 sock.bind(("127.0.0.1", 0))
2751 for i in range(0, 25):
2752 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2753 resp = 0
2754 while True:
2755 try:
2756 r = sock.recv(1000).decode()
2757 if not r.startswith("HTTP/1.1 200 OK\r\n"):
2758 raise Exception("Unexpected message: " + r)
2759 resp += 1
2760 except socket.timeout:
2761 break
2762 if resp < 20:
2763 raise Exception("Too few SSDP responses")
2764
2765 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
2766 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2767 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
2768 sock.bind(("127.0.0.1", 0))
2769 for i in range(0, 25):
2770 sock.sendto(msg.encode(), ("239.255.255.250", 1900))
2771 while True:
2772 try:
2773 r = sock.recv(1000).decode()
2774 if ap_uuid in r:
2775 break
2776 except socket.timeout:
2777 raise Exception("No SSDP response")
2778
2779 def ssdp_get_location(uuid):
2780 res = ssdp_send_msearch("uuid:" + uuid)
2781 location = None
2782 for l in res.splitlines():
2783 if l.lower().startswith("location:"):
2784 location = l.split(':', 1)[1].strip()
2785 break
2786 if location is None:
2787 raise Exception("No UPnP location found")
2788 return location
2789
2790 def upnp_get_urls(location):
2791 if sys.version_info[0] > 2:
2792 conn = urlopen(location)
2793 else:
2794 conn = urlopen(location, proxies={})
2795 tree = ET.parse(conn)
2796 root = tree.getroot()
2797 urn = '{urn:schemas-upnp-org:device-1-0}'
2798 service = root.find("./" + urn + "device/" + urn + "serviceList/" + urn + "service")
2799 res = {}
2800 res['scpd_url'] = urljoin(location, service.find(urn + 'SCPDURL').text)
2801 res['control_url'] = urljoin(location,
2802 service.find(urn + 'controlURL').text)
2803 res['event_sub_url'] = urljoin(location,
2804 service.find(urn + 'eventSubURL').text)
2805 return res
2806
2807 def upnp_soap_action(conn, path, action, include_soap_action=True,
2808 soap_action_override=None, newmsg=None, neweventtype=None,
2809 neweventmac=None):
2810 soapns = 'http://schemas.xmlsoap.org/soap/envelope/'
2811 wpsns = 'urn:schemas-wifialliance-org:service:WFAWLANConfig:1'
2812 ET.register_namespace('soapenv', soapns)
2813 ET.register_namespace('wfa', wpsns)
2814 attrib = {}
2815 attrib['{%s}encodingStyle' % soapns] = 'http://schemas.xmlsoap.org/soap/encoding/'
2816 root = ET.Element("{%s}Envelope" % soapns, attrib=attrib)
2817 body = ET.SubElement(root, "{%s}Body" % soapns)
2818 act = ET.SubElement(body, "{%s}%s" % (wpsns, action))
2819 if newmsg:
2820 msg = ET.SubElement(act, "NewMessage")
2821 msg.text = base64.b64encode(newmsg.encode()).decode()
2822 if neweventtype:
2823 msg = ET.SubElement(act, "NewWLANEventType")
2824 msg.text = neweventtype
2825 if neweventmac:
2826 msg = ET.SubElement(act, "NewWLANEventMAC")
2827 msg.text = neweventmac
2828
2829 headers = {"Content-type": 'text/xml; charset="utf-8"'}
2830 if include_soap_action:
2831 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % action
2832 elif soap_action_override:
2833 headers["SOAPAction"] = soap_action_override
2834 decl = b'<?xml version=\'1.0\' encoding=\'utf8\'?>\n'
2835 conn.request("POST", path, decl + ET.tostring(root), headers)
2836 return conn.getresponse()
2837
2838 def test_ap_wps_upnp(dev, apdev):
2839 """WPS AP and UPnP operations"""
2840 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2841 add_ssdp_ap(apdev[0], ap_uuid)
2842
2843 location = ssdp_get_location(ap_uuid)
2844 urls = upnp_get_urls(location)
2845
2846 if sys.version_info[0] > 2:
2847 conn = urlopen(urls['scpd_url'])
2848 else:
2849 conn = urlopen(urls['scpd_url'], proxies={})
2850 scpd = conn.read()
2851
2852 if sys.version_info[0] > 2:
2853 try:
2854 conn = urlopen(urljoin(location, "unknown.html"))
2855 raise Exception("Unexpected HTTP response to GET unknown URL")
2856 except HTTPError as e:
2857 if e.code != 404:
2858 raise Exception("Unexpected HTTP response to GET unknown URL")
2859 else:
2860 conn = urlopen(urljoin(location, "unknown.html"), proxies={})
2861 if conn.getcode() != 404:
2862 raise Exception("Unexpected HTTP response to GET unknown URL")
2863
2864 url = urlparse(location)
2865 conn = HTTPConnection(url.netloc)
2866 #conn.set_debuglevel(1)
2867 headers = {"Content-type": 'text/xml; charset="utf-8"',
2868 "SOAPAction": '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo"'}
2869 conn.request("POST", "hello", "\r\n\r\n", headers)
2870 resp = conn.getresponse()
2871 if resp.status != 404:
2872 raise Exception("Unexpected HTTP response: %d" % resp.status)
2873
2874 conn.request("UNKNOWN", "hello", "\r\n\r\n", headers)
2875 resp = conn.getresponse()
2876 if resp.status != 501:
2877 raise Exception("Unexpected HTTP response: %d" % resp.status)
2878
2879 headers = {"Content-type": 'text/xml; charset="utf-8"',
2880 "SOAPAction": '"urn:some-unknown-action#GetDeviceInfo"'}
2881 ctrlurl = urlparse(urls['control_url'])
2882 conn.request("POST", ctrlurl.path, "\r\n\r\n", headers)
2883 resp = conn.getresponse()
2884 if resp.status != 401:
2885 raise Exception("Unexpected HTTP response: %d" % resp.status)
2886
2887 logger.debug("GetDeviceInfo without SOAPAction header")
2888 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2889 include_soap_action=False)
2890 if resp.status != 401:
2891 raise Exception("Unexpected HTTP response: %d" % resp.status)
2892
2893 logger.debug("GetDeviceInfo with invalid SOAPAction header")
2894 for act in ["foo",
2895 "urn:schemas-wifialliance-org:service:WFAWLANConfig:1#GetDeviceInfo",
2896 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1"',
2897 '"urn:schemas-wifialliance-org:service:WFAWLANConfig:123#GetDevice']:
2898 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo",
2899 include_soap_action=False,
2900 soap_action_override=act)
2901 if resp.status != 401:
2902 raise Exception("Unexpected HTTP response: %d" % resp.status)
2903
2904 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
2905 if resp.status != 200:
2906 raise Exception("Unexpected HTTP response: %d" % resp.status)
2907 dev = resp.read().decode()
2908 if "NewDeviceInfo" not in dev:
2909 raise Exception("Unexpected GetDeviceInfo response")
2910
2911 logger.debug("PutMessage without required parameters")
2912 resp = upnp_soap_action(conn, ctrlurl.path, "PutMessage")
2913 if resp.status != 600:
2914 raise Exception("Unexpected HTTP response: %d" % resp.status)
2915
2916 logger.debug("PutWLANResponse without required parameters")
2917 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse")
2918 if resp.status != 600:
2919 raise Exception("Unexpected HTTP response: %d" % resp.status)
2920
2921 logger.debug("SetSelectedRegistrar from unregistered ER")
2922 resp = upnp_soap_action(conn, ctrlurl.path, "SetSelectedRegistrar")
2923 if resp.status != 501:
2924 raise Exception("Unexpected HTTP response: %d" % resp.status)
2925
2926 logger.debug("Unknown action")
2927 resp = upnp_soap_action(conn, ctrlurl.path, "Unknown")
2928 if resp.status != 401:
2929 raise Exception("Unexpected HTTP response: %d" % resp.status)
2930
2931 def test_ap_wps_upnp_subscribe(dev, apdev):
2932 """WPS AP and UPnP event subscription"""
2933 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
2934 hapd = add_ssdp_ap(apdev[0], ap_uuid)
2935
2936 location = ssdp_get_location(ap_uuid)
2937 urls = upnp_get_urls(location)
2938 eventurl = urlparse(urls['event_sub_url'])
2939
2940 url = urlparse(location)
2941 conn = HTTPConnection(url.netloc)
2942 #conn.set_debuglevel(1)
2943 headers = {"callback": '<http://127.0.0.1:12345/event>',
2944 "timeout": "Second-1234"}
2945 conn.request("SUBSCRIBE", "hello", "\r\n\r\n", headers)
2946 resp = conn.getresponse()
2947 if resp.status != 412:
2948 raise Exception("Unexpected HTTP response: %d" % resp.status)
2949
2950 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2951 resp = conn.getresponse()
2952 if resp.status != 412:
2953 raise Exception("Unexpected HTTP response: %d" % resp.status)
2954
2955 headers = {"NT": "upnp:event",
2956 "timeout": "Second-1234"}
2957 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2958 resp = conn.getresponse()
2959 if resp.status != 412:
2960 raise Exception("Unexpected HTTP response: %d" % resp.status)
2961
2962 headers = {"callback": '<http://127.0.0.1:12345/event>',
2963 "NT": "upnp:foobar",
2964 "timeout": "Second-1234"}
2965 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2966 resp = conn.getresponse()
2967 if resp.status != 400:
2968 raise Exception("Unexpected HTTP response: %d" % resp.status)
2969
2970 logger.debug("Valid subscription")
2971 headers = {"callback": '<http://127.0.0.1:12345/event>',
2972 "NT": "upnp:event",
2973 "timeout": "Second-1234"}
2974 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2975 resp = conn.getresponse()
2976 if resp.status != 200:
2977 raise Exception("Unexpected HTTP response: %d" % resp.status)
2978 sid = resp.getheader("sid")
2979 logger.debug("Subscription SID " + sid)
2980
2981 logger.debug("Invalid re-subscription")
2982 headers = {"NT": "upnp:event",
2983 "sid": "123456734567854",
2984 "timeout": "Second-1234"}
2985 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2986 resp = conn.getresponse()
2987 if resp.status != 400:
2988 raise Exception("Unexpected HTTP response: %d" % resp.status)
2989
2990 logger.debug("Invalid re-subscription")
2991 headers = {"NT": "upnp:event",
2992 "sid": "uuid:123456734567854",
2993 "timeout": "Second-1234"}
2994 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
2995 resp = conn.getresponse()
2996 if resp.status != 400:
2997 raise Exception("Unexpected HTTP response: %d" % resp.status)
2998
2999 logger.debug("Invalid re-subscription")
3000 headers = {"callback": '<http://127.0.0.1:12345/event>',
3001 "NT": "upnp:event",
3002 "sid": sid,
3003 "timeout": "Second-1234"}
3004 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3005 resp = conn.getresponse()
3006 if resp.status != 400:
3007 raise Exception("Unexpected HTTP response: %d" % resp.status)
3008
3009 logger.debug("SID mismatch in re-subscription")
3010 headers = {"NT": "upnp:event",
3011 "sid": "uuid:4c2bca79-1ff4-4e43-85d4-952a2b8a51fb",
3012 "timeout": "Second-1234"}
3013 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3014 resp = conn.getresponse()
3015 if resp.status != 412:
3016 raise Exception("Unexpected HTTP response: %d" % resp.status)
3017
3018 logger.debug("Valid re-subscription")
3019 headers = {"NT": "upnp:event",
3020 "sid": sid,
3021 "timeout": "Second-1234"}
3022 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3023 resp = conn.getresponse()
3024 if resp.status != 200:
3025 raise Exception("Unexpected HTTP response: %d" % resp.status)
3026 sid2 = resp.getheader("sid")
3027 logger.debug("Subscription SID " + sid2)
3028
3029 if sid != sid2:
3030 raise Exception("Unexpected SID change")
3031
3032 logger.debug("Valid re-subscription")
3033 headers = {"NT": "upnp:event",
3034 "sid": "uuid: \t \t" + sid.split(':')[1],
3035 "timeout": "Second-1234"}
3036 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3037 resp = conn.getresponse()
3038 if resp.status != 200:
3039 raise Exception("Unexpected HTTP response: %d" % resp.status)
3040
3041 logger.debug("Invalid unsubscription")
3042 headers = {"sid": sid}
3043 conn.request("UNSUBSCRIBE", "/hello", "\r\n\r\n", headers)
3044 resp = conn.getresponse()
3045 if resp.status != 412:
3046 raise Exception("Unexpected HTTP response: %d" % resp.status)
3047 headers = {"foo": "bar"}
3048 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3049 resp = conn.getresponse()
3050 if resp.status != 412:
3051 raise Exception("Unexpected HTTP response: %d" % resp.status)
3052
3053 logger.debug("Valid unsubscription")
3054 headers = {"sid": sid}
3055 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3056 resp = conn.getresponse()
3057 if resp.status != 200:
3058 raise Exception("Unexpected HTTP response: %d" % resp.status)
3059
3060 logger.debug("Unsubscription for not existing SID")
3061 headers = {"sid": sid}
3062 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3063 resp = conn.getresponse()
3064 if resp.status != 412:
3065 raise Exception("Unexpected HTTP response: %d" % resp.status)
3066
3067 logger.debug("Invalid unsubscription")
3068 headers = {"sid": " \t \tfoo"}
3069 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3070 resp = conn.getresponse()
3071 if resp.status != 400:
3072 raise Exception("Unexpected HTTP response: %d" % resp.status)
3073
3074 logger.debug("Invalid unsubscription")
3075 headers = {"sid": "uuid:\t \tfoo"}
3076 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3077 resp = conn.getresponse()
3078 if resp.status != 400:
3079 raise Exception("Unexpected HTTP response: %d" % resp.status)
3080
3081 logger.debug("Invalid unsubscription")
3082 headers = {"NT": "upnp:event",
3083 "sid": sid}
3084 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3085 resp = conn.getresponse()
3086 if resp.status != 400:
3087 raise Exception("Unexpected HTTP response: %d" % resp.status)
3088 headers = {"callback": '<http://127.0.0.1:12345/event>',
3089 "sid": sid}
3090 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3091 resp = conn.getresponse()
3092 if resp.status != 400:
3093 raise Exception("Unexpected HTTP response: %d" % resp.status)
3094
3095 logger.debug("Valid subscription with multiple callbacks")
3096 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>',
3097 "NT": "upnp:event",
3098 "timeout": "Second-1234"}
3099 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3100 resp = conn.getresponse()
3101 if resp.status != 200:
3102 raise Exception("Unexpected HTTP response: %d" % resp.status)
3103 sid = resp.getheader("sid")
3104 logger.debug("Subscription SID " + sid)
3105
3106 # Force subscription to be deleted due to errors
3107 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3108 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3109 with alloc_fail(hapd, 1, "event_build_message"):
3110 for i in range(10):
3111 dev[1].dump_monitor()
3112 dev[2].dump_monitor()
3113 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3114 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3115 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3116 dev[1].request("WPS_CANCEL")
3117 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3118 dev[2].request("WPS_CANCEL")
3119 if i % 4 == 1:
3120 time.sleep(1)
3121 else:
3122 time.sleep(0.1)
3123 time.sleep(0.2)
3124
3125 headers = {"sid": sid}
3126 conn.request("UNSUBSCRIBE", eventurl.path, "", headers)
3127 resp = conn.getresponse()
3128 if resp.status != 200 and resp.status != 412:
3129 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3130
3131 headers = {"callback": '<http://127.0.0.1:12345/event>',
3132 "NT": "upnp:event",
3133 "timeout": "Second-1234"}
3134 with alloc_fail(hapd, 1, "http_client_addr;event_send_start"):
3135 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3136 resp = conn.getresponse()
3137 if resp.status != 200:
3138 raise Exception("Unexpected HTTP response for SUBSCRIBE: %d" % resp.status)
3139 sid = resp.getheader("sid")
3140 logger.debug("Subscription SID " + sid)
3141
3142 headers = {"sid": sid}
3143 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3144 resp = conn.getresponse()
3145 if resp.status != 200:
3146 raise Exception("Unexpected HTTP response for UNSUBSCRIBE: %d" % resp.status)
3147
3148 headers = {"callback": '<http://127.0.0.1:12345/event>',
3149 "NT": "upnp:event",
3150 "timeout": "Second-1234"}
3151 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3152 resp = conn.getresponse()
3153 if resp.status != 200:
3154 raise Exception("Unexpected HTTP response: %d" % resp.status)
3155 sid = resp.getheader("sid")
3156 logger.debug("Subscription SID " + sid)
3157
3158 with alloc_fail(hapd, 1, "=wps_upnp_event_add"):
3159 for i in range(2):
3160 dev[1].dump_monitor()
3161 dev[2].dump_monitor()
3162 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3163 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3164 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3165 dev[1].request("WPS_CANCEL")
3166 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3167 dev[2].request("WPS_CANCEL")
3168 if i == 0:
3169 time.sleep(1)
3170 else:
3171 time.sleep(0.1)
3172
3173 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3174 resp = conn.getresponse()
3175 if resp.status != 200:
3176 raise Exception("Unexpected HTTP response: %d" % resp.status)
3177
3178 with alloc_fail(hapd, 1, "wpabuf_dup;wps_upnp_event_add"):
3179 dev[1].dump_monitor()
3180 dev[2].dump_monitor()
3181 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3182 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3183 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3184 dev[1].request("WPS_CANCEL")
3185 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3186 dev[2].request("WPS_CANCEL")
3187 time.sleep(0.1)
3188
3189 with fail_test(hapd, 1, "os_get_random;uuid_make;subscription_start"):
3190 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3191 resp = conn.getresponse()
3192 if resp.status != 500:
3193 raise Exception("Unexpected HTTP response: %d" % resp.status)
3194
3195 with alloc_fail(hapd, 1, "=subscription_start"):
3196 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3197 resp = conn.getresponse()
3198 if resp.status != 500:
3199 raise Exception("Unexpected HTTP response: %d" % resp.status)
3200
3201 headers = {"callback": '',
3202 "NT": "upnp:event",
3203 "timeout": "Second-1234"}
3204 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3205 resp = conn.getresponse()
3206 if resp.status != 500:
3207 raise Exception("Unexpected HTTP response: %d" % resp.status)
3208
3209 headers = {"callback": ' <',
3210 "NT": "upnp:event",
3211 "timeout": "Second-1234"}
3212 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3213 resp = conn.getresponse()
3214 if resp.status != 500:
3215 raise Exception("Unexpected HTTP response: %d" % resp.status)
3216
3217 headers = {"callback": '<http://127.0.0.1:12345/event>',
3218 "NT": "upnp:event",
3219 "timeout": "Second-1234"}
3220 with alloc_fail(hapd, 1, "wpabuf_alloc;subscription_first_event"):
3221 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3222 resp = conn.getresponse()
3223 if resp.status != 500:
3224 raise Exception("Unexpected HTTP response: %d" % resp.status)
3225
3226 with alloc_fail(hapd, 1, "wps_upnp_event_add;subscription_first_event"):
3227 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3228 resp = conn.getresponse()
3229 if resp.status != 500:
3230 raise Exception("Unexpected HTTP response: %d" % resp.status)
3231
3232 with alloc_fail(hapd, 1, "subscr_addr_add_url"):
3233 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3234 resp = conn.getresponse()
3235 if resp.status != 500:
3236 raise Exception("Unexpected HTTP response: %d" % resp.status)
3237
3238 with alloc_fail(hapd, 2, "subscr_addr_add_url"):
3239 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3240 resp = conn.getresponse()
3241 if resp.status != 500:
3242 raise Exception("Unexpected HTTP response: %d" % resp.status)
3243
3244 for i in range(6):
3245 headers = {"callback": '<http://127.0.0.1:%d/event>' % (12345 + i),
3246 "NT": "upnp:event",
3247 "timeout": "Second-1234"}
3248 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3249 resp = conn.getresponse()
3250 if resp.status != 200:
3251 raise Exception("Unexpected HTTP response: %d" % resp.status)
3252
3253 with alloc_fail(hapd, 1, "=upnp_wps_device_send_wlan_event"):
3254 dev[1].dump_monitor()
3255 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3256 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3257 dev[1].request("WPS_CANCEL")
3258 time.sleep(0.1)
3259
3260 with alloc_fail(hapd, 1, "wpabuf_alloc;upnp_wps_device_send_event"):
3261 dev[1].dump_monitor()
3262 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3263 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3264 dev[1].request("WPS_CANCEL")
3265 time.sleep(0.1)
3266
3267 with alloc_fail(hapd, 1,
3268 "base64_gen_encode;?base64_encode;upnp_wps_device_send_wlan_event"):
3269 dev[1].dump_monitor()
3270 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3271 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3272 dev[1].request("WPS_CANCEL")
3273 time.sleep(0.1)
3274
3275 hapd.disable()
3276 with alloc_fail(hapd, 1, "get_netif_info"):
3277 if "FAIL" not in hapd.request("ENABLE"):
3278 raise Exception("ENABLE succeeded during OOM")
3279
3280 def test_ap_wps_upnp_subscribe_events(dev, apdev):
3281 """WPS AP and UPnP event subscription and many events"""
3282 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3283 hapd = add_ssdp_ap(apdev[0], ap_uuid)
3284
3285 location = ssdp_get_location(ap_uuid)
3286 urls = upnp_get_urls(location)
3287 eventurl = urlparse(urls['event_sub_url'])
3288
3289 class WPSERHTTPServer(StreamRequestHandler):
3290 def handle(self):
3291 data = self.rfile.readline().strip()
3292 logger.debug(data)
3293 self.wfile.write(gen_wps_event())
3294
3295 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
3296 server.timeout = 1
3297
3298 url = urlparse(location)
3299 conn = HTTPConnection(url.netloc)
3300
3301 headers = {"callback": '<http://127.0.0.1:12345/event>',
3302 "NT": "upnp:event",
3303 "timeout": "Second-1234"}
3304 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
3305 resp = conn.getresponse()
3306 if resp.status != 200:
3307 raise Exception("Unexpected HTTP response: %d" % resp.status)
3308 sid = resp.getheader("sid")
3309 logger.debug("Subscription SID " + sid)
3310
3311 # Fetch the first event message
3312 server.handle_request()
3313
3314 # Force subscription event queue to reach the maximum length by generating
3315 # new proxied events without the ER fetching any of the pending events.
3316 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3317 dev[2].scan_for_bss(apdev[0]['bssid'], freq=2412)
3318 for i in range(16):
3319 dev[1].dump_monitor()
3320 dev[2].dump_monitor()
3321 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3322 dev[2].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3323 dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3324 dev[1].request("WPS_CANCEL")
3325 dev[2].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 5)
3326 dev[2].request("WPS_CANCEL")
3327 if i % 4 == 1:
3328 time.sleep(1)
3329 else:
3330 time.sleep(0.1)
3331
3332 hapd.request("WPS_PIN any 12345670")
3333 dev[1].dump_monitor()
3334 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3335 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=10)
3336 if ev is None:
3337 raise Exception("WPS success not reported")
3338
3339 # Close the WPS ER HTTP server without fetching all the pending events.
3340 # This tests hostapd code path that clears subscription and the remaining
3341 # event queue when the interface is deinitialized.
3342 server.handle_request()
3343 server.server_close()
3344
3345 dev[1].wait_connected()
3346
3347 def test_ap_wps_upnp_http_proto(dev, apdev):
3348 """WPS AP and UPnP/HTTP protocol testing"""
3349 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3350 add_ssdp_ap(apdev[0], ap_uuid)
3351
3352 location = ssdp_get_location(ap_uuid)
3353
3354 url = urlparse(location)
3355 conn = HTTPConnection(url.netloc, timeout=0.2)
3356 #conn.set_debuglevel(1)
3357
3358 conn.request("HEAD", "hello")
3359 resp = conn.getresponse()
3360 if resp.status != 501:
3361 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3362 conn.close()
3363
3364 for cmd in ["PUT", "DELETE", "TRACE", "CONNECT", "M-SEARCH", "M-POST"]:
3365 try:
3366 conn.request(cmd, "hello")
3367 resp = conn.getresponse()
3368 except Exception as e:
3369 pass
3370 conn.close()
3371
3372 headers = {"Content-Length": 'abc'}
3373 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3374 try:
3375 resp = conn.getresponse()
3376 except Exception as e:
3377 pass
3378 conn.close()
3379
3380 headers = {"Content-Length": '-10'}
3381 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3382 try:
3383 resp = conn.getresponse()
3384 except Exception as e:
3385 pass
3386 conn.close()
3387
3388 headers = {"Content-Length": '10000000000000'}
3389 conn.request("HEAD", "hello", "\r\n\r\nhello", headers)
3390 try:
3391 resp = conn.getresponse()
3392 except Exception as e:
3393 pass
3394 conn.close()
3395
3396 headers = {"Transfer-Encoding": 'abc'}
3397 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3398 resp = conn.getresponse()
3399 if resp.status != 501:
3400 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3401 conn.close()
3402
3403 headers = {"Transfer-Encoding": 'chunked'}
3404 conn.request("HEAD", "hello", "\r\n\r\n", headers)
3405 resp = conn.getresponse()
3406 if resp.status != 501:
3407 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3408 conn.close()
3409
3410 # Too long a header
3411 conn.request("HEAD", 5000 * 'A')
3412 try:
3413 resp = conn.getresponse()
3414 except Exception as e:
3415 pass
3416 conn.close()
3417
3418 # Long URL but within header length limits
3419 conn.request("HEAD", 3000 * 'A')
3420 resp = conn.getresponse()
3421 if resp.status != 501:
3422 raise Exception("Unexpected response to HEAD: " + str(resp.status))
3423 conn.close()
3424
3425 headers = {"Content-Length": '20'}
3426 conn.request("POST", "hello", 10 * 'A' + "\r\n\r\n", headers)
3427 try:
3428 resp = conn.getresponse()
3429 except Exception as e:
3430 pass
3431 conn.close()
3432
3433 conn.request("POST", "hello", 5000 * 'A' + "\r\n\r\n")
3434 resp = conn.getresponse()
3435 if resp.status != 404:
3436 raise Exception("Unexpected HTTP response: %d" % resp.status)
3437 conn.close()
3438
3439 conn.request("POST", "hello", 60000 * 'A' + "\r\n\r\n")
3440 try:
3441 resp = conn.getresponse()
3442 except Exception as e:
3443 pass
3444 conn.close()
3445
3446 def test_ap_wps_upnp_http_proto_chunked(dev, apdev):
3447 """WPS AP and UPnP/HTTP protocol testing for chunked encoding"""
3448 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3449 add_ssdp_ap(apdev[0], ap_uuid)
3450
3451 location = ssdp_get_location(ap_uuid)
3452
3453 url = urlparse(location)
3454 conn = HTTPConnection(url.netloc)
3455 #conn.set_debuglevel(1)
3456
3457 headers = {"Transfer-Encoding": 'chunked'}
3458 conn.request("POST", "hello",
3459 "a\r\nabcdefghij\r\n" + "2\r\nkl\r\n" + "0\r\n\r\n",
3460 headers)
3461 resp = conn.getresponse()
3462 if resp.status != 404:
3463 raise Exception("Unexpected HTTP response: %d" % resp.status)
3464 conn.close()
3465
3466 conn.putrequest("POST", "hello")
3467 conn.putheader('Transfer-Encoding', 'chunked')
3468 conn.endheaders()
3469 conn.send(b"a\r\nabcdefghij\r\n")
3470 time.sleep(0.1)
3471 conn.send(b"2\r\nkl\r\n")
3472 conn.send(b"0\r\n\r\n")
3473 resp = conn.getresponse()
3474 if resp.status != 404:
3475 raise Exception("Unexpected HTTP response: %d" % resp.status)
3476 conn.close()
3477
3478 conn.putrequest("POST", "hello")
3479 conn.putheader('Transfer-Encoding', 'chunked')
3480 conn.endheaders()
3481 completed = False
3482 try:
3483 for i in range(20000):
3484 conn.send(b"1\r\nZ\r\n")
3485 conn.send(b"0\r\n\r\n")
3486 resp = conn.getresponse()
3487 completed = True
3488 except Exception as e:
3489 pass
3490 conn.close()
3491 if completed:
3492 raise Exception("Too long chunked request did not result in connection reset")
3493
3494 headers = {"Transfer-Encoding": 'chunked'}
3495 conn.request("POST", "hello", "80000000\r\na", headers)
3496 try:
3497 resp = conn.getresponse()
3498 except Exception as e:
3499 pass
3500 conn.close()
3501
3502 conn.request("POST", "hello", "10000000\r\na", headers)
3503 try:
3504 resp = conn.getresponse()
3505 except Exception as e:
3506 pass
3507 conn.close()
3508
3509 @remote_compatible
3510 def test_ap_wps_disabled(dev, apdev):
3511 """WPS operations while WPS is disabled"""
3512 ssid = "test-wps-disabled"
3513 hapd = hostapd.add_ap(apdev[0], {"ssid": ssid})
3514 if "FAIL" not in hapd.request("WPS_PBC"):
3515 raise Exception("WPS_PBC succeeded unexpectedly")
3516 if "FAIL" not in hapd.request("WPS_CANCEL"):
3517 raise Exception("WPS_CANCEL succeeded unexpectedly")
3518
3519 def test_ap_wps_mixed_cred(dev, apdev):
3520 """WPS 2.0 STA merging mixed mode WPA/WPA2 credentials"""
3521 ssid = "test-wps-wep"
3522 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3523 "skip_cred_build": "1", "extra_cred": "wps-mixed-cred"}
3524 hapd = hostapd.add_ap(apdev[0], params)
3525 hapd.request("WPS_PBC")
3526 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3527 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3528 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=30)
3529 if ev is None:
3530 raise Exception("WPS-SUCCESS event timed out")
3531 nets = dev[0].list_networks()
3532 if len(nets) != 1:
3533 raise Exception("Unexpected number of network blocks")
3534 id = nets[0]['id']
3535 proto = dev[0].get_network(id, "proto")
3536 if proto != "WPA RSN":
3537 raise Exception("Unexpected merged proto field value: " + proto)
3538 pairwise = dev[0].get_network(id, "pairwise")
3539 p = pairwise.split()
3540 if "CCMP" not in p or "TKIP" not in p:
3541 raise Exception("Unexpected merged pairwise field value: " + pairwise)
3542
3543 @remote_compatible
3544 def test_ap_wps_while_connected(dev, apdev):
3545 """WPS PBC provisioning while connected to another AP"""
3546 ssid = "test-wps-conf"
3547 hapd = hostapd.add_ap(apdev[0],
3548 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3549 "wpa_passphrase": "12345678", "wpa": "2",
3550 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3551
3552 hostapd.add_ap(apdev[1], {"ssid": "open"})
3553 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3554
3555 logger.info("WPS provisioning step")
3556 hapd.request("WPS_PBC")
3557 dev[0].dump_monitor()
3558 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3559 dev[0].wait_connected(timeout=30)
3560 status = dev[0].get_status()
3561 if status['bssid'] != apdev[0]['bssid']:
3562 raise Exception("Unexpected BSSID")
3563
3564 @remote_compatible
3565 def test_ap_wps_while_connected_no_autoconnect(dev, apdev):
3566 """WPS PBC provisioning while connected to another AP and STA_AUTOCONNECT disabled"""
3567 ssid = "test-wps-conf"
3568 hapd = hostapd.add_ap(apdev[0],
3569 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3570 "wpa_passphrase": "12345678", "wpa": "2",
3571 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3572
3573 hostapd.add_ap(apdev[1], {"ssid": "open"})
3574
3575 try:
3576 dev[0].request("STA_AUTOCONNECT 0")
3577 dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
3578
3579 logger.info("WPS provisioning step")
3580 hapd.request("WPS_PBC")
3581 dev[0].dump_monitor()
3582 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3583 dev[0].wait_connected(timeout=30)
3584 status = dev[0].get_status()
3585 if status['bssid'] != apdev[0]['bssid']:
3586 raise Exception("Unexpected BSSID")
3587 finally:
3588 dev[0].request("STA_AUTOCONNECT 1")
3589
3590 @remote_compatible
3591 def test_ap_wps_from_event(dev, apdev):
3592 """WPS PBC event on AP to enable PBC"""
3593 ssid = "test-wps-conf"
3594 hapd = hostapd.add_ap(apdev[0],
3595 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3596 "wpa_passphrase": "12345678", "wpa": "2",
3597 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3598 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3599 dev[0].dump_monitor()
3600 hapd.dump_monitor()
3601 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
3602
3603 ev = hapd.wait_event(['WPS-ENROLLEE-SEEN'], timeout=15)
3604 if ev is None:
3605 raise Exception("No WPS-ENROLLEE-SEEN event on AP")
3606 vals = ev.split(' ')
3607 if vals[1] != dev[0].p2p_interface_addr():
3608 raise Exception("Unexpected enrollee address: " + vals[1])
3609 if vals[5] != '4':
3610 raise Exception("Unexpected Device Password Id: " + vals[5])
3611 hapd.request("WPS_PBC")
3612 dev[0].wait_connected(timeout=30)
3613
3614 def test_ap_wps_ap_scan_2(dev, apdev):
3615 """AP_SCAN 2 for WPS"""
3616 ssid = "test-wps-conf"
3617 hapd = hostapd.add_ap(apdev[0],
3618 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3619 "wpa_passphrase": "12345678", "wpa": "2",
3620 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3621 hapd.request("WPS_PBC")
3622
3623 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
3624 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
3625 wpas.dump_monitor()
3626
3627 if "OK" not in wpas.request("AP_SCAN 2"):
3628 raise Exception("Failed to set AP_SCAN 2")
3629
3630 wpas.flush_scan_cache()
3631 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
3632 wpas.dump_monitor()
3633 wpas.request("WPS_PBC " + apdev[0]['bssid'])
3634 ev = wpas.wait_event(["WPS-SUCCESS"], timeout=15)
3635 if ev is None:
3636 raise Exception("WPS-SUCCESS event timed out")
3637 wpas.wait_connected(timeout=30)
3638 wpas.dump_monitor()
3639 wpas.request("DISCONNECT")
3640 wpas.wait_disconnected()
3641 id = wpas.list_networks()[0]['id']
3642 pairwise = wpas.get_network(id, "pairwise")
3643 if "CCMP" not in pairwise.split():
3644 raise Exception("Unexpected pairwise parameter value: " + pairwise)
3645 group = wpas.get_network(id, "group")
3646 if "CCMP" not in group.split():
3647 raise Exception("Unexpected group parameter value: " + group)
3648 # Need to select a single cipher for ap_scan=2 testing
3649 wpas.set_network(id, "pairwise", "CCMP")
3650 wpas.set_network(id, "group", "CCMP")
3651 wpas.request("BSS_FLUSH 0")
3652 wpas.dump_monitor()
3653 wpas.request("REASSOCIATE")
3654 wpas.wait_connected(timeout=30)
3655 wpas.dump_monitor()
3656 wpas.request("DISCONNECT")
3657 wpas.wait_disconnected()
3658 wpas.flush_scan_cache()
3659
3660 @remote_compatible
3661 def test_ap_wps_eapol_workaround(dev, apdev):
3662 """EAPOL workaround code path for 802.1X header length mismatch"""
3663 ssid = "test-wps"
3664 hapd = hostapd.add_ap(apdev[0],
3665 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
3666 bssid = apdev[0]['bssid']
3667 hapd.request("SET ext_eapol_frame_io 1")
3668 dev[0].request("SET ext_eapol_frame_io 1")
3669 hapd.request("WPS_PBC")
3670 dev[0].request("WPS_PBC")
3671
3672 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3673 if ev is None:
3674 raise Exception("Timeout on EAPOL-TX from hostapd")
3675
3676 res = dev[0].request("EAPOL_RX " + bssid + " 020000040193000501FFFF")
3677 if "OK" not in res:
3678 raise Exception("EAPOL_RX to wpa_supplicant failed")
3679
3680 def test_ap_wps_iteration(dev, apdev):
3681 """WPS PIN and iterate through APs without selected registrar"""
3682 ssid = "test-wps-conf"
3683 hapd = hostapd.add_ap(apdev[0],
3684 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3685 "wpa_passphrase": "12345678", "wpa": "2",
3686 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3687
3688 ssid2 = "test-wps-conf2"
3689 hapd2 = hostapd.add_ap(apdev[1],
3690 {"ssid": ssid2, "eap_server": "1", "wps_state": "2",
3691 "wpa_passphrase": "12345678", "wpa": "2",
3692 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3693
3694 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3695 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
3696 dev[0].dump_monitor()
3697 pin = dev[0].request("WPS_PIN any")
3698
3699 # Wait for iteration through all WPS APs to happen before enabling any
3700 # Registrar.
3701 for i in range(2):
3702 ev = dev[0].wait_event(["Associated with"], timeout=30)
3703 if ev is None:
3704 raise Exception("No association seen")
3705 ev = dev[0].wait_event(["WPS-M2D"], timeout=10)
3706 if ev is None:
3707 raise Exception("No M2D from AP")
3708 dev[0].wait_disconnected()
3709
3710 # Verify that each AP requested PIN
3711 ev = hapd.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3712 if ev is None:
3713 raise Exception("No WPS-PIN-NEEDED event from AP")
3714 ev = hapd2.wait_event(["WPS-PIN-NEEDED"], timeout=1)
3715 if ev is None:
3716 raise Exception("No WPS-PIN-NEEDED event from AP2")
3717
3718 # Provide PIN to one of the APs and verify that connection gets formed
3719 hapd.request("WPS_PIN any " + pin)
3720 dev[0].wait_connected(timeout=30)
3721
3722 def test_ap_wps_iteration_error(dev, apdev):
3723 """WPS AP iteration on no Selected Registrar and error case with an AP"""
3724 ssid = "test-wps-conf-pin"
3725 hapd = hostapd.add_ap(apdev[0],
3726 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3727 "wpa_passphrase": "12345678", "wpa": "2",
3728 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3729 "wps_independent": "1"})
3730 hapd.request("SET ext_eapol_frame_io 1")
3731 bssid = apdev[0]['bssid']
3732 pin = dev[0].wps_read_pin()
3733 dev[0].request("WPS_PIN any " + pin)
3734
3735 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3736 if ev is None:
3737 raise Exception("No EAPOL-TX (EAP-Request/Identity) from hostapd")
3738 dev[0].request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
3739
3740 ev = hapd.wait_event(["EAPOL-TX"], timeout=15)
3741 if ev is None:
3742 raise Exception("No EAPOL-TX (EAP-WSC/Start) from hostapd")
3743 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=5)
3744 if ev is None:
3745 raise Exception("No CTRL-EVENT-EAP-STARTED")
3746
3747 # Do not forward any more EAPOL frames to test wpa_supplicant behavior for
3748 # a case with an incorrectly behaving WPS AP.
3749
3750 # Start the real target AP and activate registrar on it.
3751 hapd2 = hostapd.add_ap(apdev[1],
3752 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3753 "wpa_passphrase": "12345678", "wpa": "2",
3754 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3755 "wps_independent": "1"})
3756 hapd2.request("WPS_PIN any " + pin)
3757
3758 dev[0].wait_disconnected(timeout=15)
3759 ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED"], timeout=15)
3760 if ev is None:
3761 raise Exception("No CTRL-EVENT-EAP-STARTED for the second AP")
3762 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
3763 if ev is None:
3764 raise Exception("No WPS-CRED-RECEIVED for the second AP")
3765 dev[0].wait_connected(timeout=15)
3766
3767 @remote_compatible
3768 def test_ap_wps_priority(dev, apdev):
3769 """WPS PIN provisioning with configured AP and wps_priority"""
3770 ssid = "test-wps-conf-pin"
3771 hapd = hostapd.add_ap(apdev[0],
3772 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3773 "wpa_passphrase": "12345678", "wpa": "2",
3774 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3775 logger.info("WPS provisioning step")
3776 pin = dev[0].wps_read_pin()
3777 hapd.request("WPS_PIN any " + pin)
3778 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3779 dev[0].dump_monitor()
3780 try:
3781 dev[0].request("SET wps_priority 6")
3782 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3783 dev[0].wait_connected(timeout=30)
3784 netw = dev[0].list_networks()
3785 prio = dev[0].get_network(netw[0]['id'], 'priority')
3786 if prio != '6':
3787 raise Exception("Unexpected network priority: " + prio)
3788 finally:
3789 dev[0].request("SET wps_priority 0")
3790
3791 @remote_compatible
3792 def test_ap_wps_and_non_wps(dev, apdev):
3793 """WPS and non-WPS AP in single hostapd process"""
3794 params = {"ssid": "wps", "eap_server": "1", "wps_state": "1"}
3795 hapd = hostapd.add_ap(apdev[0], params)
3796
3797 params = {"ssid": "no wps"}
3798 hapd2 = hostapd.add_ap(apdev[1], params)
3799
3800 appin = hapd.request("WPS_AP_PIN random")
3801 if "FAIL" in appin:
3802 raise Exception("Could not generate random AP PIN")
3803 if appin not in hapd.request("WPS_AP_PIN get"):
3804 raise Exception("Could not fetch current AP PIN")
3805
3806 if "FAIL" in hapd.request("WPS_PBC"):
3807 raise Exception("WPS_PBC failed")
3808 if "FAIL" in hapd.request("WPS_CANCEL"):
3809 raise Exception("WPS_CANCEL failed")
3810
3811 def test_ap_wps_init_oom(dev, apdev):
3812 """Initial AP configuration and OOM during PSK generation"""
3813 ssid = "test-wps"
3814 params = {"ssid": ssid, "eap_server": "1", "wps_state": "1"}
3815 hapd = hostapd.add_ap(apdev[0], params)
3816
3817 with alloc_fail(hapd, 1, "base64_gen_encode;?base64_encode;wps_build_cred"):
3818 pin = dev[0].wps_read_pin()
3819 hapd.request("WPS_PIN any " + pin)
3820 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3821 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
3822 dev[0].wait_disconnected()
3823
3824 hapd.request("WPS_PIN any " + pin)
3825 dev[0].wait_connected(timeout=30)
3826
3827 @remote_compatible
3828 def test_ap_wps_er_oom(dev, apdev):
3829 """WPS ER OOM in XML processing"""
3830 try:
3831 _test_ap_wps_er_oom(dev, apdev)
3832 finally:
3833 dev[0].request("WPS_ER_STOP")
3834 dev[1].request("WPS_CANCEL")
3835 dev[0].request("DISCONNECT")
3836
3837 def _test_ap_wps_er_oom(dev, apdev):
3838 ssid = "wps-er-ap-config"
3839 ap_pin = "12345670"
3840 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
3841 hostapd.add_ap(apdev[0],
3842 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3843 "wpa_passphrase": "12345678", "wpa": "2",
3844 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
3845 "device_name": "Wireless AP", "manufacturer": "Company",
3846 "model_name": "WAP", "model_number": "123",
3847 "serial_number": "12345", "device_type": "6-0050F204-1",
3848 "os_version": "01020300",
3849 "config_methods": "label push_button",
3850 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"})
3851
3852 dev[0].connect(ssid, psk="12345678", scan_freq="2412")
3853
3854 with alloc_fail(dev[0], 1,
3855 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
3856 dev[0].request("WPS_ER_START ifname=lo")
3857 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=3)
3858 if ev is not None:
3859 raise Exception("Unexpected AP discovery")
3860
3861 dev[0].request("WPS_ER_STOP")
3862 dev[0].request("WPS_ER_START ifname=lo")
3863 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
3864 if ev is None:
3865 raise Exception("AP discovery timed out")
3866
3867 dev[1].scan_for_bss(apdev[0]['bssid'], freq=2412)
3868 with alloc_fail(dev[0], 1,
3869 "base64_gen_decode;?base64_decode;xml_get_base64_item"):
3870 dev[1].request("WPS_PBC " + apdev[0]['bssid'])
3871 ev = dev[1].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
3872 if ev is None:
3873 raise Exception("PBC scan failed")
3874 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=15)
3875 if ev is None:
3876 raise Exception("Enrollee discovery timed out")
3877
3878 @remote_compatible
3879 def test_ap_wps_er_init_oom(dev, apdev):
3880 """WPS ER and OOM during init"""
3881 try:
3882 _test_ap_wps_er_init_oom(dev, apdev)
3883 finally:
3884 dev[0].request("WPS_ER_STOP")
3885
3886 def _test_ap_wps_er_init_oom(dev, apdev):
3887 with alloc_fail(dev[0], 1, "wps_er_init"):
3888 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3889 raise Exception("WPS_ER_START succeeded during OOM")
3890 with alloc_fail(dev[0], 1, "http_server_init"):
3891 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3892 raise Exception("WPS_ER_START succeeded during OOM")
3893 with alloc_fail(dev[0], 2, "http_server_init"):
3894 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3895 raise Exception("WPS_ER_START succeeded during OOM")
3896 with alloc_fail(dev[0], 1, "eloop_sock_table_add_sock;?eloop_register_sock;wps_er_ssdp_init"):
3897 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3898 raise Exception("WPS_ER_START succeeded during OOM")
3899 with fail_test(dev[0], 1, "os_get_random;wps_er_init"):
3900 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo"):
3901 raise Exception("WPS_ER_START succeeded during os_get_random failure")
3902
3903 @remote_compatible
3904 def test_ap_wps_er_init_fail(dev, apdev):
3905 """WPS ER init failure"""
3906 if "FAIL" not in dev[0].request("WPS_ER_START ifname=does-not-exist"):
3907 dev[0].request("WPS_ER_STOP")
3908 raise Exception("WPS_ER_START with non-existing ifname succeeded")
3909
3910 def test_ap_wps_wpa_cli_action(dev, apdev, test_params):
3911 """WPS events and wpa_cli action script"""
3912 logdir = os.path.abspath(test_params['logdir'])
3913 pidfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.pid')
3914 logfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.res')
3915 actionfile = os.path.join(logdir, 'ap_wps_wpa_cli_action.wpa_cli.action.sh')
3916
3917 with open(actionfile, 'w') as f:
3918 f.write('#!/bin/sh\n')
3919 f.write('echo $* >> %s\n' % logfile)
3920 # Kill the process and wait some time before returning to allow all the
3921 # pending events to be processed with some of this happening after the
3922 # eloop SIGALRM signal has been scheduled.
3923 f.write('if [ $2 = "WPS-SUCCESS" -a -r %s ]; then kill `cat %s`; sleep 1; fi\n' % (pidfile, pidfile))
3924
3925 os.chmod(actionfile, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC |
3926 stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
3927
3928 ssid = "test-wps-conf"
3929 hapd = hostapd.add_ap(apdev[0],
3930 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
3931 "wpa_passphrase": "12345678", "wpa": "2",
3932 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
3933
3934 prg = os.path.join(test_params['logdir'],
3935 'alt-wpa_supplicant/wpa_supplicant/wpa_cli')
3936 if not os.path.exists(prg):
3937 prg = '../../wpa_supplicant/wpa_cli'
3938 arg = [prg, '-P', pidfile, '-B', '-i', dev[0].ifname, '-a', actionfile]
3939 subprocess.call(arg)
3940
3941 arg = ['ps', 'ax']
3942 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3943 out = cmd.communicate()[0].decode()
3944 cmd.wait()
3945 logger.debug("Processes:\n" + out)
3946 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) not in out:
3947 raise Exception("Did not see wpa_cli running")
3948
3949 hapd.request("WPS_PIN any 12345670")
3950 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
3951 dev[0].dump_monitor()
3952 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
3953 dev[0].wait_connected(timeout=30)
3954
3955 for i in range(30):
3956 if not os.path.exists(pidfile):
3957 break
3958 time.sleep(0.1)
3959
3960 if not os.path.exists(logfile):
3961 raise Exception("wpa_cli action results file not found")
3962 with open(logfile, 'r') as f:
3963 res = f.read()
3964 if "WPS-SUCCESS" not in res:
3965 raise Exception("WPS-SUCCESS event not seen in action file")
3966
3967 arg = ['ps', 'ax']
3968 cmd = subprocess.Popen(arg, stdout=subprocess.PIPE)
3969 out = cmd.communicate()[0].decode()
3970 cmd.wait()
3971 logger.debug("Remaining processes:\n" + out)
3972 if "wpa_cli -P %s -B -i %s" % (pidfile, dev[0].ifname) in out:
3973 raise Exception("wpa_cli still running")
3974
3975 if os.path.exists(pidfile):
3976 raise Exception("PID file not removed")
3977
3978 def test_ap_wps_er_ssdp_proto(dev, apdev):
3979 """WPS ER SSDP protocol testing"""
3980 try:
3981 _test_ap_wps_er_ssdp_proto(dev, apdev)
3982 finally:
3983 dev[0].request("WPS_ER_STOP")
3984
3985 def _test_ap_wps_er_ssdp_proto(dev, apdev):
3986 socket.setdefaulttimeout(1)
3987 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
3988 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
3989 sock.bind(("239.255.255.250", 1900))
3990 if "FAIL" not in dev[0].request("WPS_ER_START ifname=lo foo"):
3991 raise Exception("Invalid filter accepted")
3992 if "OK" not in dev[0].request("WPS_ER_START ifname=lo 1.2.3.4"):
3993 raise Exception("WPS_ER_START with filter failed")
3994 (msg, addr) = sock.recvfrom(1000)
3995 msg = msg.decode()
3996 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
3997 if "M-SEARCH" not in msg:
3998 raise Exception("Not an M-SEARCH")
3999 sock.sendto(b"FOO", addr)
4000 time.sleep(0.1)
4001 dev[0].request("WPS_ER_STOP")
4002
4003 dev[0].request("WPS_ER_START ifname=lo")
4004 (msg, addr) = sock.recvfrom(1000)
4005 msg = msg.decode()
4006 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4007 if "M-SEARCH" not in msg:
4008 raise Exception("Not an M-SEARCH")
4009 sock.sendto(b"FOO", addr)
4010 sock.sendto(b"HTTP/1.1 200 OK\r\nFOO\r\n\r\n", addr)
4011 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:foo\r\n\r\n", addr)
4012 sock.sendto(b"HTTP/1.1 200 OK\r\nNTS:ssdp:byebye\r\n\r\n", addr)
4013 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: foo=1\r\n\r\n", addr)
4014 sock.sendto(b"HTTP/1.1 200 OK\r\ncache-control: max-age=1\r\n\r\n", addr)
4015 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:\r\n\r\n", addr)
4016 sock.sendto(b"HTTP/1.1 200 OK\r\nusn:foo\r\n\r\n", addr)
4017 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid:\r\n\r\n", addr)
4018 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: \r\n\r\n", addr)
4019 sock.sendto(b"HTTP/1.1 200 OK\r\nusn: uuid: foo\r\n\r\n", addr)
4020 sock.sendto(b"HTTP/1.1 200 OK\r\nST: urn:schemas-wifialliance-org:device:WFADevice:1\r\n\r\n", addr)
4021 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)
4022 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)
4023 with alloc_fail(dev[0], 1, "wps_er_ap_add"):
4024 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)
4025 time.sleep(0.1)
4026 with alloc_fail(dev[0], 2, "wps_er_ap_add"):
4027 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)
4028 time.sleep(0.1)
4029
4030 # Add an AP with bogus URL
4031 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)
4032 # Update timeout on AP without updating URL
4033 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)
4034 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4035 if ev is None:
4036 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4037
4038 # Add an AP with a valid URL (but no server listing to it)
4039 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)
4040 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4041 if ev is None:
4042 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4043
4044 sock.close()
4045
4046 wps_event_url = None
4047
4048 def gen_upnp_info(eventSubURL='wps_event', controlURL='wps_control',
4049 udn='uuid:27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'):
4050 payload = '''<?xml version="1.0"?>
4051 <root xmlns="urn:schemas-upnp-org:device-1-0">
4052 <specVersion>
4053 <major>1</major>
4054 <minor>0</minor>
4055 </specVersion>
4056 <device>
4057 <deviceType>urn:schemas-wifialliance-org:device:WFADevice:1</deviceType>
4058 <friendlyName>WPS Access Point</friendlyName>
4059 <manufacturer>Company</manufacturer>
4060 <modelName>WAP</modelName>
4061 <modelNumber>123</modelNumber>
4062 <serialNumber>12345</serialNumber>
4063 '''
4064 if udn:
4065 payload += '<UDN>' + udn + '</UDN>'
4066 payload += '''<serviceList>
4067 <service>
4068 <serviceType>urn:schemas-wifialliance-org:service:WFAWLANConfig:1</serviceType>
4069 <serviceId>urn:wifialliance-org:serviceId:WFAWLANConfig1</serviceId>
4070 <SCPDURL>wps_scpd.xml</SCPDURL>
4071 '''
4072 if controlURL:
4073 payload += '<controlURL>' + controlURL + '</controlURL>\n'
4074 if eventSubURL:
4075 payload += '<eventSubURL>' + eventSubURL + '</eventSubURL>\n'
4076 payload += '''</service>
4077 </serviceList>
4078 </device>
4079 </root>
4080 '''
4081 hdr = 'HTTP/1.1 200 OK\r\n' + \
4082 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4083 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4084 'Connection: close\r\n' + \
4085 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4086 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4087 return (hdr + payload).encode()
4088
4089 def gen_wps_control(payload_override=None):
4090 payload = '''<?xml version="1.0"?>
4091 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4092 <s:Body>
4093 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4094 <NewDeviceInfo>EEoAARAQIgABBBBHABAn6oAanlxOc72C+Jy80Q1+ECAABgIAAAADABAaABCJZ7DPtbU3Ust9
4095 Z3wJF07WEDIAwH45D3i1OqB7eJGwTzqeapS71h3KyXncK2xJZ+xqScrlorNEg6LijBJzG2Ca
4096 +FZli0iliDJd397yAx/jk4nFXco3q5ylBSvSw9dhJ5u1xBKSnTilKGlUHPhLP75PUqM3fot9
4097 7zwtFZ4bx6x1sBA6oEe2d0aUJmLumQGCiKEIWlnxs44zego/2tAe81bDzdPBM7o5HH/FUhD+
4098 KoGzFXp51atP+1n9Vta6AkI0Vye99JKLcC6Md9dMJltSVBgd4Xc4lRAEAAIAIxAQAAIADRAN
4099 AAEBEAgAAgAEEEQAAQIQIQAHQ29tcGFueRAjAANXQVAQJAADMTIzEEIABTEyMzQ1EFQACAAG
4100 AFDyBAABEBEAC1dpcmVsZXNzIEFQEDwAAQEQAgACAAAQEgACAAAQCQACAAAQLQAEgQIDABBJ
4101 AAYANyoAASA=
4102 </NewDeviceInfo>
4103 </u:GetDeviceInfoResponse>
4104 </s:Body>
4105 </s:Envelope>
4106 '''
4107 if payload_override:
4108 payload = payload_override
4109 hdr = 'HTTP/1.1 200 OK\r\n' + \
4110 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4111 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4112 'Connection: close\r\n' + \
4113 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4114 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4115 return (hdr + payload).encode()
4116
4117 def gen_wps_event(sid='uuid:7eb3342a-8a5f-47fe-a585-0785bfec6d8a'):
4118 payload = ""
4119 hdr = 'HTTP/1.1 200 OK\r\n' + \
4120 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4121 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4122 'Connection: close\r\n' + \
4123 'Content-Length: ' + str(len(payload)) + '\r\n'
4124 if sid:
4125 hdr += 'SID: ' + sid + '\r\n'
4126 hdr += 'Timeout: Second-1801\r\n' + \
4127 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4128 return (hdr + payload).encode()
4129
4130 class WPSAPHTTPServer(StreamRequestHandler):
4131 def handle(self):
4132 data = self.rfile.readline().decode().strip()
4133 logger.info("HTTP server received: " + data)
4134 while True:
4135 hdr = self.rfile.readline().decode().strip()
4136 if len(hdr) == 0:
4137 break
4138 logger.info("HTTP header: " + hdr)
4139 if "CALLBACK:" in hdr:
4140 global wps_event_url
4141 wps_event_url = hdr.split(' ')[1].strip('<>')
4142
4143 if "GET /foo.xml" in data:
4144 self.handle_upnp_info()
4145 elif "POST /wps_control" in data:
4146 self.handle_wps_control()
4147 elif "SUBSCRIBE /wps_event" in data:
4148 self.handle_wps_event()
4149 else:
4150 self.handle_others(data)
4151
4152 def handle_upnp_info(self):
4153 self.wfile.write(gen_upnp_info())
4154
4155 def handle_wps_control(self):
4156 self.wfile.write(gen_wps_control())
4157
4158 def handle_wps_event(self):
4159 self.wfile.write(gen_wps_event())
4160
4161 def handle_others(self, data):
4162 logger.info("Ignore HTTP request: " + data)
4163
4164 class MyTCPServer(TCPServer):
4165 def __init__(self, addr, handler):
4166 self.allow_reuse_address = True
4167 TCPServer.__init__(self, addr, handler)
4168
4169 def wps_er_start(dev, http_server, max_age=1, wait_m_search=False,
4170 location_url=None):
4171 socket.setdefaulttimeout(1)
4172 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4173 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4174 sock.bind(("239.255.255.250", 1900))
4175 dev.request("WPS_ER_START ifname=lo")
4176 for i in range(100):
4177 (msg, addr) = sock.recvfrom(1000)
4178 msg = msg.decode()
4179 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4180 if "M-SEARCH" in msg:
4181 break
4182 if not wait_m_search:
4183 raise Exception("Not an M-SEARCH")
4184 if i == 99:
4185 raise Exception("No M-SEARCH seen")
4186
4187 # Add an AP with a valid URL and server listing to it
4188 server = MyTCPServer(("127.0.0.1", 12345), http_server)
4189 if not location_url:
4190 location_url = 'http://127.0.0.1:12345/foo.xml'
4191 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)
4192 server.timeout = 1
4193 return server, sock
4194
4195 def wps_er_stop(dev, sock, server, on_alloc_fail=False):
4196 sock.close()
4197 server.server_close()
4198
4199 if on_alloc_fail:
4200 done = False
4201 for i in range(50):
4202 res = dev.request("GET_ALLOC_FAIL")
4203 if res.startswith("0:"):
4204 done = True
4205 break
4206 time.sleep(0.1)
4207 if not done:
4208 raise Exception("No allocation failure reported")
4209 else:
4210 ev = dev.wait_event(["WPS-ER-AP-REMOVE"], timeout=5)
4211 if ev is None:
4212 raise Exception("No WPS-ER-AP-REMOVE event on max-age timeout")
4213 dev.request("WPS_ER_STOP")
4214
4215 def run_wps_er_proto_test(dev, handler, no_event_url=False, location_url=None):
4216 try:
4217 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
4218 server, sock = wps_er_start(dev, handler, location_url=location_url)
4219 global wps_event_url
4220 wps_event_url = None
4221 server.handle_request()
4222 server.handle_request()
4223 server.handle_request()
4224 server.server_close()
4225 if no_event_url:
4226 if wps_event_url:
4227 raise Exception("Received event URL unexpectedly")
4228 return
4229 if wps_event_url is None:
4230 raise Exception("Did not get event URL")
4231 logger.info("Event URL: " + wps_event_url)
4232 finally:
4233 dev.request("WPS_ER_STOP")
4234
4235 def send_wlanevent(url, uuid, data, no_response=False):
4236 conn = HTTPConnection(url.netloc)
4237 payload = '''<?xml version="1.0" encoding="utf-8"?>
4238 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4239 <e:property><STAStatus>1</STAStatus></e:property>
4240 <e:property><APStatus>1</APStatus></e:property>
4241 <e:property><WLANEvent>'''
4242 payload += base64.b64encode(data).decode()
4243 payload += '</WLANEvent></e:property></e:propertyset>'
4244 headers = {"Content-type": 'text/xml; charset="utf-8"',
4245 "Server": "Unspecified, UPnP/1.0, Unspecified",
4246 "HOST": url.netloc,
4247 "NT": "upnp:event",
4248 "SID": "uuid:" + uuid,
4249 "SEQ": "0",
4250 "Content-Length": str(len(payload))}
4251 conn.request("NOTIFY", url.path, payload, headers)
4252 if no_response:
4253 try:
4254 conn.getresponse()
4255 except Exception as e:
4256 pass
4257 return
4258 resp = conn.getresponse()
4259 if resp.status != 200:
4260 raise Exception("Unexpected HTTP response: %d" % resp.status)
4261
4262 def test_ap_wps_er_http_proto(dev, apdev):
4263 """WPS ER HTTP protocol testing"""
4264 try:
4265 _test_ap_wps_er_http_proto(dev, apdev)
4266 finally:
4267 dev[0].request("WPS_ER_STOP")
4268
4269 def _test_ap_wps_er_http_proto(dev, apdev):
4270 uuid = '27ea801a-9e5c-4e73-bd82-f89cbcd10d7e'
4271 server, sock = wps_er_start(dev[0], WPSAPHTTPServer, max_age=15)
4272 global wps_event_url
4273 wps_event_url = None
4274 server.handle_request()
4275 server.handle_request()
4276 server.handle_request()
4277 server.server_close()
4278 if wps_event_url is None:
4279 raise Exception("Did not get event URL")
4280 logger.info("Event URL: " + wps_event_url)
4281
4282 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=10)
4283 if ev is None:
4284 raise Exception("No WPS-ER-AP-ADD event")
4285 if uuid not in ev:
4286 raise Exception("UUID mismatch")
4287
4288 sock.close()
4289
4290 logger.info("Valid Probe Request notification")
4291 url = urlparse(wps_event_url)
4292 conn = HTTPConnection(url.netloc)
4293 payload = '''<?xml version="1.0" encoding="utf-8"?>
4294 <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
4295 <e:property><STAStatus>1</STAStatus></e:property>
4296 <e:property><APStatus>1</APStatus></e:property>
4297 <e:property><WLANEvent>ATAyOjAwOjAwOjAwOjAwOjAwEEoAARAQOgABAhAIAAIxSBBHABA2LbR7pTpRkYj7VFi5hrLk
4298 EFQACAAAAAAAAAAAEDwAAQMQAgACAAAQCQACAAAQEgACAAAQIQABIBAjAAEgECQAASAQEQAI
4299 RGV2aWNlIEEQSQAGADcqAAEg
4300 </WLANEvent></e:property>
4301 </e:propertyset>
4302 '''
4303 headers = {"Content-type": 'text/xml; charset="utf-8"',
4304 "Server": "Unspecified, UPnP/1.0, Unspecified",
4305 "HOST": url.netloc,
4306 "NT": "upnp:event",
4307 "SID": "uuid:" + uuid,
4308 "SEQ": "0",
4309 "Content-Length": str(len(payload))}
4310 conn.request("NOTIFY", url.path, payload, headers)
4311 resp = conn.getresponse()
4312 if resp.status != 200:
4313 raise Exception("Unexpected HTTP response: %d" % resp.status)
4314
4315 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=5)
4316 if ev is None:
4317 raise Exception("No WPS-ER-ENROLLEE-ADD event")
4318 if "362db47b-a53a-5191-88fb-5458b986b2e4" not in ev:
4319 raise Exception("No Enrollee UUID match")
4320
4321 logger.info("Incorrect event URL AP id")
4322 conn = HTTPConnection(url.netloc)
4323 conn.request("NOTIFY", url.path + '123', payload, headers)
4324 resp = conn.getresponse()
4325 if resp.status != 404:
4326 raise Exception("Unexpected HTTP response: %d" % resp.status)
4327
4328 logger.info("Missing AP id")
4329 conn = HTTPConnection(url.netloc)
4330 conn.request("NOTIFY", '/event/' + url.path.split('/')[2],
4331 payload, headers)
4332 time.sleep(0.1)
4333
4334 logger.info("Incorrect event URL event id")
4335 conn = HTTPConnection(url.netloc)
4336 conn.request("NOTIFY", '/event/123456789/123', payload, headers)
4337 time.sleep(0.1)
4338
4339 logger.info("Incorrect event URL prefix")
4340 conn = HTTPConnection(url.netloc)
4341 conn.request("NOTIFY", '/foobar/123456789/123', payload, headers)
4342 resp = conn.getresponse()
4343 if resp.status != 404:
4344 raise Exception("Unexpected HTTP response: %d" % resp.status)
4345
4346 logger.info("Unsupported request")
4347 conn = HTTPConnection(url.netloc)
4348 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4349 resp = conn.getresponse()
4350 if resp.status != 501:
4351 raise Exception("Unexpected HTTP response: %d" % resp.status)
4352
4353 logger.info("Unsupported request and OOM")
4354 with alloc_fail(dev[0], 1, "wps_er_http_req"):
4355 conn = HTTPConnection(url.netloc)
4356 conn.request("FOOBAR", '/foobar/123456789/123', payload, headers)
4357 time.sleep(0.5)
4358
4359 logger.info("Too short WLANEvent")
4360 data = b'\x00'
4361 send_wlanevent(url, uuid, data)
4362
4363 logger.info("Invalid WLANEventMAC")
4364 data = b'\x00qwertyuiopasdfghjklzxcvbnm'
4365 send_wlanevent(url, uuid, data)
4366
4367 logger.info("Unknown WLANEventType")
4368 data = b'\xff02:00:00:00:00:00'
4369 send_wlanevent(url, uuid, data)
4370
4371 logger.info("Probe Request notification without any attributes")
4372 data = b'\x0102:00:00:00:00:00'
4373 send_wlanevent(url, uuid, data)
4374
4375 logger.info("Probe Request notification with invalid attribute")
4376 data = b'\x0102:00:00:00:00:00\xff'
4377 send_wlanevent(url, uuid, data)
4378
4379 logger.info("EAP message without any attributes")
4380 data = b'\x0202:00:00:00:00:00'
4381 send_wlanevent(url, uuid, data)
4382
4383 logger.info("EAP message with invalid attribute")
4384 data = b'\x0202:00:00:00:00:00\xff'
4385 send_wlanevent(url, uuid, data)
4386
4387 logger.info("EAP message from new STA and not M1")
4388 data = b'\x0202:ff:ff:ff:ff:ff' + b'\x10\x22\x00\x01\x05'
4389 send_wlanevent(url, uuid, data)
4390
4391 logger.info("EAP message: M1")
4392 data = b'\x0202:00:00:00:00:00'
4393 data += b'\x10\x22\x00\x01\x04'
4394 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4395 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4396 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4397 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4398 data += b'\x10\x04\x00\x02\x00\x00'
4399 data += b'\x10\x10\x00\x02\x00\x00'
4400 data += b'\x10\x0d\x00\x01\x00'
4401 data += b'\x10\x08\x00\x02\x00\x00'
4402 data += b'\x10\x44\x00\x01\x00'
4403 data += b'\x10\x21\x00\x00'
4404 data += b'\x10\x23\x00\x00'
4405 data += b'\x10\x24\x00\x00'
4406 data += b'\x10\x42\x00\x00'
4407 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4408 data += b'\x10\x11\x00\x00'
4409 data += b'\x10\x3c\x00\x01\x00'
4410 data += b'\x10\x02\x00\x02\x00\x00'
4411 data += b'\x10\x12\x00\x02\x00\x00'
4412 data += b'\x10\x09\x00\x02\x00\x00'
4413 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
4414 m1 = data
4415 send_wlanevent(url, uuid, data)
4416
4417 logger.info("EAP message: WSC_ACK")
4418 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0d'
4419 send_wlanevent(url, uuid, data)
4420
4421 logger.info("EAP message: M1")
4422 send_wlanevent(url, uuid, m1)
4423
4424 logger.info("EAP message: WSC_NACK")
4425 data = b'\x0202:00:00:00:00:00' + b'\x10\x22\x00\x01\x0e'
4426 send_wlanevent(url, uuid, data)
4427
4428 logger.info("EAP message: M1 - Too long attribute values")
4429 data = b'\x0202:00:00:00:00:00'
4430 data += b'\x10\x11\x00\x21' + 33 * b'\x00'
4431 data += b'\x10\x45\x00\x21' + 33 * b'\x00'
4432 data += b'\x10\x42\x00\x21' + 33 * b'\x00'
4433 data += b'\x10\x24\x00\x21' + 33 * b'\x00'
4434 data += b'\x10\x23\x00\x21' + 33 * b'\x00'
4435 data += b'\x10\x21\x00\x41' + 65 * b'\x00'
4436 data += b'\x10\x49\x00\x09\x00\x37\x2a\x05\x02\x00\x00\x05\x00'
4437 send_wlanevent(url, uuid, data)
4438
4439 logger.info("EAP message: M1 missing UUID-E")
4440 data = b'\x0202:00:00:00:00:00'
4441 data += b'\x10\x22\x00\x01\x04'
4442 send_wlanevent(url, uuid, data)
4443
4444 logger.info("EAP message: M1 missing MAC Address")
4445 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4446 send_wlanevent(url, uuid, data)
4447
4448 logger.info("EAP message: M1 missing Enrollee Nonce")
4449 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4450 send_wlanevent(url, uuid, data)
4451
4452 logger.info("EAP message: M1 missing Public Key")
4453 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4454 send_wlanevent(url, uuid, data)
4455
4456 logger.info("EAP message: M1 missing Authentication Type flags")
4457 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4458 send_wlanevent(url, uuid, data)
4459
4460 logger.info("EAP message: M1 missing Encryption Type Flags")
4461 data += b'\x10\x04\x00\x02\x00\x00'
4462 send_wlanevent(url, uuid, data)
4463
4464 logger.info("EAP message: M1 missing Connection Type flags")
4465 data += b'\x10\x10\x00\x02\x00\x00'
4466 send_wlanevent(url, uuid, data)
4467
4468 logger.info("EAP message: M1 missing Config Methods")
4469 data += b'\x10\x0d\x00\x01\x00'
4470 send_wlanevent(url, uuid, data)
4471
4472 logger.info("EAP message: M1 missing Wi-Fi Protected Setup State")
4473 data += b'\x10\x08\x00\x02\x00\x00'
4474 send_wlanevent(url, uuid, data)
4475
4476 logger.info("EAP message: M1 missing Manufacturer")
4477 data += b'\x10\x44\x00\x01\x00'
4478 send_wlanevent(url, uuid, data)
4479
4480 logger.info("EAP message: M1 missing Model Name")
4481 data += b'\x10\x21\x00\x00'
4482 send_wlanevent(url, uuid, data)
4483
4484 logger.info("EAP message: M1 missing Model Number")
4485 data += b'\x10\x23\x00\x00'
4486 send_wlanevent(url, uuid, data)
4487
4488 logger.info("EAP message: M1 missing Serial Number")
4489 data += b'\x10\x24\x00\x00'
4490 send_wlanevent(url, uuid, data)
4491
4492 logger.info("EAP message: M1 missing Primary Device Type")
4493 data += b'\x10\x42\x00\x00'
4494 send_wlanevent(url, uuid, data)
4495
4496 logger.info("EAP message: M1 missing Device Name")
4497 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4498 send_wlanevent(url, uuid, data)
4499
4500 logger.info("EAP message: M1 missing RF Bands")
4501 data += b'\x10\x11\x00\x00'
4502 send_wlanevent(url, uuid, data)
4503
4504 logger.info("EAP message: M1 missing Association State")
4505 data += b'\x10\x3c\x00\x01\x00'
4506 send_wlanevent(url, uuid, data)
4507
4508 logger.info("EAP message: M1 missing Device Password ID")
4509 data += b'\x10\x02\x00\x02\x00\x00'
4510 send_wlanevent(url, uuid, data)
4511
4512 logger.info("EAP message: M1 missing Configuration Error")
4513 data += b'\x10\x12\x00\x02\x00\x00'
4514 send_wlanevent(url, uuid, data)
4515
4516 logger.info("EAP message: M1 missing OS Version")
4517 data += b'\x10\x09\x00\x02\x00\x00'
4518 send_wlanevent(url, uuid, data)
4519
4520 logger.info("Check max concurrent requests")
4521 addr = (url.hostname, url.port)
4522 socks = {}
4523 for i in range(20):
4524 socks[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4525 socket.IPPROTO_TCP)
4526 socks[i].settimeout(10)
4527 socks[i].connect(addr)
4528 for i in range(20):
4529 socks[i].send(b"GET / HTTP/1.1\r\n\r\n")
4530 count = 0
4531 for i in range(20):
4532 try:
4533 res = socks[i].recv(100).decode()
4534 if "HTTP/1" in res:
4535 count += 1
4536 else:
4537 logger.info("recv[%d]: len=%d" % (i, len(res)))
4538 except:
4539 pass
4540 socks[i].close()
4541 logger.info("%d concurrent HTTP GET operations returned response" % count)
4542 if count < 8:
4543 raise Exception("Too few concurrent HTTP connections accepted")
4544
4545 logger.info("OOM in HTTP server")
4546 for func in ["http_request_init", "httpread_create",
4547 "eloop_register_timeout;httpread_create",
4548 "eloop_sock_table_add_sock;?eloop_register_sock;httpread_create",
4549 "httpread_hdr_analyze"]:
4550 with alloc_fail(dev[0], 1, func):
4551 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4552 socket.IPPROTO_TCP)
4553 sock.connect(addr)
4554 sock.send(b"GET / HTTP/1.1\r\n\r\n")
4555 try:
4556 sock.recv(100)
4557 except:
4558 pass
4559 sock.close()
4560
4561 logger.info("Invalid HTTP header")
4562 for req in [" GET / HTTP/1.1\r\n\r\n",
4563 "HTTP/1.1 200 OK\r\n\r\n",
4564 "HTTP/\r\n\r\n",
4565 "GET %%a%aa% HTTP/1.1\r\n\r\n",
4566 "GET / HTTP/1.1\r\n FOO\r\n\r\n",
4567 "NOTIFY / HTTP/1.1\r\n" + 4097*'a' + '\r\n\r\n',
4568 "NOTIFY / HTTP/1.1\r\n\r\n" + 8193*'a',
4569 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n foo\r\n",
4570 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n1\r\nfoo\r\n",
4571 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\n",
4572 "POST / HTTP/1.1\r\nTransfer-Encoding: CHUNKED\r\n\r\n0\r\naa\ra\r\n\ra"]:
4573 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4574 socket.IPPROTO_TCP)
4575 sock.settimeout(0.1)
4576 sock.connect(addr)
4577 sock.send(req.encode())
4578 try:
4579 sock.recv(100)
4580 except:
4581 pass
4582 sock.close()
4583
4584 with alloc_fail(dev[0], 2, "httpread_read_handler"):
4585 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4586 socket.IPPROTO_TCP)
4587 sock.connect(addr)
4588 sock.send(b"NOTIFY / HTTP/1.1\r\n\r\n" + 4500 * b'a')
4589 try:
4590 sock.recv(100)
4591 except:
4592 pass
4593 sock.close()
4594
4595 conn = HTTPConnection(url.netloc)
4596 payload = '<foo'
4597 headers = {"Content-type": 'text/xml; charset="utf-8"',
4598 "Server": "Unspecified, UPnP/1.0, Unspecified",
4599 "HOST": url.netloc,
4600 "NT": "upnp:event",
4601 "SID": "uuid:" + uuid,
4602 "SEQ": "0",
4603 "Content-Length": str(len(payload))}
4604 conn.request("NOTIFY", url.path, payload, headers)
4605 resp = conn.getresponse()
4606 if resp.status != 200:
4607 raise Exception("Unexpected HTTP response: %d" % resp.status)
4608
4609 conn = HTTPConnection(url.netloc)
4610 payload = '<WLANEvent foo></WLANEvent>'
4611 headers = {"Content-type": 'text/xml; charset="utf-8"',
4612 "Server": "Unspecified, UPnP/1.0, Unspecified",
4613 "HOST": url.netloc,
4614 "NT": "upnp:event",
4615 "SID": "uuid:" + uuid,
4616 "SEQ": "0",
4617 "Content-Length": str(len(payload))}
4618 conn.request("NOTIFY", url.path, payload, headers)
4619 resp = conn.getresponse()
4620 if resp.status != 200:
4621 raise Exception("Unexpected HTTP response: %d" % resp.status)
4622
4623 with alloc_fail(dev[0], 1, "xml_get_first_item"):
4624 send_wlanevent(url, uuid, b'')
4625
4626 with alloc_fail(dev[0], 1, "wpabuf_alloc_ext_data;xml_get_base64_item"):
4627 send_wlanevent(url, uuid, b'foo')
4628
4629 for func in ["wps_init",
4630 "wps_process_manufacturer",
4631 "wps_process_model_name",
4632 "wps_process_model_number",
4633 "wps_process_serial_number",
4634 "wps_process_dev_name"]:
4635 with alloc_fail(dev[0], 1, func):
4636 send_wlanevent(url, uuid, m1)
4637
4638 with alloc_fail(dev[0], 1, "wps_er_http_resp_ok"):
4639 send_wlanevent(url, uuid, m1, no_response=True)
4640
4641 with alloc_fail(dev[0], 1, "wps_er_http_resp_not_found"):
4642 url2 = urlparse(wps_event_url.replace('/event/', '/notfound/'))
4643 send_wlanevent(url2, uuid, m1, no_response=True)
4644
4645 logger.info("EAP message: M1")
4646 data = b'\x0202:11:22:00:00:00'
4647 data += b'\x10\x22\x00\x01\x04'
4648 data += b'\x10\x47\x00\x10' + 16 * b'\x00'
4649 data += b'\x10\x20\x00\x06\x02\x00\x00\x00\x00\x00'
4650 data += b'\x10\x1a\x00\x10' + 16 * b'\x00'
4651 data += b'\x10\x32\x00\xc0' + 192 * b'\x00'
4652 data += b'\x10\x04\x00\x02\x00\x00'
4653 data += b'\x10\x10\x00\x02\x00\x00'
4654 data += b'\x10\x0d\x00\x01\x00'
4655 data += b'\x10\x08\x00\x02\x00\x00'
4656 data += b'\x10\x44\x00\x01\x00'
4657 data += b'\x10\x21\x00\x00'
4658 data += b'\x10\x23\x00\x00'
4659 data += b'\x10\x24\x00\x00'
4660 data += b'\x10\x42\x00\x00'
4661 data += b'\x10\x54\x00\x08' + 8 * b'\x00'
4662 data += b'\x10\x11\x00\x00'
4663 data += b'\x10\x3c\x00\x01\x00'
4664 data += b'\x10\x02\x00\x02\x00\x00'
4665 data += b'\x10\x12\x00\x02\x00\x00'
4666 data += b'\x10\x09\x00\x02\x00\x00'
4667 data += b'\x10\x2d\x00\x04\x00\x00\x00\x00'
4668 dev[0].dump_monitor()
4669 with alloc_fail(dev[0], 1, "wps_er_add_sta_data"):
4670 send_wlanevent(url, uuid, data)
4671 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=0.1)
4672 if ev is not None:
4673 raise Exception("Unexpected enrollee add event")
4674 send_wlanevent(url, uuid, data)
4675 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=2)
4676 if ev is None:
4677 raise Exception("Enrollee add event not seen")
4678
4679 with alloc_fail(dev[0], 1,
4680 "base64_gen_encode;?base64_encode;wps_er_soap_hdr"):
4681 send_wlanevent(url, uuid, data)
4682
4683 with alloc_fail(dev[0], 1, "wpabuf_alloc;wps_er_soap_hdr"):
4684 send_wlanevent(url, uuid, data)
4685
4686 with alloc_fail(dev[0], 1, "http_client_url_parse;wps_er_sta_send_msg"):
4687 send_wlanevent(url, uuid, data)
4688
4689 with alloc_fail(dev[0], 1, "http_client_addr;wps_er_sta_send_msg"):
4690 send_wlanevent(url, uuid, data)
4691
4692 def test_ap_wps_er_http_proto_no_event_sub_url(dev, apdev):
4693 """WPS ER HTTP protocol testing - no eventSubURL"""
4694 class WPSAPHTTPServer_no_event_sub_url(WPSAPHTTPServer):
4695 def handle_upnp_info(self):
4696 self.wfile.write(gen_upnp_info(eventSubURL=None))
4697 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_event_sub_url,
4698 no_event_url=True)
4699
4700 def test_ap_wps_er_http_proto_event_sub_url_dns(dev, apdev):
4701 """WPS ER HTTP protocol testing - DNS name in eventSubURL"""
4702 class WPSAPHTTPServer_event_sub_url_dns(WPSAPHTTPServer):
4703 def handle_upnp_info(self):
4704 self.wfile.write(gen_upnp_info(eventSubURL='http://example.com/wps_event'))
4705 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_event_sub_url_dns,
4706 no_event_url=True)
4707
4708 def test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4709 """WPS ER HTTP protocol testing - subscribe OOM"""
4710 try:
4711 _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev)
4712 finally:
4713 dev[0].request("WPS_ER_STOP")
4714
4715 def _test_ap_wps_er_http_proto_subscribe_oom(dev, apdev):
4716 tests = [(1, "http_client_url_parse"),
4717 (1, "wpabuf_alloc;wps_er_subscribe"),
4718 (1, "http_client_addr"),
4719 (1, "eloop_sock_table_add_sock;?eloop_register_sock;http_client_addr"),
4720 (1, "eloop_register_timeout;http_client_addr")]
4721 for count, func in tests:
4722 with alloc_fail(dev[0], count, func):
4723 server, sock = wps_er_start(dev[0], WPSAPHTTPServer)
4724 server.handle_request()
4725 server.handle_request()
4726 wps_er_stop(dev[0], sock, server, on_alloc_fail=True)
4727
4728 def test_ap_wps_er_http_proto_no_sid(dev, apdev):
4729 """WPS ER HTTP protocol testing - no SID"""
4730 class WPSAPHTTPServer_no_sid(WPSAPHTTPServer):
4731 def handle_wps_event(self):
4732 self.wfile.write(gen_wps_event(sid=None))
4733 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_sid)
4734
4735 def test_ap_wps_er_http_proto_invalid_sid_no_uuid(dev, apdev):
4736 """WPS ER HTTP protocol testing - invalid SID - no UUID"""
4737 class WPSAPHTTPServer_invalid_sid_no_uuid(WPSAPHTTPServer):
4738 def handle_wps_event(self):
4739 self.wfile.write(gen_wps_event(sid='FOO'))
4740 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_no_uuid)
4741
4742 def test_ap_wps_er_http_proto_invalid_sid_uuid(dev, apdev):
4743 """WPS ER HTTP protocol testing - invalid SID UUID"""
4744 class WPSAPHTTPServer_invalid_sid_uuid(WPSAPHTTPServer):
4745 def handle_wps_event(self):
4746 self.wfile.write(gen_wps_event(sid='uuid:FOO'))
4747 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_sid_uuid)
4748
4749 def test_ap_wps_er_http_proto_subscribe_failing(dev, apdev):
4750 """WPS ER HTTP protocol testing - SUBSCRIBE failing"""
4751 class WPSAPHTTPServer_fail_subscribe(WPSAPHTTPServer):
4752 def handle_wps_event(self):
4753 payload = ""
4754 hdr = 'HTTP/1.1 404 Not Found\r\n' + \
4755 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4756 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4757 'Connection: close\r\n' + \
4758 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4759 'Timeout: Second-1801\r\n' + \
4760 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4761 self.wfile.write((hdr + payload).encode())
4762 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_fail_subscribe)
4763
4764 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4765 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4766 class WPSAPHTTPServer_subscribe_invalid_response(WPSAPHTTPServer):
4767 def handle_wps_event(self):
4768 payload = ""
4769 hdr = 'HTTP/1.1 FOO\r\n' + \
4770 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4771 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4772 'Connection: close\r\n' + \
4773 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4774 'Timeout: Second-1801\r\n' + \
4775 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4776 self.wfile.write((hdr + payload).encode())
4777 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_subscribe_invalid_response)
4778
4779 def test_ap_wps_er_http_proto_subscribe_invalid_response(dev, apdev):
4780 """WPS ER HTTP protocol testing - SUBSCRIBE and invalid response"""
4781 class WPSAPHTTPServer_invalid_m1(WPSAPHTTPServer):
4782 def handle_wps_control(self):
4783 payload = '''<?xml version="1.0"?>
4784 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
4785 <s:Body>
4786 <u:GetDeviceInfoResponse xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">
4787 <NewDeviceInfo>Rk9P</NewDeviceInfo>
4788 </u:GetDeviceInfoResponse>
4789 </s:Body>
4790 </s:Envelope>
4791 '''
4792 self.wfile.write(gen_wps_control(payload_override=payload))
4793 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_m1, no_event_url=True)
4794
4795 def test_ap_wps_er_http_proto_upnp_info_no_device(dev, apdev):
4796 """WPS ER HTTP protocol testing - No device in UPnP info"""
4797 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4798 def handle_upnp_info(self):
4799 payload = '''<?xml version="1.0"?>
4800 <root xmlns="urn:schemas-upnp-org:device-1-0">
4801 <specVersion>
4802 <major>1</major>
4803 <minor>0</minor>
4804 </specVersion>
4805 </root>
4806 '''
4807 hdr = 'HTTP/1.1 200 OK\r\n' + \
4808 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4809 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4810 'Connection: close\r\n' + \
4811 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4812 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4813 self.wfile.write((hdr + payload).encode())
4814 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4815
4816 def test_ap_wps_er_http_proto_upnp_info_no_device_type(dev, apdev):
4817 """WPS ER HTTP protocol testing - No deviceType in UPnP info"""
4818 class WPSAPHTTPServer_no_device(WPSAPHTTPServer):
4819 def handle_upnp_info(self):
4820 payload = '''<?xml version="1.0"?>
4821 <root xmlns="urn:schemas-upnp-org:device-1-0">
4822 <specVersion>
4823 <major>1</major>
4824 <minor>0</minor>
4825 </specVersion>
4826 <device>
4827 </device>
4828 </root>
4829 '''
4830 hdr = 'HTTP/1.1 200 OK\r\n' + \
4831 'Content-Type: text/xml; charset="utf-8"\r\n' + \
4832 'Server: Unspecified, UPnP/1.0, Unspecified\r\n' + \
4833 'Connection: close\r\n' + \
4834 'Content-Length: ' + str(len(payload)) + '\r\n' + \
4835 'Date: Sat, 15 Aug 2015 18:55:08 GMT\r\n\r\n'
4836 self.wfile.write((hdr + payload).encode())
4837 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_device, no_event_url=True)
4838
4839 def test_ap_wps_er_http_proto_upnp_info_invalid_udn_uuid(dev, apdev):
4840 """WPS ER HTTP protocol testing - Invalid UDN UUID"""
4841 class WPSAPHTTPServer_invalid_udn_uuid(WPSAPHTTPServer):
4842 def handle_upnp_info(self):
4843 self.wfile.write(gen_upnp_info(udn='uuid:foo'))
4844 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_invalid_udn_uuid)
4845
4846 def test_ap_wps_er_http_proto_no_control_url(dev, apdev):
4847 """WPS ER HTTP protocol testing - no controlURL"""
4848 class WPSAPHTTPServer_no_control_url(WPSAPHTTPServer):
4849 def handle_upnp_info(self):
4850 self.wfile.write(gen_upnp_info(controlURL=None))
4851 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_no_control_url,
4852 no_event_url=True)
4853
4854 def test_ap_wps_er_http_proto_control_url_dns(dev, apdev):
4855 """WPS ER HTTP protocol testing - DNS name in controlURL"""
4856 class WPSAPHTTPServer_control_url_dns(WPSAPHTTPServer):
4857 def handle_upnp_info(self):
4858 self.wfile.write(gen_upnp_info(controlURL='http://example.com/wps_control'))
4859 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_control_url_dns,
4860 no_event_url=True)
4861
4862 def test_ap_wps_http_timeout(dev, apdev):
4863 """WPS AP/ER and HTTP timeout"""
4864 try:
4865 _test_ap_wps_http_timeout(dev, apdev)
4866 finally:
4867 dev[0].request("WPS_ER_STOP")
4868
4869 def _test_ap_wps_http_timeout(dev, apdev):
4870 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
4871 add_ssdp_ap(apdev[0], ap_uuid)
4872
4873 location = ssdp_get_location(ap_uuid)
4874 url = urlparse(location)
4875 addr = (url.hostname, url.port)
4876 logger.debug("Open HTTP connection to hostapd, but do not complete request")
4877 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
4878 socket.IPPROTO_TCP)
4879 sock.connect(addr)
4880 sock.send(b"G")
4881
4882 class DummyServer(StreamRequestHandler):
4883 def handle(self):
4884 logger.debug("DummyServer - start 31 sec wait")
4885 time.sleep(31)
4886 logger.debug("DummyServer - wait done")
4887
4888 logger.debug("Start WPS ER")
4889 server, sock2 = wps_er_start(dev[0], DummyServer, max_age=40,
4890 wait_m_search=True)
4891
4892 logger.debug("Start server to accept, but not complete, HTTP connection from WPS ER")
4893 # This will wait for 31 seconds..
4894 server.handle_request()
4895
4896 logger.debug("Complete HTTP connection with hostapd (that should have already closed the connection)")
4897 try:
4898 sock.send("ET / HTTP/1.1\r\n\r\n")
4899 res = sock.recv(100)
4900 sock.close()
4901 except:
4902 pass
4903
4904 def test_ap_wps_er_url_parse(dev, apdev):
4905 """WPS ER and URL parsing special cases"""
4906 try:
4907 _test_ap_wps_er_url_parse(dev, apdev)
4908 finally:
4909 dev[0].request("WPS_ER_STOP")
4910
4911 def _test_ap_wps_er_url_parse(dev, apdev):
4912 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
4913 sock.settimeout(1)
4914 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4915 sock.bind(("239.255.255.250", 1900))
4916 dev[0].request("WPS_ER_START ifname=lo")
4917 (msg, addr) = sock.recvfrom(1000)
4918 msg = msg.decode()
4919 logger.debug("Received SSDP message from %s: %s" % (str(addr), msg))
4920 if "M-SEARCH" not in msg:
4921 raise Exception("Not an M-SEARCH")
4922 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)
4923 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4924 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)
4925 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4926 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)
4927 ev = dev[0].wait_event(["WPS-ER-AP-REMOVE"], timeout=2)
4928
4929 sock.close()
4930
4931 def test_ap_wps_er_link_update(dev, apdev):
4932 """WPS ER and link update special cases"""
4933 class WPSAPHTTPServer_link_update(WPSAPHTTPServer):
4934 def handle_upnp_info(self):
4935 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4936 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update)
4937
4938 class WPSAPHTTPServer_link_update2(WPSAPHTTPServer):
4939 def handle_others(self, data):
4940 if "GET / " in data:
4941 self.wfile.write(gen_upnp_info(controlURL='/wps_control'))
4942 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_link_update2,
4943 location_url='http://127.0.0.1:12345')
4944
4945 def test_ap_wps_er_http_client(dev, apdev):
4946 """WPS ER and HTTP client special cases"""
4947 with alloc_fail(dev[0], 1, "http_link_update"):
4948 run_wps_er_proto_test(dev[0], WPSAPHTTPServer)
4949
4950 with alloc_fail(dev[0], 1, "wpabuf_alloc;http_client_url"):
4951 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4952
4953 with alloc_fail(dev[0], 1, "httpread_create;http_client_tx_ready"):
4954 run_wps_er_proto_test(dev[0], WPSAPHTTPServer, no_event_url=True)
4955
4956 class WPSAPHTTPServer_req_as_resp(WPSAPHTTPServer):
4957 def handle_upnp_info(self):
4958 self.wfile.write(b"GET / HTTP/1.1\r\n\r\n")
4959 run_wps_er_proto_test(dev[0], WPSAPHTTPServer_req_as_resp,
4960 no_event_url=True)
4961
4962 def test_ap_wps_init_oom(dev, apdev):
4963 """wps_init OOM cases"""
4964 ssid = "test-wps"
4965 appin = "12345670"
4966 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
4967 "ap_pin": appin}
4968 hapd = hostapd.add_ap(apdev[0], params)
4969 pin = dev[0].wps_read_pin()
4970
4971 with alloc_fail(hapd, 1, "wps_init"):
4972 hapd.request("WPS_PIN any " + pin)
4973 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4974 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4975 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4976 if ev is None:
4977 raise Exception("No EAP failure reported")
4978 dev[0].request("WPS_CANCEL")
4979
4980 with alloc_fail(dev[0], 2, "wps_init"):
4981 hapd.request("WPS_PIN any " + pin)
4982 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4983 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
4984 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4985 if ev is None:
4986 raise Exception("No EAP failure reported")
4987 dev[0].request("WPS_CANCEL")
4988
4989 with alloc_fail(dev[0], 2, "wps_init"):
4990 hapd.request("WPS_PBC")
4991 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
4992 dev[0].request("WPS_PBC %s" % (apdev[0]['bssid']))
4993 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
4994 if ev is None:
4995 raise Exception("No EAP failure reported")
4996 dev[0].request("WPS_CANCEL")
4997
4998 dev[0].dump_monitor()
4999 new_ssid = "wps-new-ssid"
5000 new_passphrase = "1234567890"
5001 with alloc_fail(dev[0], 3, "wps_init"):
5002 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
5003 new_passphrase, no_wait=True)
5004 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5005 if ev is None:
5006 raise Exception("No EAP failure reported")
5007
5008 dev[0].flush_scan_cache()
5009
5010 @remote_compatible
5011 def test_ap_wps_invalid_assoc_req_elem(dev, apdev):
5012 """WPS and invalid IE in Association Request frame"""
5013 ssid = "test-wps"
5014 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5015 hapd = hostapd.add_ap(apdev[0], params)
5016 pin = "12345670"
5017 hapd.request("WPS_PIN any " + pin)
5018 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5019 try:
5020 dev[0].request("VENDOR_ELEM_ADD 13 dd050050f20410")
5021 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5022 for i in range(5):
5023 ev = hapd.wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=10)
5024 if ev and "vendor=14122" in ev:
5025 break
5026 if ev is None or "vendor=14122" not in ev:
5027 raise Exception("EAP-WSC not started")
5028 dev[0].request("WPS_CANCEL")
5029 finally:
5030 dev[0].request("VENDOR_ELEM_REMOVE 13 *")
5031
5032 def test_ap_wps_pbc_pin_mismatch(dev, apdev):
5033 """WPS PBC/PIN mismatch"""
5034 ssid = "test-wps"
5035 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5036 hapd = hostapd.add_ap(apdev[0], params)
5037 hapd.request("SET wps_version_number 0x10")
5038 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5039 hapd.request("WPS_PBC")
5040 pin = dev[0].wps_read_pin()
5041 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5042 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5043 if ev is None:
5044 raise Exception("Scan did not complete")
5045 dev[0].request("WPS_CANCEL")
5046
5047 hapd.request("WPS_CANCEL")
5048 dev[0].flush_scan_cache()
5049
5050 @remote_compatible
5051 def test_ap_wps_ie_invalid(dev, apdev):
5052 """WPS PIN attempt with AP that has invalid WSC IE"""
5053 ssid = "test-wps"
5054 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5055 "vendor_elements": "dd050050f20410"}
5056 hapd = hostapd.add_ap(apdev[0], params)
5057 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
5058 hostapd.add_ap(apdev[1], params)
5059 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5060 pin = dev[0].wps_read_pin()
5061 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5062 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5063 if ev is None:
5064 raise Exception("Scan did not complete")
5065 dev[0].request("WPS_CANCEL")
5066
5067 @remote_compatible
5068 def test_ap_wps_scan_prio_order(dev, apdev):
5069 """WPS scan priority ordering"""
5070 ssid = "test-wps"
5071 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5072 hapd = hostapd.add_ap(apdev[0], params)
5073 params = {'ssid': "another", "vendor_elements": "dd050050f20410"}
5074 hostapd.add_ap(apdev[1], params)
5075 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5076 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5077 pin = dev[0].wps_read_pin()
5078 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5079 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"])
5080 if ev is None:
5081 raise Exception("Scan did not complete")
5082 dev[0].request("WPS_CANCEL")
5083
5084 def test_ap_wps_probe_req_ie_oom(dev, apdev):
5085 """WPS ProbeReq IE OOM"""
5086 ssid = "test-wps"
5087 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5088 hapd = hostapd.add_ap(apdev[0], params)
5089 pin = dev[0].wps_read_pin()
5090 hapd.request("WPS_PIN any " + pin)
5091 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5092 with alloc_fail(dev[0], 1, "wps_build_probe_req_ie"):
5093 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5094 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5095 if ev is None:
5096 raise Exception("Association not seen")
5097 dev[0].request("WPS_CANCEL")
5098 dev[0].wait_disconnected()
5099
5100 with alloc_fail(dev[0], 1, "wps_ie_encapsulate"):
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 hapd.disable()
5107 dev[0].request("REMOVE_NETWORK all")
5108 dev[0].wait_disconnected()
5109 time.sleep(0.2)
5110 dev[0].flush_scan_cache()
5111
5112 def test_ap_wps_assoc_req_ie_oom(dev, apdev):
5113 """WPS AssocReq IE OOM"""
5114 ssid = "test-wps"
5115 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5116 hapd = hostapd.add_ap(apdev[0], params)
5117 pin = dev[0].wps_read_pin()
5118 hapd.request("WPS_PIN any " + pin)
5119 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5120 with alloc_fail(dev[0], 1, "wps_build_assoc_req_ie"):
5121 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5122 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5123 if ev is None:
5124 raise Exception("Association not seen")
5125 dev[0].request("WPS_CANCEL")
5126
5127 def test_ap_wps_assoc_resp_ie_oom(dev, apdev):
5128 """WPS AssocResp IE OOM"""
5129 ssid = "test-wps"
5130 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2"}
5131 hapd = hostapd.add_ap(apdev[0], params)
5132 pin = dev[0].wps_read_pin()
5133 hapd.request("WPS_PIN any " + pin)
5134 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5135 with alloc_fail(hapd, 1, "wps_build_assoc_resp_ie"):
5136 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
5137 ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=10)
5138 if ev is None:
5139 raise Exception("Association not seen")
5140 dev[0].request("WPS_CANCEL")
5141
5142 @remote_compatible
5143 def test_ap_wps_bss_info_errors(dev, apdev):
5144 """WPS BSS info errors"""
5145 params = {"ssid": "1",
5146 "vendor_elements": "dd0e0050f20410440001ff101100010a"}
5147 hostapd.add_ap(apdev[0], params)
5148 params = {'ssid': "2", "vendor_elements": "dd050050f20410"}
5149 hostapd.add_ap(apdev[1], params)
5150 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5151 dev[0].scan_for_bss(apdev[1]['bssid'], freq="2412")
5152 bss = dev[0].get_bss(apdev[0]['bssid'])
5153 logger.info("BSS: " + str(bss))
5154 if "wps_state" in bss:
5155 raise Exception("Unexpected wps_state in BSS info")
5156 if 'wps_device_name' not in bss:
5157 raise Exception("No wps_device_name in BSS info")
5158 if bss['wps_device_name'] != '_':
5159 raise Exception("Unexpected wps_device_name value")
5160 bss = dev[0].get_bss(apdev[1]['bssid'])
5161 logger.info("BSS: " + str(bss))
5162
5163 with alloc_fail(dev[0], 1, "=wps_attr_text"):
5164 bss = dev[0].get_bss(apdev[0]['bssid'])
5165 logger.info("BSS(OOM): " + str(bss))
5166
5167 def wps_run_pbc_fail_ap(apdev, dev, hapd):
5168 hapd.request("WPS_PBC")
5169 dev.scan_for_bss(apdev['bssid'], freq="2412")
5170 dev.request("WPS_PBC " + apdev['bssid'])
5171 ev = dev.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5172 if ev is None:
5173 raise Exception("No EAP failure reported")
5174 dev.request("WPS_CANCEL")
5175 dev.wait_disconnected()
5176 for i in range(5):
5177 try:
5178 dev.flush_scan_cache()
5179 break
5180 except Exception as e:
5181 if str(e).startswith("Failed to trigger scan"):
5182 # Try again
5183 time.sleep(1)
5184 else:
5185 raise
5186
5187 def wps_run_pbc_fail(apdev, dev):
5188 hapd = wps_start_ap(apdev)
5189 wps_run_pbc_fail_ap(apdev, dev, hapd)
5190
5191 @remote_compatible
5192 def test_ap_wps_pk_oom(dev, apdev):
5193 """WPS and public key OOM"""
5194 with alloc_fail(dev[0], 1, "wps_build_public_key"):
5195 wps_run_pbc_fail(apdev[0], dev[0])
5196
5197 @remote_compatible
5198 def test_ap_wps_pk_oom_ap(dev, apdev):
5199 """WPS and public key OOM on AP"""
5200 hapd = wps_start_ap(apdev[0])
5201 with alloc_fail(hapd, 1, "wps_build_public_key"):
5202 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5203
5204 @remote_compatible
5205 def test_ap_wps_encr_oom_ap(dev, apdev):
5206 """WPS and encrypted settings decryption OOM on AP"""
5207 hapd = wps_start_ap(apdev[0])
5208 pin = dev[0].wps_read_pin()
5209 hapd.request("WPS_PIN any " + pin)
5210 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5211 with alloc_fail(hapd, 1, "wps_decrypt_encr_settings"):
5212 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
5213 ev = hapd.wait_event(["WPS-FAIL"], timeout=10)
5214 if ev is None:
5215 raise Exception("No WPS-FAIL reported")
5216 dev[0].request("WPS_CANCEL")
5217 dev[0].wait_disconnected()
5218
5219 @remote_compatible
5220 def test_ap_wps_encr_no_random_ap(dev, apdev):
5221 """WPS and no random data available for encryption on AP"""
5222 hapd = wps_start_ap(apdev[0])
5223 with fail_test(hapd, 1, "os_get_random;wps_build_encr_settings"):
5224 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5225
5226 @remote_compatible
5227 def test_ap_wps_e_hash_no_random_sta(dev, apdev):
5228 """WPS and no random data available for e-hash on STA"""
5229 with fail_test(dev[0], 1, "os_get_random;wps_build_e_hash"):
5230 wps_run_pbc_fail(apdev[0], dev[0])
5231
5232 @remote_compatible
5233 def test_ap_wps_m1_no_random(dev, apdev):
5234 """WPS and no random for M1 on STA"""
5235 with fail_test(dev[0], 1, "os_get_random;wps_build_m1"):
5236 wps_run_pbc_fail(apdev[0], dev[0])
5237
5238 @remote_compatible
5239 def test_ap_wps_m1_oom(dev, apdev):
5240 """WPS and OOM for M1 on STA"""
5241 with alloc_fail(dev[0], 1, "wps_build_m1"):
5242 wps_run_pbc_fail(apdev[0], dev[0])
5243
5244 @remote_compatible
5245 def test_ap_wps_m3_oom(dev, apdev):
5246 """WPS and OOM for M3 on STA"""
5247 with alloc_fail(dev[0], 1, "wps_build_m3"):
5248 wps_run_pbc_fail(apdev[0], dev[0])
5249
5250 @remote_compatible
5251 def test_ap_wps_m5_oom(dev, apdev):
5252 """WPS and OOM for M5 on STA"""
5253 hapd = wps_start_ap(apdev[0])
5254 hapd.request("WPS_PBC")
5255 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5256 for i in range(1, 3):
5257 with alloc_fail(dev[0], i, "wps_build_m5"):
5258 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5259 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5260 if ev is None:
5261 raise Exception("No EAP failure reported")
5262 dev[0].request("WPS_CANCEL")
5263 dev[0].wait_disconnected()
5264 dev[0].flush_scan_cache()
5265
5266 @remote_compatible
5267 def test_ap_wps_m5_no_random(dev, apdev):
5268 """WPS and no random for M5 on STA"""
5269 with fail_test(dev[0], 1,
5270 "os_get_random;wps_build_encr_settings;wps_build_m5"):
5271 wps_run_pbc_fail(apdev[0], dev[0])
5272
5273 @remote_compatible
5274 def test_ap_wps_m7_oom(dev, apdev):
5275 """WPS and OOM for M7 on STA"""
5276 hapd = wps_start_ap(apdev[0])
5277 hapd.request("WPS_PBC")
5278 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5279 for i in range(1, 3):
5280 with alloc_fail(dev[0], i, "wps_build_m7"):
5281 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
5282 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5283 if ev is None:
5284 raise Exception("No EAP failure reported")
5285 dev[0].request("WPS_CANCEL")
5286 dev[0].wait_disconnected()
5287 dev[0].flush_scan_cache()
5288
5289 @remote_compatible
5290 def test_ap_wps_m7_no_random(dev, apdev):
5291 """WPS and no random for M7 on STA"""
5292 with fail_test(dev[0], 1,
5293 "os_get_random;wps_build_encr_settings;wps_build_m7"):
5294 wps_run_pbc_fail(apdev[0], dev[0])
5295
5296 @remote_compatible
5297 def test_ap_wps_wsc_done_oom(dev, apdev):
5298 """WPS and OOM for WSC_Done on STA"""
5299 with alloc_fail(dev[0], 1, "wps_build_wsc_done"):
5300 wps_run_pbc_fail(apdev[0], dev[0])
5301
5302 def test_ap_wps_random_psk_fail(dev, apdev):
5303 """WPS and no random for PSK on AP"""
5304 ssid = "test-wps"
5305 pskfile = "/tmp/ap_wps_per_enrollee_psk.psk_file"
5306 appin = "12345670"
5307 try:
5308 os.remove(pskfile)
5309 except:
5310 pass
5311
5312 try:
5313 with open(pskfile, "w") as f:
5314 f.write("# WPA PSKs\n")
5315
5316 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5317 "wpa": "2", "wpa_key_mgmt": "WPA-PSK",
5318 "rsn_pairwise": "CCMP", "ap_pin": appin,
5319 "wpa_psk_file": pskfile}
5320 hapd = hostapd.add_ap(apdev[0], params)
5321
5322 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
5323 with fail_test(hapd, 1, "os_get_random;wps_build_cred_network_key"):
5324 dev[0].request("WPS_REG " + apdev[0]['bssid'] + " " + appin)
5325 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=10)
5326 if ev is None:
5327 raise Exception("No EAP failure reported")
5328 dev[0].request("WPS_CANCEL")
5329 dev[0].wait_disconnected()
5330
5331 with fail_test(hapd, 1, "os_get_random;wps_build_cred"):
5332 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5333
5334 with alloc_fail(hapd, 1, "wps_build_cred"):
5335 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5336
5337 with alloc_fail(hapd, 2, "wps_build_cred"):
5338 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
5339 finally:
5340 os.remove(pskfile)
5341
5342 def wps_ext_eap_identity_req(dev, hapd, bssid):
5343 logger.debug("EAP-Identity/Request")
5344 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5345 if ev is None:
5346 raise Exception("Timeout on EAPOL-TX from hostapd")
5347 res = dev.request("EAPOL_RX " + bssid + " " + ev.split(' ')[2])
5348 if "OK" not in res:
5349 raise Exception("EAPOL_RX to wpa_supplicant failed")
5350
5351 def wps_ext_eap_identity_resp(hapd, dev, addr):
5352 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
5353 if ev is None:
5354 raise Exception("Timeout on EAPOL-TX from wpa_supplicant")
5355 res = hapd.request("EAPOL_RX " + addr + " " + ev.split(' ')[2])
5356 if "OK" not in res:
5357 raise Exception("EAPOL_RX to hostapd failed")
5358
5359 def wps_ext_eap_wsc(dst, src, src_addr, msg):
5360 logger.debug(msg)
5361 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5362 if ev is None:
5363 raise Exception("Timeout on EAPOL-TX")
5364 res = dst.request("EAPOL_RX " + src_addr + " " + ev.split(' ')[2])
5365 if "OK" not in res:
5366 raise Exception("EAPOL_RX failed")
5367
5368 def wps_start_ext(apdev, dev, pbc=False, pin=None):
5369 addr = dev.own_addr()
5370 bssid = apdev['bssid']
5371 ssid = "test-wps-conf"
5372 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5373 "wpa_passphrase": "12345678", "wpa": "2",
5374 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
5375 hapd = hostapd.add_ap(apdev, params)
5376
5377 if pbc:
5378 hapd.request("WPS_PBC")
5379 else:
5380 if pin is None:
5381 pin = dev.wps_read_pin()
5382 hapd.request("WPS_PIN any " + pin)
5383 dev.scan_for_bss(bssid, freq="2412")
5384 hapd.request("SET ext_eapol_frame_io 1")
5385 dev.request("SET ext_eapol_frame_io 1")
5386
5387 if pbc:
5388 dev.request("WPS_PBC " + bssid)
5389 else:
5390 dev.request("WPS_PIN " + bssid + " " + pin)
5391 return addr, bssid, hapd
5392
5393 def wps_auth_corrupt(dst, src, addr):
5394 ev = src.wait_event(["EAPOL-TX"], timeout=10)
5395 if ev is None:
5396 raise Exception("Timeout on EAPOL-TX")
5397 src.request("SET ext_eapol_frame_io 0")
5398 dst.request("SET ext_eapol_frame_io 0")
5399 msg = ev.split(' ')[2]
5400 if msg[-24:-16] != '10050008':
5401 raise Exception("Could not find Authenticator attribute")
5402 # Corrupt Authenticator value
5403 msg = msg[:-1] + '%x' % ((int(msg[-1], 16) + 1) % 16)
5404 res = dst.request("EAPOL_RX " + addr + " " + msg)
5405 if "OK" not in res:
5406 raise Exception("EAPOL_RX failed")
5407
5408 def wps_fail_finish(hapd, dev, fail_str):
5409 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5410 if ev is None:
5411 raise Exception("WPS-FAIL not indicated")
5412 if fail_str not in ev:
5413 raise Exception("Unexpected WPS-FAIL value: " + ev)
5414 dev.request("WPS_CANCEL")
5415 dev.wait_disconnected()
5416
5417 def wps_auth_corrupt_from_ap(dev, hapd, bssid, fail_str):
5418 wps_auth_corrupt(dev, hapd, bssid)
5419 wps_fail_finish(hapd, dev, fail_str)
5420
5421 def wps_auth_corrupt_to_ap(dev, hapd, addr, fail_str):
5422 wps_auth_corrupt(hapd, dev, addr)
5423 wps_fail_finish(hapd, dev, fail_str)
5424
5425 def test_ap_wps_authenticator_mismatch_m2(dev, apdev):
5426 """WPS and Authenticator attribute mismatch in M2"""
5427 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5428 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5429 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5430 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5431 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5432 logger.debug("M2")
5433 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=5")
5434
5435 def test_ap_wps_authenticator_mismatch_m3(dev, apdev):
5436 """WPS and Authenticator attribute mismatch in M3"""
5437 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5438 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5439 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5440 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5441 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5442 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5443 logger.debug("M3")
5444 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=7")
5445
5446 def test_ap_wps_authenticator_mismatch_m4(dev, apdev):
5447 """WPS and Authenticator attribute mismatch in M4"""
5448 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5449 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5450 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5451 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5452 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5453 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5454 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5455 logger.debug("M4")
5456 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=8")
5457
5458 def test_ap_wps_authenticator_mismatch_m5(dev, apdev):
5459 """WPS and Authenticator attribute mismatch in M5"""
5460 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5461 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5462 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5463 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5464 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5465 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5466 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5467 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5468 logger.debug("M5")
5469 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=9")
5470
5471 def test_ap_wps_authenticator_mismatch_m6(dev, apdev):
5472 """WPS and Authenticator attribute mismatch in M6"""
5473 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5474 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5475 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5476 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5477 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5478 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5479 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5480 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5481 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5482 logger.debug("M6")
5483 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=10")
5484
5485 def test_ap_wps_authenticator_mismatch_m7(dev, apdev):
5486 """WPS and Authenticator attribute mismatch in M7"""
5487 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5488 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5489 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5490 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5491 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5492 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5493 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5494 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5495 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5496 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5497 logger.debug("M7")
5498 wps_auth_corrupt_to_ap(dev[0], hapd, addr, "msg=11")
5499
5500 def test_ap_wps_authenticator_mismatch_m8(dev, apdev):
5501 """WPS and Authenticator attribute mismatch in M8"""
5502 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5503 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5504 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5505 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5506 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5507 wps_ext_eap_wsc(dev[0], hapd, bssid, "M2")
5508 wps_ext_eap_wsc(hapd, dev[0], addr, "M3")
5509 wps_ext_eap_wsc(dev[0], hapd, bssid, "M4")
5510 wps_ext_eap_wsc(hapd, dev[0], addr, "M5")
5511 wps_ext_eap_wsc(dev[0], hapd, bssid, "M6")
5512 wps_ext_eap_wsc(hapd, dev[0], addr, "M7")
5513 logger.debug("M8")
5514 wps_auth_corrupt_from_ap(dev[0], hapd, bssid, "msg=12")
5515
5516 def test_ap_wps_authenticator_missing_m2(dev, apdev):
5517 """WPS and Authenticator attribute missing from M2"""
5518 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5519 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5520 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5521 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5522 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5523 logger.debug("M2")
5524 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5525 if ev is None:
5526 raise Exception("Timeout on EAPOL-TX")
5527 hapd.request("SET ext_eapol_frame_io 0")
5528 dev[0].request("SET ext_eapol_frame_io 0")
5529 msg = ev.split(' ')[2]
5530 if msg[-24:-16] != '10050008':
5531 raise Exception("Could not find Authenticator attribute")
5532 # Remove Authenticator value
5533 msg = msg[:-24]
5534 mlen = "%04x" % (int(msg[4:8], 16) - 12)
5535 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:]
5536 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5537 if "OK" not in res:
5538 raise Exception("EAPOL_RX failed")
5539 wps_fail_finish(hapd, dev[0], "msg=5")
5540
5541 def test_ap_wps_m2_dev_passwd_id_p2p(dev, apdev):
5542 """WPS and M2 with different Device Password ID (P2P)"""
5543 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5544 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5545 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5546 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5547 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5548 logger.debug("M2")
5549 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5550 if ev is None:
5551 raise Exception("Timeout on EAPOL-TX")
5552 hapd.request("SET ext_eapol_frame_io 0")
5553 dev[0].request("SET ext_eapol_frame_io 0")
5554 msg = ev.split(' ')[2]
5555 if msg[722:730] != '10120002':
5556 raise Exception("Could not find Device Password ID attribute")
5557 # Replace Device Password ID value. This will fail Authenticator check, but
5558 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5559 # log.
5560 msg = msg[0:730] + "0005" + msg[734:]
5561 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5562 if "OK" not in res:
5563 raise Exception("EAPOL_RX failed")
5564 wps_fail_finish(hapd, dev[0], "msg=5")
5565
5566 def test_ap_wps_m2_dev_passwd_id_change_pin_to_pbc(dev, apdev):
5567 """WPS and M2 with different Device Password ID (PIN to PBC)"""
5568 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5569 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5570 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5571 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5572 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5573 logger.debug("M2")
5574 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5575 if ev is None:
5576 raise Exception("Timeout on EAPOL-TX")
5577 hapd.request("SET ext_eapol_frame_io 0")
5578 dev[0].request("SET ext_eapol_frame_io 0")
5579 msg = ev.split(' ')[2]
5580 if msg[722:730] != '10120002':
5581 raise Exception("Could not find Device Password ID attribute")
5582 # Replace Device Password ID value (PIN --> PBC). This will be rejected.
5583 msg = msg[0:730] + "0004" + msg[734:]
5584 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5585 if "OK" not in res:
5586 raise Exception("EAPOL_RX failed")
5587 wps_fail_finish(hapd, dev[0], "msg=5")
5588
5589 def test_ap_wps_m2_dev_passwd_id_change_pbc_to_pin(dev, apdev):
5590 """WPS and M2 with different Device Password ID (PBC to PIN)"""
5591 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5592 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5593 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5594 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5595 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5596 logger.debug("M2")
5597 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5598 if ev is None:
5599 raise Exception("Timeout on EAPOL-TX")
5600 hapd.request("SET ext_eapol_frame_io 0")
5601 dev[0].request("SET ext_eapol_frame_io 0")
5602 msg = ev.split(' ')[2]
5603 if msg[722:730] != '10120002':
5604 raise Exception("Could not find Device Password ID attribute")
5605 # Replace Device Password ID value. This will fail Authenticator check, but
5606 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5607 # log.
5608 msg = msg[0:730] + "0000" + msg[734:]
5609 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5610 if "OK" not in res:
5611 raise Exception("EAPOL_RX failed")
5612 wps_fail_finish(hapd, dev[0], "msg=5")
5613 dev[0].flush_scan_cache()
5614
5615 def test_ap_wps_m2_missing_dev_passwd_id(dev, apdev):
5616 """WPS and M2 without Device Password ID"""
5617 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0])
5618 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5619 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5620 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5621 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5622 logger.debug("M2")
5623 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5624 if ev is None:
5625 raise Exception("Timeout on EAPOL-TX")
5626 hapd.request("SET ext_eapol_frame_io 0")
5627 dev[0].request("SET ext_eapol_frame_io 0")
5628 msg = ev.split(' ')[2]
5629 if msg[722:730] != '10120002':
5630 raise Exception("Could not find Device Password ID attribute")
5631 # Remove Device Password ID value. This will fail Authenticator check, but
5632 # allows the code path in wps_process_dev_pw_id() to be checked from debug
5633 # log.
5634 mlen = "%04x" % (int(msg[4:8], 16) - 6)
5635 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:722] + msg[734:]
5636 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5637 if "OK" not in res:
5638 raise Exception("EAPOL_RX failed")
5639 wps_fail_finish(hapd, dev[0], "msg=5")
5640
5641 def test_ap_wps_m2_missing_registrar_nonce(dev, apdev):
5642 """WPS and M2 without Registrar Nonce"""
5643 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5644 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5645 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5646 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5647 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5648 logger.debug("M2")
5649 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5650 if ev is None:
5651 raise Exception("Timeout on EAPOL-TX")
5652 hapd.request("SET ext_eapol_frame_io 0")
5653 dev[0].request("SET ext_eapol_frame_io 0")
5654 msg = ev.split(' ')[2]
5655 if msg[96:104] != '10390010':
5656 raise Exception("Could not find Registrar Nonce attribute")
5657 # Remove Registrar Nonce. This will fail Authenticator check, but
5658 # allows the code path in wps_process_registrar_nonce() to be checked from
5659 # the debug log.
5660 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5661 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:96] + msg[136:]
5662 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5663 if "OK" not in res:
5664 raise Exception("EAPOL_RX failed")
5665 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5666 if ev is None:
5667 raise Exception("Disconnect event not seen")
5668 dev[0].request("WPS_CANCEL")
5669 dev[0].flush_scan_cache()
5670
5671 def test_ap_wps_m2_missing_enrollee_nonce(dev, apdev):
5672 """WPS and M2 without Enrollee Nonce"""
5673 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5674 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5675 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5676 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5677 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5678 logger.debug("M2")
5679 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5680 if ev is None:
5681 raise Exception("Timeout on EAPOL-TX")
5682 hapd.request("SET ext_eapol_frame_io 0")
5683 dev[0].request("SET ext_eapol_frame_io 0")
5684 msg = ev.split(' ')[2]
5685 if msg[56:64] != '101a0010':
5686 raise Exception("Could not find enrollee Nonce attribute")
5687 # Remove Enrollee Nonce. This will fail Authenticator check, but
5688 # allows the code path in wps_process_enrollee_nonce() to be checked from
5689 # the debug log.
5690 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5691 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:56] + msg[96:]
5692 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5693 if "OK" not in res:
5694 raise Exception("EAPOL_RX failed")
5695 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5696 if ev is None:
5697 raise Exception("Disconnect event not seen")
5698 dev[0].request("WPS_CANCEL")
5699 dev[0].flush_scan_cache()
5700
5701 def test_ap_wps_m2_missing_uuid_r(dev, apdev):
5702 """WPS and M2 without UUID-R"""
5703 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5704 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5705 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5706 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5707 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5708 logger.debug("M2")
5709 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5710 if ev is None:
5711 raise Exception("Timeout on EAPOL-TX")
5712 hapd.request("SET ext_eapol_frame_io 0")
5713 dev[0].request("SET ext_eapol_frame_io 0")
5714 msg = ev.split(' ')[2]
5715 if msg[136:144] != '10480010':
5716 raise Exception("Could not find enrollee Nonce attribute")
5717 # Remove UUID-R. This will fail Authenticator check, but allows the code
5718 # path in wps_process_uuid_r() to be checked from the debug log.
5719 mlen = "%04x" % (int(msg[4:8], 16) - 20)
5720 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:136] + msg[176:]
5721 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5722 if "OK" not in res:
5723 raise Exception("EAPOL_RX failed")
5724 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5725 if ev is None:
5726 raise Exception("Disconnect event not seen")
5727 dev[0].request("WPS_CANCEL")
5728 dev[0].flush_scan_cache()
5729
5730 def test_ap_wps_m2_invalid(dev, apdev):
5731 """WPS and M2 parsing failure"""
5732 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5733 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5734 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5735 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5736 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5737 logger.debug("M2")
5738 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5739 if ev is None:
5740 raise Exception("Timeout on EAPOL-TX")
5741 hapd.request("SET ext_eapol_frame_io 0")
5742 dev[0].request("SET ext_eapol_frame_io 0")
5743 msg = ev.split(' ')[2]
5744 if msg[136:144] != '10480010':
5745 raise Exception("Could not find enrollee Nonce attribute")
5746 # Remove UUID-R. This will fail Authenticator check, but allows the code
5747 # path in wps_process_uuid_r() to be checked from the debug log.
5748 mlen = "%04x" % (int(msg[4:8], 16) - 1)
5749 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:-2]
5750 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5751 if "OK" not in res:
5752 raise Exception("EAPOL_RX failed")
5753 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5754 if ev is None:
5755 raise Exception("Disconnect event not seen")
5756 dev[0].request("WPS_CANCEL")
5757 dev[0].flush_scan_cache()
5758
5759 def test_ap_wps_m2_missing_msg_type(dev, apdev):
5760 """WPS and M2 without Message Type"""
5761 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5762 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5763 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5764 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5765 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5766 logger.debug("M2")
5767 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5768 if ev is None:
5769 raise Exception("Timeout on EAPOL-TX")
5770 hapd.request("SET ext_eapol_frame_io 0")
5771 dev[0].request("SET ext_eapol_frame_io 0")
5772 msg = ev.split(' ')[2]
5773 if msg[46:54] != '10220001':
5774 raise Exception("Could not find Message Type attribute")
5775 # Remove Message Type. This will fail Authenticator check, but allows the
5776 # code path in wps_process_wsc_msg() to be checked from the debug log.
5777 mlen = "%04x" % (int(msg[4:8], 16) - 5)
5778 msg = msg[0:4] + mlen + msg[8:12] + mlen + msg[16:46] + msg[56:]
5779 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5780 if "OK" not in res:
5781 raise Exception("EAPOL_RX failed")
5782 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5783 if ev is None:
5784 raise Exception("Disconnect event not seen")
5785 dev[0].request("WPS_CANCEL")
5786 dev[0].flush_scan_cache()
5787
5788 def test_ap_wps_m2_unknown_msg_type(dev, apdev):
5789 """WPS and M2 but unknown Message Type"""
5790 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5791 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5792 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5793 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5794 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5795 logger.debug("M2")
5796 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5797 if ev is None:
5798 raise Exception("Timeout on EAPOL-TX")
5799 hapd.request("SET ext_eapol_frame_io 0")
5800 dev[0].request("SET ext_eapol_frame_io 0")
5801 msg = ev.split(' ')[2]
5802 if msg[46:54] != '10220001':
5803 raise Exception("Could not find Message Type attribute")
5804 # Replace Message Type value. This will be rejected.
5805 msg = msg[0:54] + "00" + msg[56:]
5806 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5807 if "OK" not in res:
5808 raise Exception("EAPOL_RX failed")
5809 ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECT"], timeout=5)
5810 if ev is None:
5811 raise Exception("Disconnect event not seen")
5812 dev[0].request("WPS_CANCEL")
5813 dev[0].flush_scan_cache()
5814
5815 def test_ap_wps_m2_unknown_opcode(dev, apdev):
5816 """WPS and M2 but unknown opcode"""
5817 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5818 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5819 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5820 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5821 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5822 logger.debug("M2")
5823 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5824 if ev is None:
5825 raise Exception("Timeout on EAPOL-TX")
5826 hapd.request("SET ext_eapol_frame_io 0")
5827 dev[0].request("SET ext_eapol_frame_io 0")
5828 msg = ev.split(' ')[2]
5829 # Replace opcode. This will be discarded in EAP-WSC processing.
5830 msg = msg[0:32] + "00" + msg[34:]
5831 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5832 if "OK" not in res:
5833 raise Exception("EAPOL_RX failed")
5834 dev[0].request("WPS_CANCEL")
5835 dev[0].wait_disconnected()
5836 dev[0].flush_scan_cache()
5837
5838 def test_ap_wps_m2_unknown_opcode2(dev, apdev):
5839 """WPS and M2 but unknown opcode (WSC_Start)"""
5840 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5841 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5842 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5843 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5844 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5845 logger.debug("M2")
5846 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5847 if ev is None:
5848 raise Exception("Timeout on EAPOL-TX")
5849 hapd.request("SET ext_eapol_frame_io 0")
5850 dev[0].request("SET ext_eapol_frame_io 0")
5851 msg = ev.split(' ')[2]
5852 # Replace opcode. This will be discarded in EAP-WSC processing.
5853 msg = msg[0:32] + "01" + msg[34:]
5854 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5855 if "OK" not in res:
5856 raise Exception("EAPOL_RX failed")
5857 dev[0].request("WPS_CANCEL")
5858 dev[0].wait_disconnected()
5859 dev[0].flush_scan_cache()
5860
5861 def test_ap_wps_m2_unknown_opcode3(dev, apdev):
5862 """WPS and M2 but unknown opcode (WSC_Done)"""
5863 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
5864 wps_ext_eap_identity_req(dev[0], hapd, bssid)
5865 wps_ext_eap_identity_resp(hapd, dev[0], addr)
5866 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
5867 wps_ext_eap_wsc(hapd, dev[0], addr, "M1")
5868 logger.debug("M2")
5869 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5870 if ev is None:
5871 raise Exception("Timeout on EAPOL-TX")
5872 hapd.request("SET ext_eapol_frame_io 0")
5873 dev[0].request("SET ext_eapol_frame_io 0")
5874 msg = ev.split(' ')[2]
5875 # Replace opcode. This will be discarded in WPS Enrollee processing.
5876 msg = msg[0:32] + "05" + msg[34:]
5877 res = dev[0].request("EAPOL_RX " + bssid + " " + msg)
5878 if "OK" not in res:
5879 raise Exception("EAPOL_RX failed")
5880 dev[0].request("WPS_CANCEL")
5881 dev[0].wait_disconnected()
5882 dev[0].flush_scan_cache()
5883
5884 def wps_m2_but_other(dev, apdev, title, msgtype):
5885 addr, bssid, hapd = wps_start_ext(apdev, dev)
5886 wps_ext_eap_identity_req(dev, hapd, bssid)
5887 wps_ext_eap_identity_resp(hapd, dev, addr)
5888 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5889 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5890 logger.debug(title)
5891 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5892 if ev is None:
5893 raise Exception("Timeout on EAPOL-TX")
5894 hapd.request("SET ext_eapol_frame_io 0")
5895 dev.request("SET ext_eapol_frame_io 0")
5896 msg = ev.split(' ')[2]
5897 if msg[46:54] != '10220001':
5898 raise Exception("Could not find Message Type attribute")
5899 # Replace Message Type value. This will be rejected.
5900 msg = msg[0:54] + msgtype + msg[56:]
5901 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5902 if "OK" not in res:
5903 raise Exception("EAPOL_RX failed")
5904 ev = dev.wait_event(["WPS-FAIL"], timeout=5)
5905 if ev is None:
5906 raise Exception("WPS-FAIL event not seen")
5907 dev.request("WPS_CANCEL")
5908 dev.wait_disconnected()
5909
5910 def wps_m4_but_other(dev, apdev, title, msgtype):
5911 addr, bssid, hapd = wps_start_ext(apdev, dev)
5912 wps_ext_eap_identity_req(dev, hapd, bssid)
5913 wps_ext_eap_identity_resp(hapd, dev, addr)
5914 wps_ext_eap_wsc(dev, hapd, bssid, "EAP-WSC/Start")
5915 wps_ext_eap_wsc(hapd, dev, addr, "M1")
5916 wps_ext_eap_wsc(dev, hapd, bssid, "M2")
5917 wps_ext_eap_wsc(hapd, dev, addr, "M3")
5918 logger.debug(title)
5919 ev = hapd.wait_event(["EAPOL-TX"], timeout=10)
5920 if ev is None:
5921 raise Exception("Timeout on EAPOL-TX")
5922 hapd.request("SET ext_eapol_frame_io 0")
5923 dev.request("SET ext_eapol_frame_io 0")
5924 msg = ev.split(' ')[2]
5925 if msg[46:54] != '10220001':
5926 raise Exception("Could not find Message Type attribute")
5927 # Replace Message Type value. This will be rejected.
5928 msg = msg[0:54] + msgtype + msg[56:]
5929 res = dev.request("EAPOL_RX " + bssid + " " + msg)
5930 if "OK" not in res:
5931 raise Exception("EAPOL_RX failed")
5932 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
5933 if ev is None:
5934 raise Exception("WPS-FAIL event not seen")
5935 dev.request("WPS_CANCEL")
5936 dev.wait_disconnected()
5937
5938 def test_ap_wps_m2_msg_type_m4(dev, apdev):
5939 """WPS and M2 but Message Type M4"""
5940 wps_m2_but_other(dev[0], apdev[0], "M2/M4", "08")
5941
5942 def test_ap_wps_m2_msg_type_m6(dev, apdev):
5943 """WPS and M2 but Message Type M6"""
5944 wps_m2_but_other(dev[0], apdev[0], "M2/M6", "0a")
5945
5946 def test_ap_wps_m2_msg_type_m8(dev, apdev):
5947 """WPS and M2 but Message Type M8"""
5948 wps_m2_but_other(dev[0], apdev[0], "M2/M8", "0c")
5949
5950 def test_ap_wps_m4_msg_type_m2(dev, apdev):
5951 """WPS and M4 but Message Type M2"""
5952 wps_m4_but_other(dev[0], apdev[0], "M4/M2", "05")
5953
5954 def test_ap_wps_m4_msg_type_m2d(dev, apdev):
5955 """WPS and M4 but Message Type M2D"""
5956 wps_m4_but_other(dev[0], apdev[0], "M4/M2D", "06")
5957
5958 @remote_compatible
5959 def test_ap_wps_config_methods(dev, apdev):
5960 """WPS configuration method parsing"""
5961 ssid = "test-wps-conf"
5962 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5963 "wpa_passphrase": "12345678", "wpa": "2",
5964 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5965 "config_methods": "ethernet display ext_nfc_token int_nfc_token physical_display physical_push_button"}
5966 hapd = hostapd.add_ap(apdev[0], params)
5967 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
5968 "wpa_passphrase": "12345678", "wpa": "2",
5969 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
5970 "config_methods": "display push_button"}
5971 hapd2 = hostapd.add_ap(apdev[1], params)
5972
5973 def test_ap_wps_set_selected_registrar_proto(dev, apdev):
5974 """WPS UPnP SetSelectedRegistrar protocol testing"""
5975 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
5976 hapd = add_ssdp_ap(apdev[0], ap_uuid)
5977
5978 location = ssdp_get_location(ap_uuid)
5979 urls = upnp_get_urls(location)
5980 eventurl = urlparse(urls['event_sub_url'])
5981 ctrlurl = urlparse(urls['control_url'])
5982 url = urlparse(location)
5983 conn = HTTPConnection(url.netloc)
5984
5985 class WPSERHTTPServer(StreamRequestHandler):
5986 def handle(self):
5987 data = self.rfile.readline().strip()
5988 logger.debug(data)
5989 self.wfile.write(gen_wps_event())
5990
5991 server = MyTCPServer(("127.0.0.1", 12345), WPSERHTTPServer)
5992 server.timeout = 1
5993
5994 headers = {"callback": '<http://127.0.0.1:12345/event>',
5995 "NT": "upnp:event",
5996 "timeout": "Second-1234"}
5997 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
5998 resp = conn.getresponse()
5999 if resp.status != 200:
6000 raise Exception("Unexpected HTTP response: %d" % resp.status)
6001 sid = resp.getheader("sid")
6002 logger.debug("Subscription SID " + sid)
6003 server.handle_request()
6004
6005 tests = [(500, "10"),
6006 (200, "104a000110" + "1041000101" + "101200020000" +
6007 "105300023148" +
6008 "1049002c00372a0001200124111111111111222222222222333333333333444444444444555555555555666666666666" +
6009 "10480010362db47ba53a519188fb5458b986b2e4"),
6010 (200, "104a000110" + "1041000100" + "101200020000" +
6011 "105300020000"),
6012 (200, "104a000110" + "1041000100"),
6013 (200, "104a000110")]
6014 for status, test in tests:
6015 tlvs = binascii.unhexlify(test)
6016 newmsg = base64.b64encode(tlvs).decode()
6017 msg = '<?xml version="1.0"?>\n'
6018 msg += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
6019 msg += '<s:Body>'
6020 msg += '<u:SetSelectedRegistrar xmlns:u="urn:schemas-wifialliance-org:service:WFAWLANConfig:1">'
6021 msg += '<NewMessage>'
6022 msg += newmsg
6023 msg += "</NewMessage></u:SetSelectedRegistrar></s:Body></s:Envelope>"
6024 headers = {"Content-type": 'text/xml; charset="utf-8"'}
6025 headers["SOAPAction"] = '"urn:schemas-wifialliance-org:service:WFAWLANConfig:1#%s"' % "SetSelectedRegistrar"
6026 conn.request("POST", ctrlurl.path, msg, headers)
6027 resp = conn.getresponse()
6028 if resp.status != status:
6029 raise Exception("Unexpected HTTP response: %d (expected %d)" % (resp.status, status))
6030
6031 def test_ap_wps_adv_oom(dev, apdev):
6032 """WPS AP and advertisement OOM"""
6033 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
6034 hapd = add_ssdp_ap(apdev[0], ap_uuid)
6035
6036 with alloc_fail(hapd, 1, "=msearchreply_state_machine_start"):
6037 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6038 no_recv=True)
6039 time.sleep(0.2)
6040
6041 with alloc_fail(hapd, 1, "eloop_register_timeout;msearchreply_state_machine_start"):
6042 ssdp_send_msearch("urn:schemas-wifialliance-org:service:WFAWLANConfig:1",
6043 no_recv=True)
6044 time.sleep(0.2)
6045
6046 with alloc_fail(hapd, 1,
6047 "next_advertisement;advertisement_state_machine_stop"):
6048 hapd.disable()
6049
6050 with alloc_fail(hapd, 1, "ssdp_listener_start"):
6051 if "FAIL" not in hapd.request("ENABLE"):
6052 raise Exception("ENABLE succeeded during OOM")
6053
6054 def test_wps_config_methods(dev):
6055 """WPS config method update"""
6056 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
6057 wpas.interface_add("wlan5")
6058 if "OK" not in wpas.request("SET config_methods display label"):
6059 raise Exception("Failed to set config_methods")
6060 if wpas.request("GET config_methods").strip() != "display label":
6061 raise Exception("config_methods were not updated")
6062 if "OK" not in wpas.request("SET config_methods "):
6063 raise Exception("Failed to clear config_methods")
6064 if wpas.request("GET config_methods").strip() != "":
6065 raise Exception("config_methods were not cleared")
6066
6067 WPS_VENDOR_ID_WFA = 14122
6068 WPS_VENDOR_TYPE = 1
6069
6070 # EAP-WSC Op-Code values
6071 WSC_Start = 0x01
6072 WSC_ACK = 0x02
6073 WSC_NACK = 0x03
6074 WSC_MSG = 0x04
6075 WSC_Done = 0x05
6076 WSC_FRAG_ACK = 0x06
6077
6078 ATTR_AP_CHANNEL = 0x1001
6079 ATTR_ASSOC_STATE = 0x1002
6080 ATTR_AUTH_TYPE = 0x1003
6081 ATTR_AUTH_TYPE_FLAGS = 0x1004
6082 ATTR_AUTHENTICATOR = 0x1005
6083 ATTR_CONFIG_METHODS = 0x1008
6084 ATTR_CONFIG_ERROR = 0x1009
6085 ATTR_CONFIRM_URL4 = 0x100a
6086 ATTR_CONFIRM_URL6 = 0x100b
6087 ATTR_CONN_TYPE = 0x100c
6088 ATTR_CONN_TYPE_FLAGS = 0x100d
6089 ATTR_CRED = 0x100e
6090 ATTR_ENCR_TYPE = 0x100f
6091 ATTR_ENCR_TYPE_FLAGS = 0x1010
6092 ATTR_DEV_NAME = 0x1011
6093 ATTR_DEV_PASSWORD_ID = 0x1012
6094 ATTR_E_HASH1 = 0x1014
6095 ATTR_E_HASH2 = 0x1015
6096 ATTR_E_SNONCE1 = 0x1016
6097 ATTR_E_SNONCE2 = 0x1017
6098 ATTR_ENCR_SETTINGS = 0x1018
6099 ATTR_ENROLLEE_NONCE = 0x101a
6100 ATTR_FEATURE_ID = 0x101b
6101 ATTR_IDENTITY = 0x101c
6102 ATTR_IDENTITY_PROOF = 0x101d
6103 ATTR_KEY_WRAP_AUTH = 0x101e
6104 ATTR_KEY_ID = 0x101f
6105 ATTR_MAC_ADDR = 0x1020
6106 ATTR_MANUFACTURER = 0x1021
6107 ATTR_MSG_TYPE = 0x1022
6108 ATTR_MODEL_NAME = 0x1023
6109 ATTR_MODEL_NUMBER = 0x1024
6110 ATTR_NETWORK_INDEX = 0x1026
6111 ATTR_NETWORK_KEY = 0x1027
6112 ATTR_NETWORK_KEY_INDEX = 0x1028
6113 ATTR_NEW_DEVICE_NAME = 0x1029
6114 ATTR_NEW_PASSWORD = 0x102a
6115 ATTR_OOB_DEVICE_PASSWORD = 0x102c
6116 ATTR_OS_VERSION = 0x102d
6117 ATTR_POWER_LEVEL = 0x102f
6118 ATTR_PSK_CURRENT = 0x1030
6119 ATTR_PSK_MAX = 0x1031
6120 ATTR_PUBLIC_KEY = 0x1032
6121 ATTR_RADIO_ENABLE = 0x1033
6122 ATTR_REBOOT = 0x1034
6123 ATTR_REGISTRAR_CURRENT = 0x1035
6124 ATTR_REGISTRAR_ESTABLISHED = 0x1036
6125 ATTR_REGISTRAR_LIST = 0x1037
6126 ATTR_REGISTRAR_MAX = 0x1038
6127 ATTR_REGISTRAR_NONCE = 0x1039
6128 ATTR_REQUEST_TYPE = 0x103a
6129 ATTR_RESPONSE_TYPE = 0x103b
6130 ATTR_RF_BANDS = 0x103c
6131 ATTR_R_HASH1 = 0x103d
6132 ATTR_R_HASH2 = 0x103e
6133 ATTR_R_SNONCE1 = 0x103f
6134 ATTR_R_SNONCE2 = 0x1040
6135 ATTR_SELECTED_REGISTRAR = 0x1041
6136 ATTR_SERIAL_NUMBER = 0x1042
6137 ATTR_WPS_STATE = 0x1044
6138 ATTR_SSID = 0x1045
6139 ATTR_TOTAL_NETWORKS = 0x1046
6140 ATTR_UUID_E = 0x1047
6141 ATTR_UUID_R = 0x1048
6142 ATTR_VENDOR_EXT = 0x1049
6143 ATTR_VERSION = 0x104a
6144 ATTR_X509_CERT_REQ = 0x104b
6145 ATTR_X509_CERT = 0x104c
6146 ATTR_EAP_IDENTITY = 0x104d
6147 ATTR_MSG_COUNTER = 0x104e
6148 ATTR_PUBKEY_HASH = 0x104f
6149 ATTR_REKEY_KEY = 0x1050
6150 ATTR_KEY_LIFETIME = 0x1051
6151 ATTR_PERMITTED_CFG_METHODS = 0x1052
6152 ATTR_SELECTED_REGISTRAR_CONFIG_METHODS = 0x1053
6153 ATTR_PRIMARY_DEV_TYPE = 0x1054
6154 ATTR_SECONDARY_DEV_TYPE_LIST = 0x1055
6155 ATTR_PORTABLE_DEV = 0x1056
6156 ATTR_AP_SETUP_LOCKED = 0x1057
6157 ATTR_APPLICATION_EXT = 0x1058
6158 ATTR_EAP_TYPE = 0x1059
6159 ATTR_IV = 0x1060
6160 ATTR_KEY_PROVIDED_AUTO = 0x1061
6161 ATTR_802_1X_ENABLED = 0x1062
6162 ATTR_APPSESSIONKEY = 0x1063
6163 ATTR_WEPTRANSMITKEY = 0x1064
6164 ATTR_REQUESTED_DEV_TYPE = 0x106a
6165
6166 # Message Type
6167 WPS_Beacon = 0x01
6168 WPS_ProbeRequest = 0x02
6169 WPS_ProbeResponse = 0x03
6170 WPS_M1 = 0x04
6171 WPS_M2 = 0x05
6172 WPS_M2D = 0x06
6173 WPS_M3 = 0x07
6174 WPS_M4 = 0x08
6175 WPS_M5 = 0x09
6176 WPS_M6 = 0x0a
6177 WPS_M7 = 0x0b
6178 WPS_M8 = 0x0c
6179 WPS_WSC_ACK = 0x0d
6180 WPS_WSC_NACK = 0x0e
6181 WPS_WSC_DONE = 0x0f
6182
6183 def get_wsc_msg(dev):
6184 ev = dev.wait_event(["EAPOL-TX"], timeout=10)
6185 if ev is None:
6186 raise Exception("Timeout on EAPOL-TX")
6187 data = binascii.unhexlify(ev.split(' ')[2])
6188 msg = {}
6189
6190 # Parse EAPOL header
6191 if len(data) < 4:
6192 raise Exception("No room for EAPOL header")
6193 version, type, length = struct.unpack('>BBH', data[0:4])
6194 msg['eapol_version'] = version
6195 msg['eapol_type'] = type
6196 msg['eapol_length'] = length
6197 data = data[4:]
6198 if length != len(data):
6199 raise Exception("EAPOL header length mismatch (%d != %d)" % (length, len(data)))
6200 if type != 0:
6201 raise Exception("Unexpected EAPOL header type: %d" % type)
6202
6203 # Parse EAP header
6204 if len(data) < 4:
6205 raise Exception("No room for EAP header")
6206 code, identifier, length = struct.unpack('>BBH', data[0:4])
6207 msg['eap_code'] = code
6208 msg['eap_identifier'] = identifier
6209 msg['eap_length'] = length
6210 data = data[4:]
6211 if msg['eapol_length'] != msg['eap_length']:
6212 raise Exception("EAP header length mismatch (%d != %d)" % (msg['eapol_length'], length))
6213
6214 # Parse EAP expanded header
6215 if len(data) < 1:
6216 raise Exception("No EAP type included")
6217 msg['eap_type'], = struct.unpack('B', data[0:1])
6218 data = data[1:]
6219
6220 if msg['eap_type'] == 254:
6221 if len(data) < 3 + 4:
6222 raise Exception("Truncated EAP expanded header")
6223 msg['eap_vendor_id'], msg['eap_vendor_type'] = struct.unpack('>LL', b'\x00' + data[0:7])
6224 data = data[7:]
6225 else:
6226 raise Exception("Unexpected EAP type")
6227
6228 if msg['eap_vendor_id'] != WPS_VENDOR_ID_WFA:
6229 raise Exception("Unexpected Vendor-Id")
6230 if msg['eap_vendor_type'] != WPS_VENDOR_TYPE:
6231 raise Exception("Unexpected Vendor-Type")
6232
6233 # Parse EAP-WSC header
6234 if len(data) < 2:
6235 raise Exception("Truncated EAP-WSC header")
6236 msg['wsc_opcode'], msg['wsc_flags'] = struct.unpack('BB', data[0:2])
6237 data = data[2:]
6238
6239 # Parse WSC attributes
6240 msg['raw_attrs'] = data
6241 attrs = {}
6242 while len(data) > 0:
6243 if len(data) < 4:
6244 raise Exception("Truncated attribute header")
6245 attr, length = struct.unpack('>HH', data[0:4])
6246 data = data[4:]
6247 if length > len(data):
6248 raise Exception("Truncated attribute 0x%04x" % attr)
6249 attrs[attr] = data[0:length]
6250 data = data[length:]
6251 msg['wsc_attrs'] = attrs
6252
6253 if ATTR_MSG_TYPE in attrs:
6254 msg['wsc_msg_type'], = struct.unpack('B', attrs[ATTR_MSG_TYPE])
6255
6256 return msg
6257
6258 def recv_wsc_msg(dev, opcode, msg_type):
6259 msg = get_wsc_msg(dev)
6260 if msg['wsc_opcode'] != opcode or msg['wsc_msg_type'] != msg_type:
6261 raise Exception("Unexpected Op-Code/MsgType")
6262 return msg, msg['wsc_attrs'], msg['raw_attrs']
6263
6264 def build_wsc_attr(attr, payload):
6265 _payload = payload if type(payload) == bytes else payload.encode()
6266 return struct.pack('>HH', attr, len(_payload)) + _payload
6267
6268 def build_attr_msg_type(msg_type):
6269 return build_wsc_attr(ATTR_MSG_TYPE, struct.pack('B', msg_type))
6270
6271 def build_eap_wsc(eap_code, eap_id, payload, opcode=WSC_MSG):
6272 length = 4 + 8 + 2 + len(payload)
6273 # EAPOL header
6274 msg = struct.pack('>BBH', 2, 0, length)
6275 # EAP header
6276 msg += struct.pack('>BBH', eap_code, eap_id, length)
6277 # EAP expanded header for EAP-WSC
6278 msg += struct.pack('B', 254)
6279 msg += struct.pack('>L', WPS_VENDOR_ID_WFA)[1:4]
6280 msg += struct.pack('>L', WPS_VENDOR_TYPE)
6281 # EAP-WSC header
6282 msg += struct.pack('BB', opcode, 0)
6283 # WSC attributes
6284 msg += payload
6285 return msg
6286
6287 def build_eap_success(eap_id):
6288 length = 4
6289 # EAPOL header
6290 msg = struct.pack('>BBH', 2, 0, length)
6291 # EAP header
6292 msg += struct.pack('>BBH', 3, eap_id, length)
6293 return msg
6294
6295 def build_eap_failure(eap_id):
6296 length = 4
6297 # EAPOL header
6298 msg = struct.pack('>BBH', 2, 0, length)
6299 # EAP header
6300 msg += struct.pack('>BBH', 4, eap_id, length)
6301 return msg
6302
6303 def send_wsc_msg(dev, src, msg):
6304 res = dev.request("EAPOL_RX " + src + " " + binascii.hexlify(msg).decode())
6305 if "OK" not in res:
6306 raise Exception("EAPOL_RX failed")
6307
6308 group_5_prime = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF
6309 group_5_generator = 2
6310
6311 def wsc_kdf(key, label, bits):
6312 result = b''
6313 i = 1
6314 while len(result) * 8 < bits:
6315 data = struct.pack('>L', i) + label.encode() + struct.pack('>L', bits)
6316 m = hmac.new(key, data, hashlib.sha256)
6317 result += m.digest()
6318 i += 1
6319 return result[0:bits // 8]
6320
6321 def wsc_keys(kdk):
6322 keys = wsc_kdf(kdk, "Wi-Fi Easy and Secure Key Derivation", 640)
6323 authkey = keys[0:32]
6324 keywrapkey = keys[32:48]
6325 emsk = keys[48:80]
6326 return authkey, keywrapkey, emsk
6327
6328 def wsc_dev_pw_half_psk(authkey, dev_pw):
6329 m = hmac.new(authkey, dev_pw.encode(), hashlib.sha256)
6330 return m.digest()[0:16]
6331
6332 def wsc_dev_pw_psk(authkey, dev_pw):
6333 dev_pw_1 = dev_pw[0:len(dev_pw) // 2]
6334 dev_pw_2 = dev_pw[len(dev_pw) // 2:]
6335 psk1 = wsc_dev_pw_half_psk(authkey, dev_pw_1)
6336 psk2 = wsc_dev_pw_half_psk(authkey, dev_pw_2)
6337 return psk1, psk2
6338
6339 def build_attr_authenticator(authkey, prev_msg, curr_msg):
6340 m = hmac.new(authkey, prev_msg + curr_msg, hashlib.sha256)
6341 auth = m.digest()[0:8]
6342 return build_wsc_attr(ATTR_AUTHENTICATOR, auth)
6343
6344 def build_attr_encr_settings(authkey, keywrapkey, data):
6345 m = hmac.new(authkey, data, hashlib.sha256)
6346 kwa = m.digest()[0:8]
6347 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6348 iv = 16*b'\x99'
6349 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6350 pad_len = 16 - len(data) % 16
6351 ps = pad_len * struct.pack('B', pad_len)
6352 data += ps
6353 wrapped = aes.encrypt(data)
6354 return build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6355
6356 def decrypt_attr_encr_settings(authkey, keywrapkey, data):
6357 if len(data) < 32 or len(data) % 16 != 0:
6358 raise Exception("Unexpected Encrypted Settings length: %d" % len(data))
6359 iv = data[0:16]
6360 encr = data[16:]
6361 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6362 decrypted = aes.decrypt(encr)
6363 pad_len, = struct.unpack('B', decrypted[-1:])
6364 if pad_len > len(decrypted):
6365 raise Exception("Invalid padding in Encrypted Settings")
6366 for i in range(-pad_len, -1):
6367 if decrypted[i] != decrypted[-1]:
6368 raise Exception("Invalid PS value in Encrypted Settings")
6369
6370 decrypted = decrypted[0:len(decrypted) - pad_len]
6371 if len(decrypted) < 12:
6372 raise Exception("Truncated Encrypted Settings plaintext")
6373 kwa = decrypted[-12:]
6374 attr, length = struct.unpack(">HH", kwa[0:4])
6375 if attr != ATTR_KEY_WRAP_AUTH or length != 8:
6376 raise Exception("Invalid KWA header")
6377 kwa = kwa[4:]
6378 decrypted = decrypted[0:len(decrypted) - 12]
6379
6380 m = hmac.new(authkey, decrypted, hashlib.sha256)
6381 calc_kwa = m.digest()[0:8]
6382 if kwa != calc_kwa:
6383 raise Exception("KWA mismatch")
6384
6385 return decrypted
6386
6387 def zeropad_str(val, pad_len):
6388 while len(val) < pad_len * 2:
6389 val = '0' + val
6390 return val
6391
6392 def wsc_dh_init():
6393 # For now, use a hardcoded private key. In theory, this is supposed to be
6394 # randomly selected.
6395 own_private = 0x123456789
6396 own_public = pow(group_5_generator, own_private, group_5_prime)
6397 pk = binascii.unhexlify(zeropad_str(format(own_public, '02x'), 192))
6398 return own_private, pk
6399
6400 def wsc_dh_kdf(peer_pk, own_private, mac_addr, e_nonce, r_nonce):
6401 peer_public = int(binascii.hexlify(peer_pk), 16)
6402 if peer_public < 2 or peer_public >= group_5_prime:
6403 raise Exception("Invalid peer public key")
6404 if pow(peer_public, (group_5_prime - 1) // 2, group_5_prime) != 1:
6405 raise Exception("Unexpected Legendre symbol for peer public key")
6406
6407 shared_secret = pow(peer_public, own_private, group_5_prime)
6408 ss = zeropad_str(format(shared_secret, "02x"), 192)
6409 logger.debug("DH shared secret: " + ss)
6410
6411 dhkey = hashlib.sha256(binascii.unhexlify(ss)).digest()
6412 logger.debug("DHKey: " + binascii.hexlify(dhkey).decode())
6413
6414 m = hmac.new(dhkey, e_nonce + mac_addr + r_nonce, hashlib.sha256)
6415 kdk = m.digest()
6416 logger.debug("KDK: " + binascii.hexlify(kdk).decode())
6417 authkey, keywrapkey, emsk = wsc_keys(kdk)
6418 logger.debug("AuthKey: " + binascii.hexlify(authkey).decode())
6419 logger.debug("KeyWrapKey: " + binascii.hexlify(keywrapkey).decode())
6420 logger.debug("EMSK: " + binascii.hexlify(emsk).decode())
6421 return authkey, keywrapkey
6422
6423 def wsc_dev_pw_hash(authkey, dev_pw, e_pk, r_pk):
6424 psk1, psk2 = wsc_dev_pw_psk(authkey, dev_pw)
6425 logger.debug("PSK1: " + binascii.hexlify(psk1).decode())
6426 logger.debug("PSK2: " + binascii.hexlify(psk2).decode())
6427
6428 # Note: Secret values are supposed to be random, but hardcoded values are
6429 # fine for testing.
6430 s1 = 16*b'\x77'
6431 m = hmac.new(authkey, s1 + psk1 + e_pk + r_pk, hashlib.sha256)
6432 hash1 = m.digest()
6433 logger.debug("Hash1: " + binascii.hexlify(hash1).decode())
6434
6435 s2 = 16*b'\x88'
6436 m = hmac.new(authkey, s2 + psk2 + e_pk + r_pk, hashlib.sha256)
6437 hash2 = m.digest()
6438 logger.debug("Hash2: " + binascii.hexlify(hash2).decode())
6439 return s1, s2, hash1, hash2
6440
6441 def build_m1(eap_id, uuid_e, mac_addr, e_nonce, e_pk,
6442 manufacturer='', model_name='', config_methods='\x00\x00'):
6443 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6444 attrs += build_attr_msg_type(WPS_M1)
6445 attrs += build_wsc_attr(ATTR_UUID_E, uuid_e)
6446 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6447 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6448 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, e_pk)
6449 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6450 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6451 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6452 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, config_methods)
6453 attrs += build_wsc_attr(ATTR_WPS_STATE, '\x00')
6454 attrs += build_wsc_attr(ATTR_MANUFACTURER, manufacturer)
6455 attrs += build_wsc_attr(ATTR_MODEL_NAME, model_name)
6456 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6457 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6458 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6459 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6460 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6461 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6462 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, '\x00\x00')
6463 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6464 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6465 m1 = build_eap_wsc(2, eap_id, attrs)
6466 return m1, attrs
6467
6468 def build_m2(authkey, m1, eap_id, e_nonce, r_nonce, uuid_r, r_pk,
6469 dev_pw_id='\x00\x00', eap_code=1):
6470 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6471 attrs += build_attr_msg_type(WPS_M2)
6472 if e_nonce:
6473 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6474 if r_nonce:
6475 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6476 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6477 if r_pk:
6478 attrs += build_wsc_attr(ATTR_PUBLIC_KEY, r_pk)
6479 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6480 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6481 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6482 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6483 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6484 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6485 attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6486 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6487 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6488 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6489 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6490 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6491 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6492 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6493 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6494 attrs += build_attr_authenticator(authkey, m1, attrs)
6495 m2 = build_eap_wsc(eap_code, eap_id, attrs)
6496 return m2, attrs
6497
6498 def build_m2d(m1, eap_id, e_nonce, r_nonce, uuid_r, dev_pw_id=None, eap_code=1):
6499 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6500 attrs += build_attr_msg_type(WPS_M2D)
6501 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6502 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6503 attrs += build_wsc_attr(ATTR_UUID_R, uuid_r)
6504 attrs += build_wsc_attr(ATTR_AUTH_TYPE_FLAGS, '\x00\x00')
6505 attrs += build_wsc_attr(ATTR_ENCR_TYPE_FLAGS, '\x00\x00')
6506 attrs += build_wsc_attr(ATTR_CONN_TYPE_FLAGS, '\x00')
6507 attrs += build_wsc_attr(ATTR_CONFIG_METHODS, '\x00\x00')
6508 attrs += build_wsc_attr(ATTR_MANUFACTURER, '')
6509 attrs += build_wsc_attr(ATTR_MODEL_NAME, '')
6510 #attrs += build_wsc_attr(ATTR_MODEL_NUMBER, '')
6511 attrs += build_wsc_attr(ATTR_SERIAL_NUMBER, '')
6512 attrs += build_wsc_attr(ATTR_PRIMARY_DEV_TYPE, 8*'\x00')
6513 attrs += build_wsc_attr(ATTR_DEV_NAME, '')
6514 attrs += build_wsc_attr(ATTR_RF_BANDS, '\x00')
6515 attrs += build_wsc_attr(ATTR_ASSOC_STATE, '\x00\x00')
6516 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, '\x00\x00')
6517 attrs += build_wsc_attr(ATTR_OS_VERSION, '\x00\x00\x00\x00')
6518 if dev_pw_id:
6519 attrs += build_wsc_attr(ATTR_DEV_PASSWORD_ID, dev_pw_id)
6520 m2d = build_eap_wsc(eap_code, eap_id, attrs)
6521 return m2d, attrs
6522
6523 def build_ack(eap_id, e_nonce, r_nonce, msg_type=WPS_WSC_ACK, eap_code=1):
6524 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6525 if msg_type is not None:
6526 attrs += build_attr_msg_type(msg_type)
6527 if e_nonce:
6528 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6529 if r_nonce:
6530 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6531 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_ACK)
6532 return msg, attrs
6533
6534 def build_nack(eap_id, e_nonce, r_nonce, config_error='\x00\x00',
6535 msg_type=WPS_WSC_NACK, eap_code=1):
6536 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6537 if msg_type is not None:
6538 attrs += build_attr_msg_type(msg_type)
6539 if e_nonce:
6540 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6541 if r_nonce:
6542 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
6543 if config_error:
6544 attrs += build_wsc_attr(ATTR_CONFIG_ERROR, config_error)
6545 msg = build_eap_wsc(eap_code, eap_id, attrs, opcode=WSC_NACK)
6546 return msg, attrs
6547
6548 def test_wps_ext(dev, apdev):
6549 """WPS against external implementation"""
6550 pin = "12345670"
6551 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6552 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6553 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6554
6555 logger.debug("Receive WSC/Start from AP")
6556 msg = get_wsc_msg(hapd)
6557 if msg['wsc_opcode'] != WSC_Start:
6558 raise Exception("Unexpected Op-Code for WSC/Start")
6559 wsc_start_id = msg['eap_identifier']
6560
6561 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6562 uuid_e = 16*b'\x11'
6563 e_nonce = 16*b'\x22'
6564 own_private, e_pk = wsc_dh_init()
6565
6566 logger.debug("Send M1 to AP")
6567 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
6568 e_nonce, e_pk)
6569 send_wsc_msg(hapd, addr, m1)
6570
6571 logger.debug("Receive M2 from AP")
6572 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
6573
6574 authkey, keywrapkey = wsc_dh_kdf(m2_attrs[ATTR_PUBLIC_KEY], own_private,
6575 mac_addr, e_nonce,
6576 m2_attrs[ATTR_REGISTRAR_NONCE])
6577 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk,
6578 m2_attrs[ATTR_PUBLIC_KEY])
6579
6580 logger.debug("Send M3 to AP")
6581 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6582 attrs += build_attr_msg_type(WPS_M3)
6583 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6584 m2_attrs[ATTR_REGISTRAR_NONCE])
6585 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
6586 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
6587 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
6588 raw_m3_attrs = attrs
6589 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6590 send_wsc_msg(hapd, addr, m3)
6591
6592 logger.debug("Receive M4 from AP")
6593 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
6594
6595 logger.debug("Send M5 to AP")
6596 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6597 attrs += build_attr_msg_type(WPS_M5)
6598 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6599 m2_attrs[ATTR_REGISTRAR_NONCE])
6600 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
6601 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6602 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
6603 raw_m5_attrs = attrs
6604 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6605 send_wsc_msg(hapd, addr, m5)
6606
6607 logger.debug("Receive M6 from AP")
6608 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
6609
6610 logger.debug("Send M7 to AP")
6611 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6612 attrs += build_attr_msg_type(WPS_M7)
6613 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6614 m2_attrs[ATTR_REGISTRAR_NONCE])
6615 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
6616 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6617 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
6618 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
6619 raw_m7_attrs = attrs
6620 send_wsc_msg(hapd, addr, m7)
6621
6622 logger.debug("Receive M8 from AP")
6623 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
6624 m8_cred = decrypt_attr_encr_settings(authkey, keywrapkey,
6625 m8_attrs[ATTR_ENCR_SETTINGS])
6626 logger.debug("M8 Credential: " + binascii.hexlify(m8_cred).decode())
6627
6628 logger.debug("Prepare WSC_Done")
6629 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6630 attrs += build_attr_msg_type(WPS_WSC_DONE)
6631 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
6632 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE,
6633 m2_attrs[ATTR_REGISTRAR_NONCE])
6634 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
6635 # Do not send WSC_Done yet to allow exchangw with STA complete before the
6636 # AP disconnects.
6637
6638 uuid_r = 16*b'\x33'
6639 r_nonce = 16*b'\x44'
6640
6641 eap_id = wsc_start_id
6642 logger.debug("Send WSC/Start to STA")
6643 wsc_start = build_eap_wsc(1, eap_id, b'', opcode=WSC_Start)
6644 send_wsc_msg(dev[0], bssid, wsc_start)
6645 eap_id = (eap_id + 1) % 256
6646
6647 logger.debug("Receive M1 from STA")
6648 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6649
6650 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6651 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6652 r_nonce)
6653 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6654 m1_attrs[ATTR_PUBLIC_KEY],
6655 e_pk)
6656
6657 logger.debug("Send M2 to STA")
6658 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6659 m1_attrs[ATTR_ENROLLEE_NONCE],
6660 r_nonce, uuid_r, e_pk)
6661 send_wsc_msg(dev[0], bssid, m2)
6662 eap_id = (eap_id + 1) % 256
6663
6664 logger.debug("Receive M3 from STA")
6665 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6666
6667 logger.debug("Send M4 to STA")
6668 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6669 attrs += build_attr_msg_type(WPS_M4)
6670 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6671 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6672 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6673 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6674 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6675 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6676 raw_m4_attrs = attrs
6677 m4 = build_eap_wsc(1, eap_id, attrs)
6678 send_wsc_msg(dev[0], bssid, m4)
6679 eap_id = (eap_id + 1) % 256
6680
6681 logger.debug("Receive M5 from STA")
6682 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6683
6684 logger.debug("Send M6 to STA")
6685 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6686 attrs += build_attr_msg_type(WPS_M6)
6687 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6688 m1_attrs[ATTR_ENROLLEE_NONCE])
6689 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6690 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6691 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6692 raw_m6_attrs = attrs
6693 m6 = build_eap_wsc(1, eap_id, attrs)
6694 send_wsc_msg(dev[0], bssid, m6)
6695 eap_id = (eap_id + 1) % 256
6696
6697 logger.debug("Receive M7 from STA")
6698 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6699
6700 logger.debug("Send M8 to STA")
6701 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6702 attrs += build_attr_msg_type(WPS_M8)
6703 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6704 m1_attrs[ATTR_ENROLLEE_NONCE])
6705 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6706 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6707 raw_m8_attrs = attrs
6708 m8 = build_eap_wsc(1, eap_id, attrs)
6709 send_wsc_msg(dev[0], bssid, m8)
6710 eap_id = (eap_id + 1) % 256
6711
6712 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=5)
6713 if ev is None:
6714 raise Exception("wpa_supplicant did not report credential")
6715
6716 logger.debug("Receive WSC_Done from STA")
6717 msg = get_wsc_msg(dev[0])
6718 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6719 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6720
6721 logger.debug("Send WSC_Done to AP")
6722 hapd.request("SET ext_eapol_frame_io 0")
6723 dev[0].request("SET ext_eapol_frame_io 0")
6724 send_wsc_msg(hapd, addr, wsc_done)
6725
6726 ev = hapd.wait_event(["WPS-REG-SUCCESS"], timeout=5)
6727 if ev is None:
6728 raise Exception("hostapd did not report WPS success")
6729
6730 dev[0].wait_connected()
6731
6732 def wps_start_kwa(dev, apdev):
6733 pin = "12345670"
6734 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6735 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6736 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6737 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6738
6739 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6740 uuid_r = 16*b'\x33'
6741 r_nonce = 16*b'\x44'
6742 own_private, e_pk = wsc_dh_init()
6743
6744 logger.debug("Receive M1 from STA")
6745 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6746 eap_id = (msg['eap_identifier'] + 1) % 256
6747
6748 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6749 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6750 r_nonce)
6751 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6752 m1_attrs[ATTR_PUBLIC_KEY],
6753 e_pk)
6754
6755 logger.debug("Send M2 to STA")
6756 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6757 m1_attrs[ATTR_ENROLLEE_NONCE],
6758 r_nonce, uuid_r, e_pk)
6759 send_wsc_msg(dev[0], bssid, m2)
6760 eap_id = (eap_id + 1) % 256
6761
6762 logger.debug("Receive M3 from STA")
6763 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6764
6765 logger.debug("Send M4 to STA")
6766 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6767 attrs += build_attr_msg_type(WPS_M4)
6768 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6769 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6770 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6771
6772 return r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs
6773
6774 def wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id):
6775 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6776 m4 = build_eap_wsc(1, eap_id, attrs)
6777 send_wsc_msg(dev[0], bssid, m4)
6778 eap_id = (eap_id + 1) % 256
6779
6780 logger.debug("Receive M5 from STA")
6781 msg = get_wsc_msg(dev[0])
6782 if msg['wsc_opcode'] != WSC_NACK:
6783 raise Exception("Unexpected message - expected WSC_Nack")
6784
6785 dev[0].request("WPS_CANCEL")
6786 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6787 dev[0].wait_disconnected()
6788
6789 def test_wps_ext_kwa_proto_no_kwa(dev, apdev):
6790 """WPS and KWA error: No KWA attribute"""
6791 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6792 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6793 # Encrypted Settings without KWA
6794 iv = 16*b'\x99'
6795 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6796 pad_len = 16 - len(data) % 16
6797 ps = pad_len * struct.pack('B', pad_len)
6798 data += ps
6799 wrapped = aes.encrypt(data)
6800 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6801 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6802
6803 def test_wps_ext_kwa_proto_data_after_kwa(dev, apdev):
6804 """WPS and KWA error: Data after KWA"""
6805 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6806 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6807 # Encrypted Settings and data after KWA
6808 m = hmac.new(authkey, data, hashlib.sha256)
6809 kwa = m.digest()[0:8]
6810 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
6811 data += build_wsc_attr(ATTR_VENDOR_EXT, "1234567890")
6812 iv = 16*b'\x99'
6813 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6814 pad_len = 16 - len(data) % 16
6815 ps = pad_len * struct.pack('B', pad_len)
6816 data += ps
6817 wrapped = aes.encrypt(data)
6818 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6819 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6820
6821 def test_wps_ext_kwa_proto_kwa_mismatch(dev, apdev):
6822 """WPS and KWA error: KWA mismatch"""
6823 r_s1, keywrapkey, authkey, raw_m3_attrs, eap_id, bssid, attrs = wps_start_kwa(dev, apdev)
6824 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6825 # Encrypted Settings and KWA with incorrect value
6826 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, 8*'\x00')
6827 iv = 16*b'\x99'
6828 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
6829 pad_len = 16 - len(data) % 16
6830 ps = pad_len * struct.pack('B', pad_len)
6831 data += ps
6832 wrapped = aes.encrypt(data)
6833 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
6834 wps_stop_kwa(dev, bssid, attrs, authkey, raw_m3_attrs, eap_id)
6835
6836 def wps_run_cred_proto(dev, apdev, m8_cred, connect=False, no_connect=False):
6837 pin = "12345670"
6838 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
6839 wps_ext_eap_identity_req(dev[0], hapd, bssid)
6840 wps_ext_eap_identity_resp(hapd, dev[0], addr)
6841 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
6842
6843 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6844 uuid_r = 16*b'\x33'
6845 r_nonce = 16*b'\x44'
6846 own_private, e_pk = wsc_dh_init()
6847
6848 logger.debug("Receive M1 from STA")
6849 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
6850 eap_id = (msg['eap_identifier'] + 1) % 256
6851
6852 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
6853 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
6854 r_nonce)
6855 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
6856 m1_attrs[ATTR_PUBLIC_KEY],
6857 e_pk)
6858
6859 logger.debug("Send M2 to STA")
6860 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
6861 m1_attrs[ATTR_ENROLLEE_NONCE],
6862 r_nonce, uuid_r, e_pk)
6863 send_wsc_msg(dev[0], bssid, m2)
6864 eap_id = (eap_id + 1) % 256
6865
6866 logger.debug("Receive M3 from STA")
6867 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
6868
6869 logger.debug("Send M4 to STA")
6870 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6871 attrs += build_attr_msg_type(WPS_M4)
6872 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
6873 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
6874 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
6875 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
6876 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6877 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
6878 raw_m4_attrs = attrs
6879 m4 = build_eap_wsc(1, eap_id, attrs)
6880 send_wsc_msg(dev[0], bssid, m4)
6881 eap_id = (eap_id + 1) % 256
6882
6883 logger.debug("Receive M5 from STA")
6884 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
6885
6886 logger.debug("Send M6 to STA")
6887 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6888 attrs += build_attr_msg_type(WPS_M6)
6889 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6890 m1_attrs[ATTR_ENROLLEE_NONCE])
6891 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
6892 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
6893 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
6894 raw_m6_attrs = attrs
6895 m6 = build_eap_wsc(1, eap_id, attrs)
6896 send_wsc_msg(dev[0], bssid, m6)
6897 eap_id = (eap_id + 1) % 256
6898
6899 logger.debug("Receive M7 from STA")
6900 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
6901
6902 logger.debug("Send M8 to STA")
6903 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
6904 attrs += build_attr_msg_type(WPS_M8)
6905 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE,
6906 m1_attrs[ATTR_ENROLLEE_NONCE])
6907 attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
6908 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
6909 raw_m8_attrs = attrs
6910 m8 = build_eap_wsc(1, eap_id, attrs)
6911 send_wsc_msg(dev[0], bssid, m8)
6912 eap_id = (eap_id + 1) % 256
6913
6914 if no_connect:
6915 logger.debug("Receive WSC_Done from STA")
6916 msg = get_wsc_msg(dev[0])
6917 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6918 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6919
6920 hapd.request("SET ext_eapol_frame_io 0")
6921 dev[0].request("SET ext_eapol_frame_io 0")
6922
6923 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6924
6925 dev[0].wait_disconnected()
6926 dev[0].request("REMOVE_NETWORK all")
6927 elif connect:
6928 logger.debug("Receive WSC_Done from STA")
6929 msg = get_wsc_msg(dev[0])
6930 if msg['wsc_opcode'] != WSC_Done or msg['wsc_msg_type'] != WPS_WSC_DONE:
6931 raise Exception("Unexpected Op-Code/MsgType for WSC_Done")
6932
6933 hapd.request("SET ext_eapol_frame_io 0")
6934 dev[0].request("SET ext_eapol_frame_io 0")
6935
6936 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6937
6938 dev[0].wait_connected()
6939 else:
6940 # Verify STA NACK's the credential
6941 msg = get_wsc_msg(dev[0])
6942 if msg['wsc_opcode'] != WSC_NACK:
6943 raise Exception("Unexpected message - expected WSC_Nack")
6944 dev[0].request("WPS_CANCEL")
6945 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
6946 dev[0].wait_disconnected()
6947
6948 def build_cred(nw_idx='\x01', ssid='test-wps-conf', auth_type='\x00\x20',
6949 encr_type='\x00\x08', nw_key="12345678",
6950 mac_addr='\x00\x00\x00\x00\x00\x00'):
6951 attrs = b''
6952 if nw_idx is not None:
6953 attrs += build_wsc_attr(ATTR_NETWORK_INDEX, nw_idx)
6954 if ssid is not None:
6955 attrs += build_wsc_attr(ATTR_SSID, ssid)
6956 if auth_type is not None:
6957 attrs += build_wsc_attr(ATTR_AUTH_TYPE, auth_type)
6958 if encr_type is not None:
6959 attrs += build_wsc_attr(ATTR_ENCR_TYPE, encr_type)
6960 if nw_key is not None:
6961 attrs += build_wsc_attr(ATTR_NETWORK_KEY, nw_key)
6962 if mac_addr is not None:
6963 attrs += build_wsc_attr(ATTR_MAC_ADDR, mac_addr)
6964 return build_wsc_attr(ATTR_CRED, attrs)
6965
6966 def test_wps_ext_cred_proto_success(dev, apdev):
6967 """WPS and Credential: success"""
6968 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6969 m8_cred = build_cred(mac_addr=mac_addr)
6970 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6971
6972 def test_wps_ext_cred_proto_mac_addr_mismatch(dev, apdev):
6973 """WPS and Credential: MAC Address mismatch"""
6974 m8_cred = build_cred()
6975 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6976
6977 def test_wps_ext_cred_proto_zero_padding(dev, apdev):
6978 """WPS and Credential: zeropadded attributes"""
6979 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6980 m8_cred = build_cred(mac_addr=mac_addr, ssid='test-wps-conf\x00',
6981 nw_key="12345678\x00")
6982 wps_run_cred_proto(dev, apdev, m8_cred, connect=True)
6983
6984 def test_wps_ext_cred_proto_ssid_missing(dev, apdev):
6985 """WPS and Credential: SSID missing"""
6986 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6987 m8_cred = build_cred(mac_addr=mac_addr, ssid=None)
6988 wps_run_cred_proto(dev, apdev, m8_cred)
6989
6990 def test_wps_ext_cred_proto_ssid_zero_len(dev, apdev):
6991 """WPS and Credential: Zero-length SSID"""
6992 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6993 m8_cred = build_cred(mac_addr=mac_addr, ssid="")
6994 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
6995
6996 def test_wps_ext_cred_proto_auth_type_missing(dev, apdev):
6997 """WPS and Credential: Auth Type missing"""
6998 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
6999 m8_cred = build_cred(mac_addr=mac_addr, auth_type=None)
7000 wps_run_cred_proto(dev, apdev, m8_cred)
7001
7002 def test_wps_ext_cred_proto_encr_type_missing(dev, apdev):
7003 """WPS and Credential: Encr Type missing"""
7004 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7005 m8_cred = build_cred(mac_addr=mac_addr, encr_type=None)
7006 wps_run_cred_proto(dev, apdev, m8_cred)
7007
7008 def test_wps_ext_cred_proto_network_key_missing(dev, apdev):
7009 """WPS and Credential: Network Key missing"""
7010 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7011 m8_cred = build_cred(mac_addr=mac_addr, nw_key=None)
7012 wps_run_cred_proto(dev, apdev, m8_cred)
7013
7014 def test_wps_ext_cred_proto_network_key_missing_open(dev, apdev):
7015 """WPS and Credential: Network Key missing (open)"""
7016 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7017 m8_cred = build_cred(mac_addr=mac_addr, auth_type='\x00\x01',
7018 encr_type='\x00\x01', nw_key=None, ssid="foo")
7019 wps_run_cred_proto(dev, apdev, m8_cred, no_connect=True)
7020
7021 def test_wps_ext_cred_proto_mac_addr_missing(dev, apdev):
7022 """WPS and Credential: MAC Address missing"""
7023 m8_cred = build_cred(mac_addr=None)
7024 wps_run_cred_proto(dev, apdev, m8_cred)
7025
7026 def test_wps_ext_cred_proto_invalid_encr_type(dev, apdev):
7027 """WPS and Credential: Invalid Encr Type"""
7028 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7029 m8_cred = build_cred(mac_addr=mac_addr, encr_type='\x00\x00')
7030 wps_run_cred_proto(dev, apdev, m8_cred)
7031
7032 def test_wps_ext_cred_proto_missing_cred(dev, apdev):
7033 """WPS and Credential: Missing Credential"""
7034 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7035 m8_cred = b''
7036 wps_run_cred_proto(dev, apdev, m8_cred)
7037
7038 def test_wps_ext_proto_m2_no_public_key(dev, apdev):
7039 """WPS and no Public Key in M2"""
7040 pin = "12345670"
7041 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7042 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7043 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7044 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7045
7046 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7047 uuid_r = 16*b'\x33'
7048 r_nonce = 16*b'\x44'
7049 own_private, e_pk = wsc_dh_init()
7050
7051 logger.debug("Receive M1 from STA")
7052 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7053 eap_id = (msg['eap_identifier'] + 1) % 256
7054
7055 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7056 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7057 r_nonce)
7058 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7059 m1_attrs[ATTR_PUBLIC_KEY],
7060 e_pk)
7061
7062 logger.debug("Send M2 to STA")
7063 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7064 m1_attrs[ATTR_ENROLLEE_NONCE],
7065 r_nonce, uuid_r, None)
7066 send_wsc_msg(dev[0], bssid, m2)
7067 eap_id = (eap_id + 1) % 256
7068
7069 # Verify STA NACK's the credential
7070 msg = get_wsc_msg(dev[0])
7071 if msg['wsc_opcode'] != WSC_NACK:
7072 raise Exception("Unexpected message - expected WSC_Nack")
7073 dev[0].request("WPS_CANCEL")
7074 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7075 dev[0].wait_disconnected()
7076
7077 def test_wps_ext_proto_m2_invalid_public_key(dev, apdev):
7078 """WPS and invalid Public Key in M2"""
7079 pin = "12345670"
7080 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7081 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7082 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7083 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7084
7085 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7086 uuid_r = 16*b'\x33'
7087 r_nonce = 16*b'\x44'
7088 own_private, e_pk = wsc_dh_init()
7089
7090 logger.debug("Receive M1 from STA")
7091 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7092 eap_id = (msg['eap_identifier'] + 1) % 256
7093
7094 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7095 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7096 r_nonce)
7097 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7098 m1_attrs[ATTR_PUBLIC_KEY],
7099 e_pk)
7100
7101 logger.debug("Send M2 to STA")
7102 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7103 m1_attrs[ATTR_ENROLLEE_NONCE],
7104 r_nonce, uuid_r, 192*b'\xff')
7105 send_wsc_msg(dev[0], bssid, m2)
7106 eap_id = (eap_id + 1) % 256
7107
7108 # Verify STA NACK's the credential
7109 msg = get_wsc_msg(dev[0])
7110 if msg['wsc_opcode'] != WSC_NACK:
7111 raise Exception("Unexpected message - expected WSC_Nack")
7112 dev[0].request("WPS_CANCEL")
7113 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7114 dev[0].wait_disconnected()
7115
7116 def test_wps_ext_proto_m2_public_key_oom(dev, apdev):
7117 """WPS and Public Key OOM in M2"""
7118 pin = "12345670"
7119 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7120 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7121 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7122 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7123
7124 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7125 uuid_r = 16*b'\x33'
7126 r_nonce = 16*b'\x44'
7127 own_private, e_pk = wsc_dh_init()
7128
7129 logger.debug("Receive M1 from STA")
7130 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7131 eap_id = (msg['eap_identifier'] + 1) % 256
7132
7133 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7134 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7135 r_nonce)
7136 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7137 m1_attrs[ATTR_PUBLIC_KEY],
7138 e_pk)
7139
7140 logger.debug("Send M2 to STA")
7141 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7142 m1_attrs[ATTR_ENROLLEE_NONCE],
7143 r_nonce, uuid_r, e_pk)
7144 with alloc_fail(dev[0], 1, "wpabuf_alloc_copy;wps_process_pubkey"):
7145 send_wsc_msg(dev[0], bssid, m2)
7146 eap_id = (eap_id + 1) % 256
7147
7148 # Verify STA NACK's the credential
7149 msg = get_wsc_msg(dev[0])
7150 if msg['wsc_opcode'] != WSC_NACK:
7151 raise Exception("Unexpected message - expected WSC_Nack")
7152 dev[0].request("WPS_CANCEL")
7153 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7154 dev[0].wait_disconnected()
7155
7156 def test_wps_ext_proto_nack_m3(dev, apdev):
7157 """WPS and NACK M3"""
7158 pin = "12345670"
7159 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7160 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7161 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7162 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7163
7164 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7165 uuid_r = 16*b'\x33'
7166 r_nonce = 16*b'\x44'
7167 own_private, e_pk = wsc_dh_init()
7168
7169 logger.debug("Receive M1 from STA")
7170 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7171 eap_id = (msg['eap_identifier'] + 1) % 256
7172
7173 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7174 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7175 r_nonce)
7176 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7177 m1_attrs[ATTR_PUBLIC_KEY],
7178 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 NACK to STA")
7191 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7192 r_nonce, config_error='\x01\x23')
7193 send_wsc_msg(dev[0], bssid, msg)
7194 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7195 if ev is None:
7196 raise Exception("Failure not reported")
7197 if "msg=7 config_error=291" not in ev:
7198 raise Exception("Unexpected failure reason: " + ev)
7199
7200 def test_wps_ext_proto_nack_m5(dev, apdev):
7201 """WPS and NACK M5"""
7202 pin = "12345670"
7203 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7204 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7205 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7206 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7207
7208 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7209 uuid_r = 16*b'\x33'
7210 r_nonce = 16*b'\x44'
7211 own_private, e_pk = wsc_dh_init()
7212
7213 logger.debug("Receive M1 from STA")
7214 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7215 eap_id = (msg['eap_identifier'] + 1) % 256
7216
7217 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7218 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7219 r_nonce)
7220 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7221 m1_attrs[ATTR_PUBLIC_KEY],
7222 e_pk)
7223
7224 logger.debug("Send M2 to STA")
7225 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7226 m1_attrs[ATTR_ENROLLEE_NONCE],
7227 r_nonce, uuid_r, e_pk)
7228 send_wsc_msg(dev[0], bssid, m2)
7229 eap_id = (eap_id + 1) % 256
7230
7231 logger.debug("Receive M3 from STA")
7232 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7233
7234 logger.debug("Send M4 to STA")
7235 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7236 attrs += build_attr_msg_type(WPS_M4)
7237 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7238 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7239 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7240 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7241 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7242 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7243 raw_m4_attrs = attrs
7244 m4 = build_eap_wsc(1, eap_id, attrs)
7245 send_wsc_msg(dev[0], bssid, m4)
7246 eap_id = (eap_id + 1) % 256
7247
7248 logger.debug("Receive M5 from STA")
7249 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7250
7251 logger.debug("Send NACK to STA")
7252 msg, attrs = build_nack(eap_id, m1_attrs[ATTR_ENROLLEE_NONCE],
7253 r_nonce, config_error='\x01\x24')
7254 send_wsc_msg(dev[0], bssid, msg)
7255 ev = dev[0].wait_event(["WPS-FAIL"], timeout=5)
7256 if ev is None:
7257 raise Exception("Failure not reported")
7258 if "msg=9 config_error=292" not in ev:
7259 raise Exception("Unexpected failure reason: " + ev)
7260
7261 def wps_nack_m3(dev, apdev):
7262 pin = "00000000"
7263 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pbc=True)
7264 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7265 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7266 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7267
7268 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7269 uuid_r = 16*b'\x33'
7270 r_nonce = 16*b'\x44'
7271 own_private, e_pk = wsc_dh_init()
7272
7273 logger.debug("Receive M1 from STA")
7274 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7275 eap_id = (msg['eap_identifier'] + 1) % 256
7276
7277 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7278 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7279 r_nonce)
7280 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7281 m1_attrs[ATTR_PUBLIC_KEY],
7282 e_pk)
7283
7284 logger.debug("Send M2 to STA")
7285 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7286 m1_attrs[ATTR_ENROLLEE_NONCE],
7287 r_nonce, uuid_r, e_pk, dev_pw_id='\x00\x04')
7288 send_wsc_msg(dev[0], bssid, m2)
7289 eap_id = (eap_id + 1) % 256
7290
7291 logger.debug("Receive M3 from STA")
7292 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7293 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid
7294
7295 def test_wps_ext_proto_nack_m3_no_config_error(dev, apdev):
7296 """WPS and NACK M3 missing Config Error"""
7297 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7298 logger.debug("Send NACK to STA")
7299 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, config_error=None)
7300 send_wsc_msg(dev[0], bssid, msg)
7301 dev[0].request("WPS_CANCEL")
7302 dev[0].wait_disconnected()
7303 dev[0].flush_scan_cache()
7304
7305 def test_wps_ext_proto_nack_m3_no_e_nonce(dev, apdev):
7306 """WPS and NACK M3 missing E-Nonce"""
7307 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7308 logger.debug("Send NACK to STA")
7309 msg, attrs = build_nack(eap_id, None, r_nonce)
7310 send_wsc_msg(dev[0], bssid, msg)
7311 dev[0].request("WPS_CANCEL")
7312 dev[0].wait_disconnected()
7313 dev[0].flush_scan_cache()
7314
7315 def test_wps_ext_proto_nack_m3_e_nonce_mismatch(dev, apdev):
7316 """WPS and NACK M3 E-Nonce mismatch"""
7317 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7318 logger.debug("Send NACK to STA")
7319 msg, attrs = build_nack(eap_id, 16*'\x00', r_nonce)
7320 send_wsc_msg(dev[0], bssid, msg)
7321 dev[0].request("WPS_CANCEL")
7322 dev[0].wait_disconnected()
7323 dev[0].flush_scan_cache()
7324
7325 def test_wps_ext_proto_nack_m3_no_r_nonce(dev, apdev):
7326 """WPS and NACK M3 missing R-Nonce"""
7327 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7328 logger.debug("Send NACK to STA")
7329 msg, attrs = build_nack(eap_id, e_nonce, None)
7330 send_wsc_msg(dev[0], bssid, msg)
7331 dev[0].request("WPS_CANCEL")
7332 dev[0].wait_disconnected()
7333 dev[0].flush_scan_cache()
7334
7335 def test_wps_ext_proto_nack_m3_r_nonce_mismatch(dev, apdev):
7336 """WPS and NACK M3 R-Nonce mismatch"""
7337 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7338 logger.debug("Send NACK to STA")
7339 msg, attrs = build_nack(eap_id, e_nonce, 16*'\x00')
7340 send_wsc_msg(dev[0], bssid, msg)
7341 dev[0].request("WPS_CANCEL")
7342 dev[0].wait_disconnected()
7343 dev[0].flush_scan_cache()
7344
7345 def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
7346 """WPS and NACK M3 no Message Type"""
7347 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7348 logger.debug("Send NACK to STA")
7349 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
7350 send_wsc_msg(dev[0], bssid, msg)
7351 dev[0].request("WPS_CANCEL")
7352 dev[0].wait_disconnected()
7353 dev[0].flush_scan_cache()
7354
7355 def test_wps_ext_proto_nack_m3_invalid_msg_type(dev, apdev):
7356 """WPS and NACK M3 invalid Message Type"""
7357 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7358 logger.debug("Send NACK to STA")
7359 msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=123)
7360 send_wsc_msg(dev[0], bssid, msg)
7361 dev[0].request("WPS_CANCEL")
7362 dev[0].wait_disconnected()
7363 dev[0].flush_scan_cache()
7364
7365 def test_wps_ext_proto_nack_m3_invalid_attr(dev, apdev):
7366 """WPS and NACK M3 invalid attribute"""
7367 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7368 logger.debug("Send NACK to STA")
7369 attrs = b'\x10\x10\x00'
7370 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_NACK)
7371 send_wsc_msg(dev[0], bssid, msg)
7372 dev[0].request("WPS_CANCEL")
7373 dev[0].wait_disconnected()
7374 dev[0].flush_scan_cache()
7375
7376 def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev):
7377 """WPS and ACK M3 missing E-Nonce"""
7378 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7379 logger.debug("Send NACK to STA")
7380 msg, attrs = build_ack(eap_id, None, r_nonce)
7381 send_wsc_msg(dev[0], bssid, msg)
7382 dev[0].request("WPS_CANCEL")
7383 dev[0].wait_disconnected()
7384 dev[0].flush_scan_cache()
7385
7386 def test_wps_ext_proto_ack_m3_e_nonce_mismatch(dev, apdev):
7387 """WPS and ACK M3 E-Nonce mismatch"""
7388 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7389 logger.debug("Send NACK to STA")
7390 msg, attrs = build_ack(eap_id, 16*'\x00', r_nonce)
7391 send_wsc_msg(dev[0], bssid, msg)
7392 dev[0].request("WPS_CANCEL")
7393 dev[0].wait_disconnected()
7394 dev[0].flush_scan_cache()
7395
7396 def test_wps_ext_proto_ack_m3_no_r_nonce(dev, apdev):
7397 """WPS and ACK M3 missing R-Nonce"""
7398 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7399 logger.debug("Send NACK to STA")
7400 msg, attrs = build_ack(eap_id, e_nonce, None)
7401 send_wsc_msg(dev[0], bssid, msg)
7402 dev[0].request("WPS_CANCEL")
7403 dev[0].wait_disconnected()
7404 dev[0].flush_scan_cache()
7405
7406 def test_wps_ext_proto_ack_m3_r_nonce_mismatch(dev, apdev):
7407 """WPS and ACK M3 R-Nonce mismatch"""
7408 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7409 logger.debug("Send NACK to STA")
7410 msg, attrs = build_ack(eap_id, e_nonce, 16*'\x00')
7411 send_wsc_msg(dev[0], bssid, msg)
7412 dev[0].request("WPS_CANCEL")
7413 dev[0].wait_disconnected()
7414 dev[0].flush_scan_cache()
7415
7416 def test_wps_ext_proto_ack_m3_no_msg_type(dev, apdev):
7417 """WPS and ACK M3 no Message Type"""
7418 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7419 logger.debug("Send NACK to STA")
7420 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=None)
7421 send_wsc_msg(dev[0], bssid, msg)
7422 dev[0].request("WPS_CANCEL")
7423 dev[0].wait_disconnected()
7424 dev[0].flush_scan_cache()
7425
7426 def test_wps_ext_proto_ack_m3_invalid_msg_type(dev, apdev):
7427 """WPS and ACK M3 invalid Message Type"""
7428 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7429 logger.debug("Send NACK to STA")
7430 msg, attrs = build_ack(eap_id, e_nonce, r_nonce, msg_type=123)
7431 send_wsc_msg(dev[0], bssid, msg)
7432 dev[0].request("WPS_CANCEL")
7433 dev[0].wait_disconnected()
7434 dev[0].flush_scan_cache()
7435
7436 def test_wps_ext_proto_ack_m3_invalid_attr(dev, apdev):
7437 """WPS and ACK M3 invalid attribute"""
7438 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7439 logger.debug("Send ACK to STA")
7440 attrs = b'\x10\x10\x00'
7441 msg = build_eap_wsc(1, eap_id, attrs, opcode=WSC_ACK)
7442 send_wsc_msg(dev[0], bssid, msg)
7443 dev[0].request("WPS_CANCEL")
7444 dev[0].wait_disconnected()
7445 dev[0].flush_scan_cache()
7446
7447 def test_wps_ext_proto_ack_m3(dev, apdev):
7448 """WPS and ACK M3"""
7449 eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
7450 logger.debug("Send ACK to STA")
7451 msg, attrs = build_ack(eap_id, e_nonce, r_nonce)
7452 send_wsc_msg(dev[0], bssid, msg)
7453 dev[0].request("WPS_CANCEL")
7454 dev[0].wait_disconnected()
7455 dev[0].flush_scan_cache()
7456
7457 def wps_to_m3_helper(dev, apdev):
7458 pin = "12345670"
7459 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7460 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7461 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7462 wps_ext_eap_wsc(dev[0], hapd, bssid, "EAP-WSC/Start")
7463
7464 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7465 uuid_r = 16*b'\x33'
7466 r_nonce = 16*b'\x44'
7467 own_private, e_pk = wsc_dh_init()
7468
7469 logger.debug("Receive M1 from STA")
7470 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M1)
7471 eap_id = (msg['eap_identifier'] + 1) % 256
7472
7473 authkey, keywrapkey = wsc_dh_kdf(m1_attrs[ATTR_PUBLIC_KEY], own_private,
7474 mac_addr, m1_attrs[ATTR_ENROLLEE_NONCE],
7475 r_nonce)
7476 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, pin,
7477 m1_attrs[ATTR_PUBLIC_KEY],
7478 e_pk)
7479
7480 logger.debug("Send M2 to STA")
7481 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, eap_id,
7482 m1_attrs[ATTR_ENROLLEE_NONCE],
7483 r_nonce, uuid_r, e_pk)
7484 send_wsc_msg(dev[0], bssid, m2)
7485 eap_id = (eap_id + 1) % 256
7486
7487 logger.debug("Receive M3 from STA")
7488 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M3)
7489 return eap_id, m1_attrs, r_nonce, bssid, r_hash1, r_hash2, r_s1, r_s2, raw_m3_attrs, authkey, keywrapkey
7490
7491 def wps_to_m3(dev, apdev):
7492 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)
7493 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s1, raw_m3_attrs, authkey, keywrapkey
7494
7495 def wps_to_m5(dev, apdev):
7496 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)
7497
7498 logger.debug("Send M4 to STA")
7499 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7500 attrs += build_attr_msg_type(WPS_M4)
7501 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, m1_attrs[ATTR_ENROLLEE_NONCE])
7502 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7503 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7504 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7505 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7506 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7507 raw_m4_attrs = attrs
7508 m4 = build_eap_wsc(1, eap_id, attrs)
7509 send_wsc_msg(dev[0], bssid, m4)
7510 eap_id = (eap_id + 1) % 256
7511
7512 logger.debug("Receive M5 from STA")
7513 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M5)
7514
7515 return eap_id, m1_attrs[ATTR_ENROLLEE_NONCE], r_nonce, bssid, r_hash1, r_hash2, r_s2, raw_m5_attrs, authkey, keywrapkey
7516
7517 def test_wps_ext_proto_m4_missing_r_hash1(dev, apdev):
7518 """WPS and no R-Hash1 in M4"""
7519 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7520
7521 logger.debug("Send M4 to STA")
7522 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7523 attrs += build_attr_msg_type(WPS_M4)
7524 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7525 #attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7526 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7527 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7528 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7529 attrs += build_attr_authenticator(authkey, m3, attrs)
7530 m4 = build_eap_wsc(1, eap_id, attrs)
7531 send_wsc_msg(dev[0], bssid, m4)
7532 eap_id = (eap_id + 1) % 256
7533
7534 logger.debug("Receive M5 (NACK) from STA")
7535 msg = get_wsc_msg(dev[0])
7536 if msg['wsc_opcode'] != WSC_NACK:
7537 raise Exception("Unexpected message - expected WSC_Nack")
7538
7539 dev[0].request("WPS_CANCEL")
7540 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7541 dev[0].wait_disconnected()
7542
7543 def test_wps_ext_proto_m4_missing_r_hash2(dev, apdev):
7544 """WPS and no R-Hash2 in M4"""
7545 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7546
7547 logger.debug("Send M4 to STA")
7548 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7549 attrs += build_attr_msg_type(WPS_M4)
7550 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7551 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7552 #attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7553 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7554 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7555 attrs += build_attr_authenticator(authkey, m3, attrs)
7556 m4 = build_eap_wsc(1, eap_id, attrs)
7557 send_wsc_msg(dev[0], bssid, m4)
7558 eap_id = (eap_id + 1) % 256
7559
7560 logger.debug("Receive M5 (NACK) from STA")
7561 msg = get_wsc_msg(dev[0])
7562 if msg['wsc_opcode'] != WSC_NACK:
7563 raise Exception("Unexpected message - expected WSC_Nack")
7564
7565 dev[0].request("WPS_CANCEL")
7566 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7567 dev[0].wait_disconnected()
7568
7569 def test_wps_ext_proto_m4_missing_r_snonce1(dev, apdev):
7570 """WPS and no R-SNonce1 in M4"""
7571 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7572
7573 logger.debug("Send M4 to STA")
7574 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7575 attrs += build_attr_msg_type(WPS_M4)
7576 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7577 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7578 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7579 #data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7580 data = b''
7581 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7582 attrs += build_attr_authenticator(authkey, m3, attrs)
7583 m4 = build_eap_wsc(1, eap_id, attrs)
7584 send_wsc_msg(dev[0], bssid, m4)
7585 eap_id = (eap_id + 1) % 256
7586
7587 logger.debug("Receive M5 (NACK) from STA")
7588 msg = get_wsc_msg(dev[0])
7589 if msg['wsc_opcode'] != WSC_NACK:
7590 raise Exception("Unexpected message - expected WSC_Nack")
7591
7592 dev[0].request("WPS_CANCEL")
7593 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7594 dev[0].wait_disconnected()
7595
7596 def test_wps_ext_proto_m4_invalid_pad_string(dev, apdev):
7597 """WPS and invalid pad string in M4"""
7598 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7599
7600 logger.debug("Send M4 to STA")
7601 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7602 attrs += build_attr_msg_type(WPS_M4)
7603 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7604 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7605 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7606 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7607
7608 m = hmac.new(authkey, data, hashlib.sha256)
7609 kwa = m.digest()[0:8]
7610 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7611 iv = 16*b'\x99'
7612 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7613 pad_len = 16 - len(data) % 16
7614 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', pad_len - 1)
7615 data += ps
7616 wrapped = aes.encrypt(data)
7617 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7618
7619 attrs += build_attr_authenticator(authkey, m3, attrs)
7620 m4 = build_eap_wsc(1, eap_id, attrs)
7621 send_wsc_msg(dev[0], bssid, m4)
7622 eap_id = (eap_id + 1) % 256
7623
7624 logger.debug("Receive M5 (NACK) from STA")
7625 msg = get_wsc_msg(dev[0])
7626 if msg['wsc_opcode'] != WSC_NACK:
7627 raise Exception("Unexpected message - expected WSC_Nack")
7628
7629 dev[0].request("WPS_CANCEL")
7630 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7631 dev[0].wait_disconnected()
7632
7633 def test_wps_ext_proto_m4_invalid_pad_value(dev, apdev):
7634 """WPS and invalid pad value in M4"""
7635 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7636
7637 logger.debug("Send M4 to STA")
7638 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7639 attrs += build_attr_msg_type(WPS_M4)
7640 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7641 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7642 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7643 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7644
7645 m = hmac.new(authkey, data, hashlib.sha256)
7646 kwa = m.digest()[0:8]
7647 data += build_wsc_attr(ATTR_KEY_WRAP_AUTH, kwa)
7648 iv = 16*b'\x99'
7649 aes = AES.new(keywrapkey, AES.MODE_CBC, iv)
7650 pad_len = 16 - len(data) % 16
7651 ps = (pad_len - 1) * struct.pack('B', pad_len) + struct.pack('B', 255)
7652 data += ps
7653 wrapped = aes.encrypt(data)
7654 attrs += build_wsc_attr(ATTR_ENCR_SETTINGS, iv + wrapped)
7655
7656 attrs += build_attr_authenticator(authkey, m3, attrs)
7657 m4 = build_eap_wsc(1, eap_id, attrs)
7658 send_wsc_msg(dev[0], bssid, m4)
7659 eap_id = (eap_id + 1) % 256
7660
7661 logger.debug("Receive M5 (NACK) from STA")
7662 msg = get_wsc_msg(dev[0])
7663 if msg['wsc_opcode'] != WSC_NACK:
7664 raise Exception("Unexpected message - expected WSC_Nack")
7665
7666 dev[0].request("WPS_CANCEL")
7667 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7668 dev[0].wait_disconnected()
7669
7670 def test_wps_ext_proto_m4_no_encr_settings(dev, apdev):
7671 """WPS and no Encr Settings in M4"""
7672 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s1, m3, authkey, keywrapkey = wps_to_m3(dev, apdev)
7673
7674 logger.debug("Send M4 to STA")
7675 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7676 attrs += build_attr_msg_type(WPS_M4)
7677 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7678 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7679 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7680 attrs += build_attr_authenticator(authkey, m3, attrs)
7681 m4 = build_eap_wsc(1, eap_id, attrs)
7682 send_wsc_msg(dev[0], bssid, m4)
7683 eap_id = (eap_id + 1) % 256
7684
7685 logger.debug("Receive M5 (NACK) from STA")
7686 msg = get_wsc_msg(dev[0])
7687 if msg['wsc_opcode'] != WSC_NACK:
7688 raise Exception("Unexpected message - expected WSC_Nack")
7689
7690 dev[0].request("WPS_CANCEL")
7691 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7692 dev[0].wait_disconnected()
7693
7694 def test_wps_ext_proto_m6_missing_r_snonce2(dev, apdev):
7695 """WPS and no R-SNonce2 in M6"""
7696 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7697
7698 logger.debug("Send M6 to STA")
7699 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7700 attrs += build_attr_msg_type(WPS_M6)
7701 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7702 #data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7703 data = b''
7704 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7705 attrs += build_attr_authenticator(authkey, m5, attrs)
7706 m6 = build_eap_wsc(1, eap_id, attrs)
7707 send_wsc_msg(dev[0], bssid, m6)
7708 eap_id = (eap_id + 1) % 256
7709
7710 logger.debug("Receive M7 (NACK) from STA")
7711 msg = get_wsc_msg(dev[0])
7712 if msg['wsc_opcode'] != WSC_NACK:
7713 raise Exception("Unexpected message - expected WSC_Nack")
7714
7715 dev[0].request("WPS_CANCEL")
7716 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7717 dev[0].wait_disconnected()
7718
7719 def test_wps_ext_proto_m6_no_encr_settings(dev, apdev):
7720 """WPS and no Encr Settings in M6"""
7721 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7722
7723 logger.debug("Send M6 to STA")
7724 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7725 attrs += build_attr_msg_type(WPS_M6)
7726 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7727 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7728 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7729 attrs += build_attr_authenticator(authkey, m5, attrs)
7730 m6 = build_eap_wsc(1, eap_id, attrs)
7731 send_wsc_msg(dev[0], bssid, m6)
7732 eap_id = (eap_id + 1) % 256
7733
7734 logger.debug("Receive M7 (NACK) from STA")
7735 msg = get_wsc_msg(dev[0])
7736 if msg['wsc_opcode'] != WSC_NACK:
7737 raise Exception("Unexpected message - expected WSC_Nack")
7738
7739 dev[0].request("WPS_CANCEL")
7740 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7741 dev[0].wait_disconnected()
7742
7743 def test_wps_ext_proto_m8_no_encr_settings(dev, apdev):
7744 """WPS and no Encr Settings in M6"""
7745 eap_id, e_nonce, r_nonce, bssid, r_hash1, r_hash2, r_s2, m5, authkey, keywrapkey = wps_to_m5(dev, apdev)
7746
7747 logger.debug("Send M6 to STA")
7748 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7749 attrs += build_attr_msg_type(WPS_M6)
7750 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7751 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7752 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7753 attrs += build_attr_authenticator(authkey, m5, attrs)
7754 raw_m6_attrs = attrs
7755 m6 = build_eap_wsc(1, eap_id, attrs)
7756 send_wsc_msg(dev[0], bssid, m6)
7757 eap_id = (eap_id + 1) % 256
7758
7759 logger.debug("Receive M7 from STA")
7760 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(dev[0], WSC_MSG, WPS_M7)
7761
7762 logger.debug("Send M8 to STA")
7763 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7764 attrs += build_attr_msg_type(WPS_M8)
7765 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7766 #attrs += build_attr_encr_settings(authkey, keywrapkey, m8_cred)
7767 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7768 raw_m8_attrs = attrs
7769 m8 = build_eap_wsc(1, eap_id, attrs)
7770 send_wsc_msg(dev[0], bssid, m8)
7771
7772 logger.debug("Receive WSC_Done (NACK) from STA")
7773 msg = get_wsc_msg(dev[0])
7774 if msg['wsc_opcode'] != WSC_NACK:
7775 raise Exception("Unexpected message - expected WSC_Nack")
7776
7777 dev[0].request("WPS_CANCEL")
7778 send_wsc_msg(dev[0], bssid, build_eap_failure(eap_id))
7779 dev[0].wait_disconnected()
7780
7781 def wps_start_ext_reg(apdev, dev):
7782 addr = dev.own_addr()
7783 bssid = apdev['bssid']
7784 ssid = "test-wps-conf"
7785 appin = "12345670"
7786 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
7787 "wpa_passphrase": "12345678", "wpa": "2",
7788 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
7789 "ap_pin": appin}
7790 hapd = hostapd.add_ap(apdev, params)
7791
7792 dev.scan_for_bss(bssid, freq="2412")
7793 hapd.request("SET ext_eapol_frame_io 1")
7794 dev.request("SET ext_eapol_frame_io 1")
7795
7796 dev.request("WPS_REG " + bssid + " " + appin)
7797
7798 return addr, bssid, hapd
7799
7800 def wps_run_ap_settings_proto(dev, apdev, ap_settings, success):
7801 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7802 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7803 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7804
7805 logger.debug("Receive M1 from AP")
7806 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7807 mac_addr = m1_attrs[ATTR_MAC_ADDR]
7808 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7809 e_pk = m1_attrs[ATTR_PUBLIC_KEY]
7810
7811 appin = '12345670'
7812 uuid_r = 16*b'\x33'
7813 r_nonce = 16*b'\x44'
7814 own_private, r_pk = wsc_dh_init()
7815 authkey, keywrapkey = wsc_dh_kdf(e_pk, own_private, mac_addr, e_nonce,
7816 r_nonce)
7817 r_s1, r_s2, r_hash1, r_hash2 = wsc_dev_pw_hash(authkey, appin, e_pk, r_pk)
7818
7819 logger.debug("Send M2 to AP")
7820 m2, raw_m2_attrs = build_m2(authkey, raw_m1_attrs, msg['eap_identifier'],
7821 e_nonce, r_nonce, uuid_r, r_pk, eap_code=2)
7822 send_wsc_msg(hapd, addr, m2)
7823
7824 logger.debug("Receive M3 from AP")
7825 msg, m3_attrs, raw_m3_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M3)
7826
7827 logger.debug("Send M4 to AP")
7828 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7829 attrs += build_attr_msg_type(WPS_M4)
7830 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7831 attrs += build_wsc_attr(ATTR_R_HASH1, r_hash1)
7832 attrs += build_wsc_attr(ATTR_R_HASH2, r_hash2)
7833 data = build_wsc_attr(ATTR_R_SNONCE1, r_s1)
7834 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7835 attrs += build_attr_authenticator(authkey, raw_m3_attrs, attrs)
7836 raw_m4_attrs = attrs
7837 m4 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7838 send_wsc_msg(hapd, addr, m4)
7839
7840 logger.debug("Receive M5 from AP")
7841 msg, m5_attrs, raw_m5_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M5)
7842
7843 logger.debug("Send M6 to STA")
7844 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7845 attrs += build_attr_msg_type(WPS_M6)
7846 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7847 data = build_wsc_attr(ATTR_R_SNONCE2, r_s2)
7848 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
7849 attrs += build_attr_authenticator(authkey, raw_m5_attrs, attrs)
7850 raw_m6_attrs = attrs
7851 m6 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7852 send_wsc_msg(hapd, addr, m6)
7853
7854 logger.debug("Receive M7 from AP")
7855 msg, m7_attrs, raw_m7_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M7)
7856
7857 logger.debug("Send M8 to STA")
7858 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
7859 attrs += build_attr_msg_type(WPS_M8)
7860 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
7861 if ap_settings:
7862 attrs += build_attr_encr_settings(authkey, keywrapkey, ap_settings)
7863 attrs += build_attr_authenticator(authkey, raw_m7_attrs, attrs)
7864 raw_m8_attrs = attrs
7865 m8 = build_eap_wsc(2, msg['eap_identifier'], attrs)
7866 send_wsc_msg(hapd, addr, m8)
7867
7868 if success:
7869 ev = hapd.wait_event(["WPS-NEW-AP-SETTINGS"], timeout=5)
7870 if ev is None:
7871 raise Exception("New AP settings not reported")
7872 logger.debug("Receive WSC_Done from AP")
7873 msg = get_wsc_msg(hapd)
7874 if msg['wsc_opcode'] != WSC_Done:
7875 raise Exception("Unexpected message - expected WSC_Done")
7876
7877 logger.debug("Send WSC_ACK to AP")
7878 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
7879 eap_code=2)
7880 send_wsc_msg(hapd, addr, ack)
7881 dev[0].wait_disconnected()
7882 else:
7883 ev = hapd.wait_event(["WPS-FAIL"], timeout=5)
7884 if ev is None:
7885 raise Exception("WPS failure not reported")
7886 logger.debug("Receive WSC_NACK from AP")
7887 msg = get_wsc_msg(hapd)
7888 if msg['wsc_opcode'] != WSC_NACK:
7889 raise Exception("Unexpected message - expected WSC_NACK")
7890
7891 logger.debug("Send WSC_NACK to AP")
7892 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7893 eap_code=2)
7894 send_wsc_msg(hapd, addr, nack)
7895 dev[0].wait_disconnected()
7896
7897 def test_wps_ext_ap_settings_success(dev, apdev):
7898 """WPS and AP Settings: success"""
7899 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7900 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7901 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7902 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7903 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7904 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7905 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7906
7907 @remote_compatible
7908 def test_wps_ext_ap_settings_missing(dev, apdev):
7909 """WPS and AP Settings: missing"""
7910 wps_run_ap_settings_proto(dev, apdev, None, False)
7911
7912 @remote_compatible
7913 def test_wps_ext_ap_settings_mac_addr_mismatch(dev, apdev):
7914 """WPS and AP Settings: MAC Address mismatch"""
7915 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7916 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7917 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7918 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7919 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7920 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, '\x00\x00\x00\x00\x00\x00')
7921 wps_run_ap_settings_proto(dev, apdev, ap_settings, True)
7922
7923 @remote_compatible
7924 def test_wps_ext_ap_settings_mac_addr_missing(dev, apdev):
7925 """WPS and AP Settings: missing MAC Address"""
7926 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7927 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7928 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7929 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x01')
7930 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7931 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7932
7933 @remote_compatible
7934 def test_wps_ext_ap_settings_reject_encr_type(dev, apdev):
7935 """WPS and AP Settings: reject Encr Type"""
7936 ap_settings = build_wsc_attr(ATTR_NETWORK_INDEX, '\x01')
7937 ap_settings += build_wsc_attr(ATTR_SSID, "test")
7938 ap_settings += build_wsc_attr(ATTR_AUTH_TYPE, '\x00\x01')
7939 ap_settings += build_wsc_attr(ATTR_ENCR_TYPE, '\x00\x00')
7940 ap_settings += build_wsc_attr(ATTR_NETWORK_KEY, '')
7941 ap_settings += build_wsc_attr(ATTR_MAC_ADDR, binascii.unhexlify(apdev[0]['bssid'].replace(':', '')))
7942 wps_run_ap_settings_proto(dev, apdev, ap_settings, False)
7943
7944 @remote_compatible
7945 def test_wps_ext_ap_settings_m2d(dev, apdev):
7946 """WPS and AP Settings: M2D"""
7947 addr, bssid, hapd = wps_start_ext_reg(apdev[0], dev[0])
7948 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7949 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7950
7951 logger.debug("Receive M1 from AP")
7952 msg, m1_attrs, raw_m1_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M1)
7953 e_nonce = m1_attrs[ATTR_ENROLLEE_NONCE]
7954
7955 r_nonce = 16*'\x44'
7956 uuid_r = 16*'\x33'
7957
7958 logger.debug("Send M2D to AP")
7959 m2d, raw_m2d_attrs = build_m2d(raw_m1_attrs, msg['eap_identifier'],
7960 e_nonce, r_nonce, uuid_r,
7961 dev_pw_id='\x00\x00', eap_code=2)
7962 send_wsc_msg(hapd, addr, m2d)
7963
7964 ev = hapd.wait_event(["WPS-M2D"], timeout=5)
7965 if ev is None:
7966 raise Exception("M2D not reported")
7967
7968 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
7969
7970 def wps_wait_ap_nack(hapd, dev, e_nonce, r_nonce):
7971 logger.debug("Receive WSC_NACK from AP")
7972 msg = get_wsc_msg(hapd)
7973 if msg['wsc_opcode'] != WSC_NACK:
7974 raise Exception("Unexpected message - expected WSC_NACK")
7975
7976 logger.debug("Send WSC_NACK to AP")
7977 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
7978 eap_code=2)
7979 send_wsc_msg(hapd, dev.own_addr(), nack)
7980 dev.wait_disconnected()
7981
7982 @remote_compatible
7983 def test_wps_ext_m3_missing_e_hash1(dev, apdev):
7984 """WPS proto: M3 missing E-Hash1"""
7985 pin = "12345670"
7986 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
7987 wps_ext_eap_identity_req(dev[0], hapd, bssid)
7988 wps_ext_eap_identity_resp(hapd, dev[0], addr)
7989
7990 logger.debug("Receive WSC/Start from AP")
7991 msg = get_wsc_msg(hapd)
7992 if msg['wsc_opcode'] != WSC_Start:
7993 raise Exception("Unexpected Op-Code for WSC/Start")
7994
7995 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
7996 uuid_e = 16*b'\x11'
7997 e_nonce = 16*b'\x22'
7998 own_private, e_pk = wsc_dh_init()
7999
8000 logger.debug("Send M1 to AP")
8001 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8002 e_nonce, e_pk)
8003 send_wsc_msg(hapd, addr, m1)
8004
8005 logger.debug("Receive M2 from AP")
8006 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8007 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8008 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8009
8010 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8011 r_nonce)
8012 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8013
8014 logger.debug("Send M3 to AP")
8015 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8016 attrs += build_attr_msg_type(WPS_M3)
8017 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8018 #attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8019 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8020 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8021 raw_m3_attrs = attrs
8022 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8023 send_wsc_msg(hapd, addr, m3)
8024
8025 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8026
8027 @remote_compatible
8028 def test_wps_ext_m3_missing_e_hash2(dev, apdev):
8029 """WPS proto: M3 missing E-Hash2"""
8030 pin = "12345670"
8031 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8032 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8033 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8034
8035 logger.debug("Receive WSC/Start from AP")
8036 msg = get_wsc_msg(hapd)
8037 if msg['wsc_opcode'] != WSC_Start:
8038 raise Exception("Unexpected Op-Code for WSC/Start")
8039
8040 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8041 uuid_e = 16*b'\x11'
8042 e_nonce = 16*b'\x22'
8043 own_private, e_pk = wsc_dh_init()
8044
8045 logger.debug("Send M1 to AP")
8046 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8047 e_nonce, e_pk)
8048 send_wsc_msg(hapd, addr, m1)
8049
8050 logger.debug("Receive M2 from AP")
8051 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8052 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8053 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8054
8055 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8056 r_nonce)
8057 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8058
8059 logger.debug("Send M3 to AP")
8060 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8061 attrs += build_attr_msg_type(WPS_M3)
8062 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8063 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8064 #attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8065 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8066 raw_m3_attrs = attrs
8067 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8068 send_wsc_msg(hapd, addr, m3)
8069
8070 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8071
8072 @remote_compatible
8073 def test_wps_ext_m5_missing_e_snonce1(dev, apdev):
8074 """WPS proto: M5 missing E-SNonce1"""
8075 pin = "12345670"
8076 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8077 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8078 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8079
8080 logger.debug("Receive WSC/Start from AP")
8081 msg = get_wsc_msg(hapd)
8082 if msg['wsc_opcode'] != WSC_Start:
8083 raise Exception("Unexpected Op-Code for WSC/Start")
8084
8085 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8086 uuid_e = 16*b'\x11'
8087 e_nonce = 16*b'\x22'
8088 own_private, e_pk = wsc_dh_init()
8089
8090 logger.debug("Send M1 to AP")
8091 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8092 e_nonce, e_pk)
8093 send_wsc_msg(hapd, addr, m1)
8094
8095 logger.debug("Receive M2 from AP")
8096 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8097 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8098 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8099
8100 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8101 r_nonce)
8102 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8103
8104 logger.debug("Send M3 to AP")
8105 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8106 attrs += build_attr_msg_type(WPS_M3)
8107 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8108 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8109 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8110 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8111 raw_m3_attrs = attrs
8112 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8113 send_wsc_msg(hapd, addr, m3)
8114
8115 logger.debug("Receive M4 from AP")
8116 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8117
8118 logger.debug("Send M5 to AP")
8119 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8120 attrs += build_attr_msg_type(WPS_M5)
8121 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8122 #data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8123 data = b''
8124 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8125 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8126 raw_m5_attrs = attrs
8127 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8128 send_wsc_msg(hapd, addr, m5)
8129
8130 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8131
8132 @remote_compatible
8133 def test_wps_ext_m5_e_snonce1_mismatch(dev, apdev):
8134 """WPS proto: M5 E-SNonce1 mismatch"""
8135 pin = "12345670"
8136 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8137 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8138 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8139
8140 logger.debug("Receive WSC/Start from AP")
8141 msg = get_wsc_msg(hapd)
8142 if msg['wsc_opcode'] != WSC_Start:
8143 raise Exception("Unexpected Op-Code for WSC/Start")
8144
8145 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8146 uuid_e = 16*b'\x11'
8147 e_nonce = 16*b'\x22'
8148 own_private, e_pk = wsc_dh_init()
8149
8150 logger.debug("Send M1 to AP")
8151 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8152 e_nonce, e_pk)
8153 send_wsc_msg(hapd, addr, m1)
8154
8155 logger.debug("Receive M2 from AP")
8156 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8157 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8158 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8159
8160 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8161 r_nonce)
8162 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8163
8164 logger.debug("Send M3 to AP")
8165 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8166 attrs += build_attr_msg_type(WPS_M3)
8167 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8168 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8169 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8170 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8171 raw_m3_attrs = attrs
8172 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8173 send_wsc_msg(hapd, addr, m3)
8174
8175 logger.debug("Receive M4 from AP")
8176 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8177
8178 logger.debug("Send M5 to AP")
8179 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8180 attrs += build_attr_msg_type(WPS_M5)
8181 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8182 data = build_wsc_attr(ATTR_E_SNONCE1, 16*'\x00')
8183 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8184 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8185 raw_m5_attrs = attrs
8186 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8187 send_wsc_msg(hapd, addr, m5)
8188
8189 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8190
8191 def test_wps_ext_m7_missing_e_snonce2(dev, apdev):
8192 """WPS proto: M7 missing E-SNonce2"""
8193 pin = "12345670"
8194 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8195 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8196 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8197
8198 logger.debug("Receive WSC/Start from AP")
8199 msg = get_wsc_msg(hapd)
8200 if msg['wsc_opcode'] != WSC_Start:
8201 raise Exception("Unexpected Op-Code for WSC/Start")
8202
8203 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8204 uuid_e = 16*b'\x11'
8205 e_nonce = 16*b'\x22'
8206 own_private, e_pk = wsc_dh_init()
8207
8208 logger.debug("Send M1 to AP")
8209 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8210 e_nonce, e_pk)
8211 send_wsc_msg(hapd, addr, m1)
8212
8213 logger.debug("Receive M2 from AP")
8214 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8215 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8216 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8217
8218 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8219 r_nonce)
8220 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8221
8222 logger.debug("Send M3 to AP")
8223 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8224 attrs += build_attr_msg_type(WPS_M3)
8225 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8226 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8227 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8228 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8229 raw_m3_attrs = attrs
8230 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8231 send_wsc_msg(hapd, addr, m3)
8232
8233 logger.debug("Receive M4 from AP")
8234 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8235
8236 logger.debug("Send M5 to AP")
8237 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8238 attrs += build_attr_msg_type(WPS_M5)
8239 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8240 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8241 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8242 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8243 raw_m5_attrs = attrs
8244 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8245 send_wsc_msg(hapd, addr, m5)
8246
8247 logger.debug("Receive M6 from AP")
8248 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8249
8250 logger.debug("Send M7 to AP")
8251 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8252 attrs += build_attr_msg_type(WPS_M7)
8253 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8254 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
8255 data = b''
8256 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8257 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8258 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8259 raw_m7_attrs = attrs
8260 send_wsc_msg(hapd, addr, m7)
8261
8262 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8263
8264 @remote_compatible
8265 def test_wps_ext_m7_e_snonce2_mismatch(dev, apdev):
8266 """WPS proto: M7 E-SNonce2 mismatch"""
8267 pin = "12345670"
8268 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8269 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8270 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8271
8272 logger.debug("Receive WSC/Start from AP")
8273 msg = get_wsc_msg(hapd)
8274 if msg['wsc_opcode'] != WSC_Start:
8275 raise Exception("Unexpected Op-Code for WSC/Start")
8276
8277 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8278 uuid_e = 16*b'\x11'
8279 e_nonce = 16*b'\x22'
8280 own_private, e_pk = wsc_dh_init()
8281
8282 logger.debug("Send M1 to AP")
8283 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8284 e_nonce, e_pk)
8285 send_wsc_msg(hapd, addr, m1)
8286
8287 logger.debug("Receive M2 from AP")
8288 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8289 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8290 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8291
8292 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8293 r_nonce)
8294 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8295
8296 logger.debug("Send M3 to AP")
8297 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8298 attrs += build_attr_msg_type(WPS_M3)
8299 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8300 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8301 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8302 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8303 raw_m3_attrs = attrs
8304 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8305 send_wsc_msg(hapd, addr, m3)
8306
8307 logger.debug("Receive M4 from AP")
8308 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8309
8310 logger.debug("Send M5 to AP")
8311 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8312 attrs += build_attr_msg_type(WPS_M5)
8313 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8314 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8315 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8316 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8317 raw_m5_attrs = attrs
8318 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8319 send_wsc_msg(hapd, addr, m5)
8320
8321 logger.debug("Receive M6 from AP")
8322 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
8323
8324 logger.debug("Send M7 to AP")
8325 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8326 attrs += build_attr_msg_type(WPS_M7)
8327 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8328 data = build_wsc_attr(ATTR_E_SNONCE2, 16*'\x00')
8329 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8330 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
8331 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8332 raw_m7_attrs = attrs
8333 send_wsc_msg(hapd, addr, m7)
8334
8335 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8336
8337 @remote_compatible
8338 def test_wps_ext_m1_pubkey_oom(dev, apdev):
8339 """WPS proto: M1 PubKey OOM"""
8340 pin = "12345670"
8341 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8342 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8343 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8344
8345 logger.debug("Receive WSC/Start from AP")
8346 msg = get_wsc_msg(hapd)
8347 if msg['wsc_opcode'] != WSC_Start:
8348 raise Exception("Unexpected Op-Code for WSC/Start")
8349
8350 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8351 uuid_e = 16*'\x11'
8352 e_nonce = 16*'\x22'
8353 own_private, e_pk = wsc_dh_init()
8354
8355 logger.debug("Send M1 to AP")
8356 with alloc_fail(hapd, 1, "wpabuf_alloc_copy;wps_process_pubkey"):
8357 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8358 e_nonce, e_pk)
8359 send_wsc_msg(hapd, addr, m1)
8360 wps_wait_eap_failure(hapd, dev[0])
8361
8362 def wps_wait_eap_failure(hapd, dev):
8363 ev = hapd.wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
8364 if ev is None:
8365 raise Exception("EAP-Failure not reported")
8366 dev.wait_disconnected()
8367
8368 @remote_compatible
8369 def test_wps_ext_m3_m1(dev, apdev):
8370 """WPS proto: M3 replaced with M1"""
8371 pin = "12345670"
8372 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8373 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8374 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8375
8376 logger.debug("Receive WSC/Start from AP")
8377 msg = get_wsc_msg(hapd)
8378 if msg['wsc_opcode'] != WSC_Start:
8379 raise Exception("Unexpected Op-Code for WSC/Start")
8380
8381 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8382 uuid_e = 16*b'\x11'
8383 e_nonce = 16*b'\x22'
8384 own_private, e_pk = wsc_dh_init()
8385
8386 logger.debug("Send M1 to AP")
8387 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8388 e_nonce, e_pk)
8389 send_wsc_msg(hapd, addr, m1)
8390
8391 logger.debug("Receive M2 from AP")
8392 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8393 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8394 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8395
8396 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8397 r_nonce)
8398 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8399
8400 logger.debug("Send M3(M1) to AP")
8401 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8402 attrs += build_attr_msg_type(WPS_M1)
8403 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8404 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8405 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8406 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8407 raw_m3_attrs = attrs
8408 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8409 send_wsc_msg(hapd, addr, m3)
8410
8411 wps_wait_eap_failure(hapd, dev[0])
8412
8413 @remote_compatible
8414 def test_wps_ext_m5_m3(dev, apdev):
8415 """WPS proto: M5 replaced with M3"""
8416 pin = "12345670"
8417 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8418 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8419 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8420
8421 logger.debug("Receive WSC/Start from AP")
8422 msg = get_wsc_msg(hapd)
8423 if msg['wsc_opcode'] != WSC_Start:
8424 raise Exception("Unexpected Op-Code for WSC/Start")
8425
8426 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8427 uuid_e = 16*b'\x11'
8428 e_nonce = 16*b'\x22'
8429 own_private, e_pk = wsc_dh_init()
8430
8431 logger.debug("Send M1 to AP")
8432 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8433 e_nonce, e_pk)
8434 send_wsc_msg(hapd, addr, m1)
8435
8436 logger.debug("Receive M2 from AP")
8437 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8438 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8439 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8440
8441 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8442 r_nonce)
8443 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8444
8445 logger.debug("Send M3 to AP")
8446 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8447 attrs += build_attr_msg_type(WPS_M3)
8448 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8449 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8450 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8451 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8452 raw_m3_attrs = attrs
8453 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8454 send_wsc_msg(hapd, addr, m3)
8455
8456 logger.debug("Receive M4 from AP")
8457 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
8458
8459 logger.debug("Send M5(M3) to AP")
8460 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8461 attrs += build_attr_msg_type(WPS_M3)
8462 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8463 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
8464 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
8465 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
8466 raw_m5_attrs = attrs
8467 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8468 send_wsc_msg(hapd, addr, m5)
8469
8470 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8471
8472 @remote_compatible
8473 def test_wps_ext_m3_m2(dev, apdev):
8474 """WPS proto: M3 replaced with M2"""
8475 pin = "12345670"
8476 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8477 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8478 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8479
8480 logger.debug("Receive WSC/Start from AP")
8481 msg = get_wsc_msg(hapd)
8482 if msg['wsc_opcode'] != WSC_Start:
8483 raise Exception("Unexpected Op-Code for WSC/Start")
8484
8485 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8486 uuid_e = 16*b'\x11'
8487 e_nonce = 16*b'\x22'
8488 own_private, e_pk = wsc_dh_init()
8489
8490 logger.debug("Send M1 to AP")
8491 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8492 e_nonce, e_pk)
8493 send_wsc_msg(hapd, addr, m1)
8494
8495 logger.debug("Receive M2 from AP")
8496 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8497 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8498 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8499
8500 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8501 r_nonce)
8502 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8503
8504 logger.debug("Send M3(M2) to AP")
8505 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8506 attrs += build_attr_msg_type(WPS_M2)
8507 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8508 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8509 raw_m3_attrs = attrs
8510 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8511 send_wsc_msg(hapd, addr, m3)
8512
8513 wps_wait_eap_failure(hapd, dev[0])
8514
8515 @remote_compatible
8516 def test_wps_ext_m3_m5(dev, apdev):
8517 """WPS proto: M3 replaced with M5"""
8518 pin = "12345670"
8519 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8520 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8521 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8522
8523 logger.debug("Receive WSC/Start from AP")
8524 msg = get_wsc_msg(hapd)
8525 if msg['wsc_opcode'] != WSC_Start:
8526 raise Exception("Unexpected Op-Code for WSC/Start")
8527
8528 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8529 uuid_e = 16*b'\x11'
8530 e_nonce = 16*b'\x22'
8531 own_private, e_pk = wsc_dh_init()
8532
8533 logger.debug("Send M1 to AP")
8534 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8535 e_nonce, e_pk)
8536 send_wsc_msg(hapd, addr, m1)
8537
8538 logger.debug("Receive M2 from AP")
8539 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8540 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8541 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8542
8543 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8544 r_nonce)
8545 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8546
8547 logger.debug("Send M3(M5) to AP")
8548 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8549 attrs += build_attr_msg_type(WPS_M5)
8550 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8551 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8552 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8553 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8554 raw_m3_attrs = attrs
8555 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8556 send_wsc_msg(hapd, addr, m3)
8557
8558 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8559
8560 @remote_compatible
8561 def test_wps_ext_m3_m7(dev, apdev):
8562 """WPS proto: M3 replaced with M7"""
8563 pin = "12345670"
8564 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8565 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8566 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8567
8568 logger.debug("Receive WSC/Start from AP")
8569 msg = get_wsc_msg(hapd)
8570 if msg['wsc_opcode'] != WSC_Start:
8571 raise Exception("Unexpected Op-Code for WSC/Start")
8572
8573 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8574 uuid_e = 16*b'\x11'
8575 e_nonce = 16*b'\x22'
8576 own_private, e_pk = wsc_dh_init()
8577
8578 logger.debug("Send M1 to AP")
8579 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8580 e_nonce, e_pk)
8581 send_wsc_msg(hapd, addr, m1)
8582
8583 logger.debug("Receive M2 from AP")
8584 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8585 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8586 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8587
8588 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8589 r_nonce)
8590 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8591
8592 logger.debug("Send M3(M7) to AP")
8593 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8594 attrs += build_attr_msg_type(WPS_M7)
8595 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
8596 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
8597 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
8598 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8599 raw_m3_attrs = attrs
8600 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
8601 send_wsc_msg(hapd, addr, m3)
8602
8603 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
8604
8605 @remote_compatible
8606 def test_wps_ext_m3_done(dev, apdev):
8607 """WPS proto: M3 replaced with WSC_Done"""
8608 pin = "12345670"
8609 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8610 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8611 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8612
8613 logger.debug("Receive WSC/Start from AP")
8614 msg = get_wsc_msg(hapd)
8615 if msg['wsc_opcode'] != WSC_Start:
8616 raise Exception("Unexpected Op-Code for WSC/Start")
8617
8618 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8619 uuid_e = 16*b'\x11'
8620 e_nonce = 16*b'\x22'
8621 own_private, e_pk = wsc_dh_init()
8622
8623 logger.debug("Send M1 to AP")
8624 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8625 e_nonce, e_pk)
8626 send_wsc_msg(hapd, addr, m1)
8627
8628 logger.debug("Receive M2 from AP")
8629 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8630 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8631 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8632
8633 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8634 r_nonce)
8635 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8636
8637 logger.debug("Send M3(WSC_Done) to AP")
8638 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
8639 attrs += build_attr_msg_type(WPS_WSC_DONE)
8640 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
8641 raw_m3_attrs = attrs
8642 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
8643 send_wsc_msg(hapd, addr, m3)
8644
8645 wps_wait_eap_failure(hapd, dev[0])
8646
8647 @remote_compatible
8648 def test_wps_ext_m2_nack_invalid(dev, apdev):
8649 """WPS proto: M2 followed by invalid NACK"""
8650 pin = "12345670"
8651 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8652 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8653 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8654
8655 logger.debug("Receive WSC/Start from AP")
8656 msg = get_wsc_msg(hapd)
8657 if msg['wsc_opcode'] != WSC_Start:
8658 raise Exception("Unexpected Op-Code for WSC/Start")
8659
8660 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8661 uuid_e = 16*b'\x11'
8662 e_nonce = 16*b'\x22'
8663 own_private, e_pk = wsc_dh_init()
8664
8665 logger.debug("Send M1 to AP")
8666 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8667 e_nonce, e_pk)
8668 send_wsc_msg(hapd, addr, m1)
8669
8670 logger.debug("Receive M2 from AP")
8671 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8672 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8673 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8674
8675 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8676 r_nonce)
8677 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8678
8679 logger.debug("Send WSC_NACK to AP")
8680 attrs = b'\x10\x00\x00'
8681 nack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_NACK)
8682 send_wsc_msg(hapd, addr, nack)
8683
8684 wps_wait_eap_failure(hapd, dev[0])
8685
8686 @remote_compatible
8687 def test_wps_ext_m2_nack_no_msg_type(dev, apdev):
8688 """WPS proto: M2 followed by NACK without Msg Type"""
8689 pin = "12345670"
8690 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8691 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8692 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8693
8694 logger.debug("Receive WSC/Start from AP")
8695 msg = get_wsc_msg(hapd)
8696 if msg['wsc_opcode'] != WSC_Start:
8697 raise Exception("Unexpected Op-Code for WSC/Start")
8698
8699 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8700 uuid_e = 16*b'\x11'
8701 e_nonce = 16*b'\x22'
8702 own_private, e_pk = wsc_dh_init()
8703
8704 logger.debug("Send M1 to AP")
8705 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8706 e_nonce, e_pk)
8707 send_wsc_msg(hapd, addr, m1)
8708
8709 logger.debug("Receive M2 from AP")
8710 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8711 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8712 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8713
8714 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8715 r_nonce)
8716 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8717
8718 logger.debug("Send WSC_NACK to AP")
8719 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8720 msg_type=None, eap_code=2)
8721 send_wsc_msg(hapd, addr, nack)
8722
8723 wps_wait_eap_failure(hapd, dev[0])
8724
8725 @remote_compatible
8726 def test_wps_ext_m2_nack_invalid_msg_type(dev, apdev):
8727 """WPS proto: M2 followed by NACK with invalid Msg Type"""
8728 pin = "12345670"
8729 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8730 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8731 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8732
8733 logger.debug("Receive WSC/Start from AP")
8734 msg = get_wsc_msg(hapd)
8735 if msg['wsc_opcode'] != WSC_Start:
8736 raise Exception("Unexpected Op-Code for WSC/Start")
8737
8738 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8739 uuid_e = 16*b'\x11'
8740 e_nonce = 16*b'\x22'
8741 own_private, e_pk = wsc_dh_init()
8742
8743 logger.debug("Send M1 to AP")
8744 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8745 e_nonce, e_pk)
8746 send_wsc_msg(hapd, addr, m1)
8747
8748 logger.debug("Receive M2 from AP")
8749 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8750 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8751 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8752
8753 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8754 r_nonce)
8755 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8756
8757 logger.debug("Send WSC_NACK to AP")
8758 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8759 msg_type=WPS_WSC_ACK, eap_code=2)
8760 send_wsc_msg(hapd, addr, nack)
8761
8762 wps_wait_eap_failure(hapd, dev[0])
8763
8764 @remote_compatible
8765 def test_wps_ext_m2_nack_e_nonce_mismatch(dev, apdev):
8766 """WPS proto: M2 followed by NACK with e-nonce mismatch"""
8767 pin = "12345670"
8768 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8769 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8770 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8771
8772 logger.debug("Receive WSC/Start from AP")
8773 msg = get_wsc_msg(hapd)
8774 if msg['wsc_opcode'] != WSC_Start:
8775 raise Exception("Unexpected Op-Code for WSC/Start")
8776
8777 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8778 uuid_e = 16*b'\x11'
8779 e_nonce = 16*b'\x22'
8780 own_private, e_pk = wsc_dh_init()
8781
8782 logger.debug("Send M1 to AP")
8783 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8784 e_nonce, e_pk)
8785 send_wsc_msg(hapd, addr, m1)
8786
8787 logger.debug("Receive M2 from AP")
8788 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8789 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8790 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8791
8792 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8793 r_nonce)
8794 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8795
8796 logger.debug("Send WSC_NACK to AP")
8797 nack, attrs = build_nack(msg['eap_identifier'], 16*b'\x00', r_nonce,
8798 eap_code=2)
8799 send_wsc_msg(hapd, addr, nack)
8800
8801 wps_wait_eap_failure(hapd, dev[0])
8802
8803 @remote_compatible
8804 def test_wps_ext_m2_nack_no_config_error(dev, apdev):
8805 """WPS proto: M2 followed by NACK without Config Error"""
8806 pin = "12345670"
8807 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8808 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8809 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8810
8811 logger.debug("Receive WSC/Start from AP")
8812 msg = get_wsc_msg(hapd)
8813 if msg['wsc_opcode'] != WSC_Start:
8814 raise Exception("Unexpected Op-Code for WSC/Start")
8815
8816 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8817 uuid_e = 16*b'\x11'
8818 e_nonce = 16*b'\x22'
8819 own_private, e_pk = wsc_dh_init()
8820
8821 logger.debug("Send M1 to AP")
8822 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8823 e_nonce, e_pk)
8824 send_wsc_msg(hapd, addr, m1)
8825
8826 logger.debug("Receive M2 from AP")
8827 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8828 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8829 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8830
8831 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8832 r_nonce)
8833 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8834
8835 logger.debug("Send WSC_NACK to AP")
8836 nack, attrs = build_nack(msg['eap_identifier'], e_nonce, r_nonce,
8837 config_error=None, eap_code=2)
8838 send_wsc_msg(hapd, addr, nack)
8839
8840 wps_wait_eap_failure(hapd, dev[0])
8841
8842 @remote_compatible
8843 def test_wps_ext_m2_ack_invalid(dev, apdev):
8844 """WPS proto: M2 followed by invalid ACK"""
8845 pin = "12345670"
8846 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8847 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8848 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8849
8850 logger.debug("Receive WSC/Start from AP")
8851 msg = get_wsc_msg(hapd)
8852 if msg['wsc_opcode'] != WSC_Start:
8853 raise Exception("Unexpected Op-Code for WSC/Start")
8854
8855 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8856 uuid_e = 16*b'\x11'
8857 e_nonce = 16*b'\x22'
8858 own_private, e_pk = wsc_dh_init()
8859
8860 logger.debug("Send M1 to AP")
8861 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8862 e_nonce, e_pk)
8863 send_wsc_msg(hapd, addr, m1)
8864
8865 logger.debug("Receive M2 from AP")
8866 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8867 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8868 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8869
8870 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8871 r_nonce)
8872 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8873
8874 logger.debug("Send WSC_ACK to AP")
8875 attrs = b'\x10\x00\x00'
8876 ack = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_ACK)
8877 send_wsc_msg(hapd, addr, ack)
8878
8879 wps_wait_eap_failure(hapd, dev[0])
8880
8881 @remote_compatible
8882 def test_wps_ext_m2_ack(dev, apdev):
8883 """WPS proto: M2 followed by ACK"""
8884 pin = "12345670"
8885 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8886 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8887 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8888
8889 logger.debug("Receive WSC/Start from AP")
8890 msg = get_wsc_msg(hapd)
8891 if msg['wsc_opcode'] != WSC_Start:
8892 raise Exception("Unexpected Op-Code for WSC/Start")
8893
8894 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8895 uuid_e = 16*b'\x11'
8896 e_nonce = 16*b'\x22'
8897 own_private, e_pk = wsc_dh_init()
8898
8899 logger.debug("Send M1 to AP")
8900 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8901 e_nonce, e_pk)
8902 send_wsc_msg(hapd, addr, m1)
8903
8904 logger.debug("Receive M2 from AP")
8905 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8906 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8907 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8908
8909 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8910 r_nonce)
8911 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8912
8913 logger.debug("Send WSC_ACK to AP")
8914 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce, eap_code=2)
8915 send_wsc_msg(hapd, addr, ack)
8916
8917 wps_wait_eap_failure(hapd, dev[0])
8918
8919 @remote_compatible
8920 def test_wps_ext_m2_ack_no_msg_type(dev, apdev):
8921 """WPS proto: M2 followed by ACK missing Msg Type"""
8922 pin = "12345670"
8923 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8924 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8925 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8926
8927 logger.debug("Receive WSC/Start from AP")
8928 msg = get_wsc_msg(hapd)
8929 if msg['wsc_opcode'] != WSC_Start:
8930 raise Exception("Unexpected Op-Code for WSC/Start")
8931
8932 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8933 uuid_e = 16*b'\x11'
8934 e_nonce = 16*b'\x22'
8935 own_private, e_pk = wsc_dh_init()
8936
8937 logger.debug("Send M1 to AP")
8938 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8939 e_nonce, e_pk)
8940 send_wsc_msg(hapd, addr, m1)
8941
8942 logger.debug("Receive M2 from AP")
8943 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8944 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8945 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8946
8947 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8948 r_nonce)
8949 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8950
8951 logger.debug("Send WSC_ACK to AP")
8952 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8953 msg_type=None, eap_code=2)
8954 send_wsc_msg(hapd, addr, ack)
8955
8956 wps_wait_eap_failure(hapd, dev[0])
8957
8958 @remote_compatible
8959 def test_wps_ext_m2_ack_invalid_msg_type(dev, apdev):
8960 """WPS proto: M2 followed by ACK with invalid Msg Type"""
8961 pin = "12345670"
8962 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
8963 wps_ext_eap_identity_req(dev[0], hapd, bssid)
8964 wps_ext_eap_identity_resp(hapd, dev[0], addr)
8965
8966 logger.debug("Receive WSC/Start from AP")
8967 msg = get_wsc_msg(hapd)
8968 if msg['wsc_opcode'] != WSC_Start:
8969 raise Exception("Unexpected Op-Code for WSC/Start")
8970
8971 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
8972 uuid_e = 16*b'\x11'
8973 e_nonce = 16*b'\x22'
8974 own_private, e_pk = wsc_dh_init()
8975
8976 logger.debug("Send M1 to AP")
8977 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
8978 e_nonce, e_pk)
8979 send_wsc_msg(hapd, addr, m1)
8980
8981 logger.debug("Receive M2 from AP")
8982 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
8983 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
8984 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
8985
8986 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
8987 r_nonce)
8988 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
8989
8990 logger.debug("Send WSC_ACK to AP")
8991 ack, attrs = build_ack(msg['eap_identifier'], e_nonce, r_nonce,
8992 msg_type=WPS_WSC_NACK, eap_code=2)
8993 send_wsc_msg(hapd, addr, ack)
8994
8995 wps_wait_eap_failure(hapd, dev[0])
8996
8997 @remote_compatible
8998 def test_wps_ext_m2_ack_e_nonce_mismatch(dev, apdev):
8999 """WPS proto: M2 followed by ACK with e-nonce mismatch"""
9000 pin = "12345670"
9001 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9002 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9003 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9004
9005 logger.debug("Receive WSC/Start from AP")
9006 msg = get_wsc_msg(hapd)
9007 if msg['wsc_opcode'] != WSC_Start:
9008 raise Exception("Unexpected Op-Code for WSC/Start")
9009
9010 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9011 uuid_e = 16*b'\x11'
9012 e_nonce = 16*b'\x22'
9013 own_private, e_pk = wsc_dh_init()
9014
9015 logger.debug("Send M1 to AP")
9016 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9017 e_nonce, e_pk)
9018 send_wsc_msg(hapd, addr, m1)
9019
9020 logger.debug("Receive M2 from AP")
9021 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9022 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9023 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9024
9025 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9026 r_nonce)
9027 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9028
9029 logger.debug("Send WSC_ACK to AP")
9030 ack, attrs = build_ack(msg['eap_identifier'], 16*b'\x00', r_nonce,
9031 eap_code=2)
9032 send_wsc_msg(hapd, addr, ack)
9033
9034 wps_wait_eap_failure(hapd, dev[0])
9035
9036 @remote_compatible
9037 def test_wps_ext_m1_invalid(dev, apdev):
9038 """WPS proto: M1 failing parsing"""
9039 pin = "12345670"
9040 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9041 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9042 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9043
9044 logger.debug("Receive WSC/Start from AP")
9045 msg = get_wsc_msg(hapd)
9046 if msg['wsc_opcode'] != WSC_Start:
9047 raise Exception("Unexpected Op-Code for WSC/Start")
9048
9049 logger.debug("Send M1 to AP")
9050 attrs = b'\x10\x00\x00'
9051 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9052 send_wsc_msg(hapd, addr, m1)
9053
9054 wps_wait_eap_failure(hapd, dev[0])
9055
9056 def test_wps_ext_m1_missing_msg_type(dev, apdev):
9057 """WPS proto: M1 missing Msg Type"""
9058 pin = "12345670"
9059 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9060 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9061 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9062
9063 logger.debug("Receive WSC/Start from AP")
9064 msg = get_wsc_msg(hapd)
9065 if msg['wsc_opcode'] != WSC_Start:
9066 raise Exception("Unexpected Op-Code for WSC/Start")
9067
9068 logger.debug("Send M1 to AP")
9069 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9070 m1 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9071 send_wsc_msg(hapd, addr, m1)
9072
9073 wps_wait_ap_nack(hapd, dev[0], 16*b'\x00', 16*b'\x00')
9074
9075 def wps_ext_wsc_done(dev, apdev):
9076 pin = "12345670"
9077 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9078 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9079 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9080
9081 logger.debug("Receive WSC/Start from AP")
9082 msg = get_wsc_msg(hapd)
9083 if msg['wsc_opcode'] != WSC_Start:
9084 raise Exception("Unexpected Op-Code for WSC/Start")
9085
9086 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9087 uuid_e = 16*b'\x11'
9088 e_nonce = 16*b'\x22'
9089 own_private, e_pk = wsc_dh_init()
9090
9091 logger.debug("Send M1 to AP")
9092 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9093 e_nonce, e_pk)
9094 send_wsc_msg(hapd, addr, m1)
9095
9096 logger.debug("Receive M2 from AP")
9097 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9098 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9099 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9100
9101 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9102 r_nonce)
9103 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9104
9105 logger.debug("Send M3 to AP")
9106 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9107 attrs += build_attr_msg_type(WPS_M3)
9108 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9109 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9110 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9111 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9112 raw_m3_attrs = attrs
9113 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9114 send_wsc_msg(hapd, addr, m3)
9115
9116 logger.debug("Receive M4 from AP")
9117 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9118
9119 logger.debug("Send M5 to AP")
9120 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9121 attrs += build_attr_msg_type(WPS_M5)
9122 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9123 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9124 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9125 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9126 raw_m5_attrs = attrs
9127 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9128 send_wsc_msg(hapd, addr, m5)
9129
9130 logger.debug("Receive M6 from AP")
9131 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9132
9133 logger.debug("Send M7 to AP")
9134 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9135 attrs += build_attr_msg_type(WPS_M7)
9136 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9137 data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9138 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9139 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9140 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9141 raw_m7_attrs = attrs
9142 send_wsc_msg(hapd, addr, m7)
9143
9144 logger.debug("Receive M8 from AP")
9145 msg, m8_attrs, raw_m8_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M8)
9146 return hapd, msg, e_nonce, r_nonce
9147
9148 @remote_compatible
9149 def test_wps_ext_wsc_done_invalid(dev, apdev):
9150 """WPS proto: invalid WSC_Done"""
9151 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9152
9153 logger.debug("Send WSC_Done to AP")
9154 attrs = b'\x10\x00\x00'
9155 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9156 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9157
9158 wps_wait_eap_failure(hapd, dev[0])
9159
9160 @remote_compatible
9161 def test_wps_ext_wsc_done_no_msg_type(dev, apdev):
9162 """WPS proto: invalid WSC_Done"""
9163 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9164
9165 logger.debug("Send WSC_Done to AP")
9166 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9167 #attrs += build_attr_msg_type(WPS_WSC_DONE)
9168 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9169 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9170 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9171 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9172
9173 wps_wait_eap_failure(hapd, dev[0])
9174
9175 @remote_compatible
9176 def test_wps_ext_wsc_done_wrong_msg_type(dev, apdev):
9177 """WPS proto: WSC_Done with wrong Msg Type"""
9178 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9179
9180 logger.debug("Send WSC_Done to AP")
9181 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9182 attrs += build_attr_msg_type(WPS_WSC_ACK)
9183 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9184 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9185 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9186 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9187
9188 wps_wait_eap_failure(hapd, dev[0])
9189
9190 @remote_compatible
9191 def test_wps_ext_wsc_done_no_e_nonce(dev, apdev):
9192 """WPS proto: WSC_Done without e_nonce"""
9193 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9194
9195 logger.debug("Send WSC_Done to AP")
9196 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9197 attrs += build_attr_msg_type(WPS_WSC_DONE)
9198 #attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9199 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9200 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9201 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9202
9203 wps_wait_eap_failure(hapd, dev[0])
9204
9205 def test_wps_ext_wsc_done_no_r_nonce(dev, apdev):
9206 """WPS proto: WSC_Done without r_nonce"""
9207 hapd, msg, e_nonce, r_nonce = wps_ext_wsc_done(dev, apdev)
9208
9209 logger.debug("Send WSC_Done to AP")
9210 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9211 attrs += build_attr_msg_type(WPS_WSC_DONE)
9212 attrs += build_wsc_attr(ATTR_ENROLLEE_NONCE, e_nonce)
9213 #attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9214 wsc_done = build_eap_wsc(2, msg['eap_identifier'], attrs, opcode=WSC_Done)
9215 send_wsc_msg(hapd, dev[0].own_addr(), wsc_done)
9216
9217 wps_wait_eap_failure(hapd, dev[0])
9218
9219 @remote_compatible
9220 def test_wps_ext_m7_no_encr_settings(dev, apdev):
9221 """WPS proto: M7 without Encr Settings"""
9222 pin = "12345670"
9223 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9224 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9225 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9226
9227 logger.debug("Receive WSC/Start from AP")
9228 msg = get_wsc_msg(hapd)
9229 if msg['wsc_opcode'] != WSC_Start:
9230 raise Exception("Unexpected Op-Code for WSC/Start")
9231
9232 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9233 uuid_e = 16*b'\x11'
9234 e_nonce = 16*b'\x22'
9235 own_private, e_pk = wsc_dh_init()
9236
9237 logger.debug("Send M1 to AP")
9238 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9239 e_nonce, e_pk)
9240 send_wsc_msg(hapd, addr, m1)
9241
9242 logger.debug("Receive M2 from AP")
9243 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9244 r_nonce = m2_attrs[ATTR_REGISTRAR_NONCE]
9245 r_pk = m2_attrs[ATTR_PUBLIC_KEY]
9246
9247 authkey, keywrapkey = wsc_dh_kdf(r_pk, own_private, mac_addr, e_nonce,
9248 r_nonce)
9249 e_s1, e_s2, e_hash1, e_hash2 = wsc_dev_pw_hash(authkey, pin, e_pk, r_pk)
9250
9251 logger.debug("Send M3 to AP")
9252 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9253 attrs += build_attr_msg_type(WPS_M3)
9254 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9255 attrs += build_wsc_attr(ATTR_E_HASH1, e_hash1)
9256 attrs += build_wsc_attr(ATTR_E_HASH2, e_hash2)
9257 attrs += build_attr_authenticator(authkey, raw_m2_attrs, attrs)
9258 raw_m3_attrs = attrs
9259 m3 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9260 send_wsc_msg(hapd, addr, m3)
9261
9262 logger.debug("Receive M4 from AP")
9263 msg, m4_attrs, raw_m4_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M4)
9264
9265 logger.debug("Send M5 to AP")
9266 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9267 attrs += build_attr_msg_type(WPS_M5)
9268 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9269 data = build_wsc_attr(ATTR_E_SNONCE1, e_s1)
9270 attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9271 attrs += build_attr_authenticator(authkey, raw_m4_attrs, attrs)
9272 raw_m5_attrs = attrs
9273 m5 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9274 send_wsc_msg(hapd, addr, m5)
9275
9276 logger.debug("Receive M6 from AP")
9277 msg, m6_attrs, raw_m6_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M6)
9278
9279 logger.debug("Send M7 to AP")
9280 attrs = build_wsc_attr(ATTR_VERSION, '\x10')
9281 attrs += build_attr_msg_type(WPS_M7)
9282 attrs += build_wsc_attr(ATTR_REGISTRAR_NONCE, r_nonce)
9283 #data = build_wsc_attr(ATTR_E_SNONCE2, e_s2)
9284 #attrs += build_attr_encr_settings(authkey, keywrapkey, data)
9285 attrs += build_attr_authenticator(authkey, raw_m6_attrs, attrs)
9286 m7 = build_eap_wsc(2, msg['eap_identifier'], attrs)
9287 raw_m7_attrs = attrs
9288 send_wsc_msg(hapd, addr, m7)
9289
9290 wps_wait_ap_nack(hapd, dev[0], e_nonce, r_nonce)
9291
9292 @remote_compatible
9293 def test_wps_ext_m1_workaround(dev, apdev):
9294 """WPS proto: M1 Manufacturer/Model workaround"""
9295 pin = "12345670"
9296 addr, bssid, hapd = wps_start_ext(apdev[0], dev[0], pin=pin)
9297 wps_ext_eap_identity_req(dev[0], hapd, bssid)
9298 wps_ext_eap_identity_resp(hapd, dev[0], addr)
9299
9300 logger.debug("Receive WSC/Start from AP")
9301 msg = get_wsc_msg(hapd)
9302 if msg['wsc_opcode'] != WSC_Start:
9303 raise Exception("Unexpected Op-Code for WSC/Start")
9304
9305 mac_addr = binascii.unhexlify(dev[0].own_addr().replace(':', ''))
9306 uuid_e = 16*b'\x11'
9307 e_nonce = 16*b'\x22'
9308 own_private, e_pk = wsc_dh_init()
9309
9310 logger.debug("Send M1 to AP")
9311 m1, raw_m1_attrs = build_m1(msg['eap_identifier'], uuid_e, mac_addr,
9312 e_nonce, e_pk, manufacturer='Apple TEST',
9313 model_name='AirPort', config_methods=b'\xff\xff')
9314 send_wsc_msg(hapd, addr, m1)
9315
9316 logger.debug("Receive M2 from AP")
9317 msg, m2_attrs, raw_m2_attrs = recv_wsc_msg(hapd, WSC_MSG, WPS_M2)
9318
9319 @remote_compatible
9320 def test_ap_wps_disable_enable(dev, apdev):
9321 """WPS and DISABLE/ENABLE AP"""
9322 hapd = wps_start_ap(apdev[0])
9323 hapd.disable()
9324 hapd.enable()
9325 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9326
9327 def test_ap_wps_upnp_web_oom(dev, apdev, params):
9328 """hostapd WPS UPnP web OOM"""
9329 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9330 hapd = add_ssdp_ap(apdev[0], ap_uuid)
9331
9332 location = ssdp_get_location(ap_uuid)
9333 url = urlparse(location)
9334 urls = upnp_get_urls(location)
9335 eventurl = urlparse(urls['event_sub_url'])
9336 ctrlurl = urlparse(urls['control_url'])
9337
9338 conn = HTTPConnection(url.netloc)
9339 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9340 conn.request("GET", "/wps_device.xml")
9341 try:
9342 resp = conn.getresponse()
9343 except:
9344 pass
9345
9346 conn = HTTPConnection(url.netloc)
9347 conn.request("GET", "/unknown")
9348 resp = conn.getresponse()
9349 if resp.status != 404:
9350 raise Exception("Unexpected HTTP result for unknown URL: %d" + resp.status)
9351
9352 with alloc_fail(hapd, 1, "web_connection_parse_get"):
9353 conn.request("GET", "/unknown")
9354 try:
9355 resp = conn.getresponse()
9356 print(resp.status)
9357 except:
9358 pass
9359
9360 conn = HTTPConnection(url.netloc)
9361 conn.request("GET", "/wps_device.xml")
9362 resp = conn.getresponse()
9363 if resp.status != 200:
9364 raise Exception("GET /wps_device.xml failed")
9365
9366 conn = HTTPConnection(url.netloc)
9367 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9368 if resp.status != 200:
9369 raise Exception("GetDeviceInfo failed")
9370
9371 with alloc_fail(hapd, 1, "web_process_get_device_info"):
9372 conn = HTTPConnection(url.netloc)
9373 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9374 if resp.status != 500:
9375 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9376
9377 with alloc_fail(hapd, 1, "wps_build_m1;web_process_get_device_info"):
9378 conn = HTTPConnection(url.netloc)
9379 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9380 if resp.status != 500:
9381 raise Exception("Internal error not reported from GetDeviceInfo OOM")
9382
9383 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_send_reply"):
9384 conn = HTTPConnection(url.netloc)
9385 try:
9386 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9387 except:
9388 pass
9389
9390 conn = HTTPConnection(url.netloc)
9391 resp = upnp_soap_action(conn, ctrlurl.path, "GetDeviceInfo")
9392 if resp.status != 200:
9393 raise Exception("GetDeviceInfo failed")
9394
9395 # No NewWLANEventType in PutWLANResponse NewMessage
9396 conn = HTTPConnection(url.netloc)
9397 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse", newmsg="foo")
9398 if resp.status != 600:
9399 raise Exception("Unexpected HTTP response: %d" % resp.status)
9400
9401 # No NewWLANEventMAC in PutWLANResponse NewMessage
9402 conn = HTTPConnection(url.netloc)
9403 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9404 newmsg="foo", neweventtype="1")
9405 if resp.status != 600:
9406 raise Exception("Unexpected HTTP response: %d" % resp.status)
9407
9408 # Invalid NewWLANEventMAC in PutWLANResponse NewMessage
9409 conn = HTTPConnection(url.netloc)
9410 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9411 newmsg="foo", neweventtype="1",
9412 neweventmac="foo")
9413 if resp.status != 600:
9414 raise Exception("Unexpected HTTP response: %d" % resp.status)
9415
9416 # Workaround for NewWLANEventMAC in PutWLANResponse NewMessage
9417 # Ignored unexpected PutWLANResponse WLANEventType 1
9418 conn = HTTPConnection(url.netloc)
9419 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9420 newmsg="foo", neweventtype="1",
9421 neweventmac="00.11.22.33.44.55")
9422 if resp.status != 500:
9423 raise Exception("Unexpected HTTP response: %d" % resp.status)
9424
9425 # PutWLANResponse NewMessage with invalid EAP message
9426 conn = HTTPConnection(url.netloc)
9427 resp = upnp_soap_action(conn, ctrlurl.path, "PutWLANResponse",
9428 newmsg="foo", neweventtype="2",
9429 neweventmac="00:11:22:33:44:55")
9430 if resp.status != 200:
9431 raise Exception("Unexpected HTTP response: %d" % resp.status)
9432
9433 with alloc_fail(hapd, 1, "web_connection_parse_subscribe"):
9434 conn = HTTPConnection(url.netloc)
9435 headers = {"callback": '<http://127.0.0.1:12345/event>',
9436 "NT": "upnp:event",
9437 "timeout": "Second-1234"}
9438 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9439 try:
9440 resp = conn.getresponse()
9441 except:
9442 pass
9443
9444 with alloc_fail(hapd, 1, "dup_binstr;web_connection_parse_subscribe"):
9445 conn = HTTPConnection(url.netloc)
9446 headers = {"callback": '<http://127.0.0.1:12345/event>',
9447 "NT": "upnp:event",
9448 "timeout": "Second-1234"}
9449 conn.request("SUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9450 resp = conn.getresponse()
9451 if resp.status != 500:
9452 raise Exception("Unexpected HTTP response: %d" % resp.status)
9453
9454 with alloc_fail(hapd, 1, "wpabuf_alloc;web_connection_parse_unsubscribe"):
9455 conn = HTTPConnection(url.netloc)
9456 headers = {"callback": '<http://127.0.0.1:12345/event>',
9457 "NT": "upnp:event",
9458 "timeout": "Second-1234"}
9459 conn.request("UNSUBSCRIBE", eventurl.path, "\r\n\r\n", headers)
9460 try:
9461 resp = conn.getresponse()
9462 except:
9463 pass
9464
9465 with alloc_fail(hapd, 1, "web_connection_unimplemented"):
9466 conn = HTTPConnection(url.netloc)
9467 conn.request("HEAD", "/wps_device.xml")
9468 try:
9469 resp = conn.getresponse()
9470 except:
9471 pass
9472
9473 def test_ap_wps_frag_ack_oom(dev, apdev):
9474 """WPS and fragment ack OOM"""
9475 dev[0].request("SET wps_fragment_size 50")
9476 hapd = wps_start_ap(apdev[0])
9477 with alloc_fail(hapd, 1, "eap_wsc_build_frag_ack"):
9478 wps_run_pbc_fail_ap(apdev[0], dev[0], hapd)
9479
9480 def wait_scan_stopped(dev):
9481 dev.request("ABORT_SCAN")
9482 for i in range(50):
9483 res = dev.get_driver_status_field("scan_state")
9484 if "SCAN_STARTED" not in res and "SCAN_REQUESTED" not in res:
9485 break
9486 logger.debug("Waiting for scan to complete")
9487 time.sleep(0.1)
9488
9489 @remote_compatible
9490 def test_ap_wps_eap_wsc_errors(dev, apdev):
9491 """WPS and EAP-WSC error cases"""
9492 ssid = "test-wps-conf-pin"
9493 appin = "12345670"
9494 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9495 "wpa_passphrase": "12345678", "wpa": "2",
9496 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9497 "fragment_size": "300", "ap_pin": appin}
9498 hapd = hostapd.add_ap(apdev[0], params)
9499 bssid = apdev[0]['bssid']
9500
9501 pin = dev[0].wps_read_pin()
9502 hapd.request("WPS_PIN any " + pin)
9503 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9504 dev[0].dump_monitor()
9505
9506 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK", "CCMP",
9507 "new passphrase", no_wait=True)
9508 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9509 if ev is None:
9510 raise Exception("WPS-FAIL not reported")
9511 dev[0].request("WPS_CANCEL")
9512 dev[0].wait_disconnected()
9513 wait_scan_stopped(dev[0])
9514 dev[0].dump_monitor()
9515
9516 dev[0].wps_reg(bssid, appin, "new ssid", "FOO", "CCMP",
9517 "new passphrase", no_wait=True)
9518 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9519 if ev is None:
9520 raise Exception("WPS-FAIL not reported")
9521 dev[0].request("WPS_CANCEL")
9522 dev[0].wait_disconnected()
9523 wait_scan_stopped(dev[0])
9524 dev[0].dump_monitor()
9525
9526 dev[0].wps_reg(bssid, appin, "new ssid", "WPA2PSK", "FOO",
9527 "new passphrase", no_wait=True)
9528 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9529 if ev is None:
9530 raise Exception("WPS-FAIL not reported")
9531 dev[0].request("WPS_CANCEL")
9532 dev[0].wait_disconnected()
9533 wait_scan_stopped(dev[0])
9534 dev[0].dump_monitor()
9535
9536 dev[0].wps_reg(bssid, appin + "new_key=a", "new ssid", "WPA2PSK", "CCMP",
9537 "new passphrase", no_wait=True)
9538 ev = dev[0].wait_event(["WPS-FAIL"], timeout=10)
9539 if ev is None:
9540 raise Exception("WPS-FAIL not reported")
9541 dev[0].request("WPS_CANCEL")
9542 dev[0].wait_disconnected()
9543 wait_scan_stopped(dev[0])
9544 dev[0].dump_monitor()
9545
9546 tests = ["eap_wsc_init",
9547 "eap_msg_alloc;eap_wsc_build_msg",
9548 "wpabuf_alloc;eap_wsc_process_fragment"]
9549 for func in tests:
9550 with alloc_fail(dev[0], 1, func):
9551 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9552 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9553 dev[0].request("WPS_CANCEL")
9554 dev[0].wait_disconnected()
9555 wait_scan_stopped(dev[0])
9556 dev[0].dump_monitor()
9557
9558 tests = [(1, "wps_decrypt_encr_settings"),
9559 (2, "hmac_sha256;wps_derive_psk")]
9560 for count, func in tests:
9561 hapd.request("WPS_PIN any " + pin)
9562 with fail_test(dev[0], count, func):
9563 dev[0].request("WPS_PIN %s %s" % (bssid, pin))
9564 wait_fail_trigger(dev[0], "GET_FAIL")
9565 dev[0].request("WPS_CANCEL")
9566 dev[0].wait_disconnected()
9567 wait_scan_stopped(dev[0])
9568 dev[0].dump_monitor()
9569
9570 with alloc_fail(dev[0], 1, "eap_msg_alloc;eap_sm_build_expanded_nak"):
9571 dev[0].wps_reg(bssid, appin + " new_ssid=a", "new ssid", "WPA2PSK",
9572 "CCMP", "new passphrase", no_wait=True)
9573 wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
9574 dev[0].request("WPS_CANCEL")
9575 dev[0].wait_disconnected()
9576 wait_scan_stopped(dev[0])
9577 dev[0].dump_monitor()
9578
9579 def test_ap_wps_eap_wsc(dev, apdev):
9580 """WPS and EAP-WSC in network profile"""
9581 params = int_eap_server_params()
9582 params["wps_state"] = "2"
9583 hapd = hostapd.add_ap(apdev[0], params)
9584 bssid = apdev[0]['bssid']
9585
9586 logger.info("Unexpected identity")
9587 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9588 eap="WSC", identity="WFA-SimpleConfig-Enrollee-unexpected",
9589 wait_connect=False)
9590 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9591 if ev is None:
9592 raise Exception("No EAP-Failure seen")
9593 dev[0].request("REMOVE_NETWORK all")
9594 dev[0].wait_disconnected()
9595
9596 logger.info("No phase1 parameter")
9597 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9598 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9599 wait_connect=False)
9600 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9601 if ev is None:
9602 raise Exception("Timeout on EAP method start")
9603 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9604 if ev is None:
9605 raise Exception("No EAP-Failure seen")
9606 dev[0].request("REMOVE_NETWORK all")
9607 dev[0].wait_disconnected()
9608
9609 logger.info("No PIN/PBC in phase1")
9610 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9611 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9612 phase1="foo", wait_connect=False)
9613 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9614 if ev is None:
9615 raise Exception("Timeout on EAP method start")
9616 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9617 if ev is None:
9618 raise Exception("No EAP-Failure seen")
9619 dev[0].request("REMOVE_NETWORK all")
9620 dev[0].wait_disconnected()
9621
9622 logger.info("Invalid pkhash in phase1")
9623 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9624 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9625 phase1="foo pkhash=q pbc=1", wait_connect=False)
9626 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9627 if ev is None:
9628 raise Exception("Timeout on EAP method start")
9629 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9630 if ev is None:
9631 raise Exception("No EAP-Failure seen")
9632 dev[0].request("REMOVE_NETWORK all")
9633 dev[0].wait_disconnected()
9634
9635 logger.info("Zero fragment_size")
9636 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9637 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9638 fragment_size="0", phase1="pin=12345670", wait_connect=False)
9639 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9640 if ev is None:
9641 raise Exception("Timeout on EAP method start")
9642 ev = dev[0].wait_event(["WPS-M2D"], timeout=5)
9643 if ev is None:
9644 raise Exception("No M2D seen")
9645 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9646 if ev is None:
9647 raise Exception("No EAP-Failure seen")
9648 dev[0].request("REMOVE_NETWORK all")
9649 dev[0].wait_disconnected()
9650
9651 logger.info("Missing new_auth")
9652 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9653 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9654 phase1="pin=12345670 new_ssid=aa", wait_connect=False)
9655 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9656 if ev is None:
9657 raise Exception("Timeout on EAP method start")
9658 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9659 if ev is None:
9660 raise Exception("No EAP-Failure seen")
9661 dev[0].request("REMOVE_NETWORK all")
9662 dev[0].wait_disconnected()
9663
9664 logger.info("Missing new_encr")
9665 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9666 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9667 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa", wait_connect=False)
9668 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9669 if ev is None:
9670 raise Exception("Timeout on EAP method start")
9671 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9672 if ev is None:
9673 raise Exception("No EAP-Failure seen")
9674 dev[0].request("REMOVE_NETWORK all")
9675 dev[0].wait_disconnected()
9676
9677 logger.info("Missing new_key")
9678 dev[0].connect("test-wpa2-eap", key_mgmt="WPA-EAP", scan_freq="2412",
9679 eap="WSC", identity="WFA-SimpleConfig-Enrollee-1-0",
9680 phase1="pin=12345670 new_auth=WPA2PSK new_ssid=aa new_encr=CCMP",
9681 wait_connect=False)
9682 ev = dev[0].wait_event(["CTRL-EVENT-EAP-PROPOSED-METHOD"], timeout=5)
9683 if ev is None:
9684 raise Exception("Timeout on EAP method start")
9685 ev = dev[0].wait_event(["CTRL-EVENT-EAP-FAILURE"], timeout=5)
9686 if ev is None:
9687 raise Exception("No EAP-Failure seen")
9688 dev[0].request("REMOVE_NETWORK all")
9689 dev[0].wait_disconnected()
9690
9691 def test_ap_wps_and_bss_limit(dev, apdev):
9692 """WPS and wpa_supplicant BSS entry limit"""
9693 try:
9694 _test_ap_wps_and_bss_limit(dev, apdev)
9695 finally:
9696 dev[0].request("SET bss_max_count 200")
9697 pass
9698
9699 def _test_ap_wps_and_bss_limit(dev, apdev):
9700 params = {"ssid": "test-wps", "eap_server": "1", "wps_state": "2",
9701 "wpa_passphrase": "12345678", "wpa": "2",
9702 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
9703 hapd = hostapd.add_ap(apdev[0], params)
9704
9705 params = {"ssid": "test-wps-2", "eap_server": "1", "wps_state": "2",
9706 "wpa_passphrase": "1234567890", "wpa": "2",
9707 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"}
9708 hapd2 = hostapd.add_ap(apdev[1], params)
9709
9710 id = dev[1].add_network()
9711 dev[1].set_network(id, "mode", "2")
9712 dev[1].set_network_quoted(id, "ssid", "wpas-ap-no-wps")
9713 dev[1].set_network_quoted(id, "psk", "12345678")
9714 dev[1].set_network(id, "frequency", "2462")
9715 dev[1].set_network(id, "scan_freq", "2462")
9716 dev[1].set_network(id, "wps_disabled", "1")
9717 dev[1].select_network(id)
9718
9719 id = dev[2].add_network()
9720 dev[2].set_network(id, "mode", "2")
9721 dev[2].set_network_quoted(id, "ssid", "wpas-ap")
9722 dev[2].set_network_quoted(id, "psk", "12345678")
9723 dev[2].set_network(id, "frequency", "2437")
9724 dev[2].set_network(id, "scan_freq", "2437")
9725 dev[2].select_network(id)
9726
9727 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9728 wpas.interface_add("wlan5")
9729 id = wpas.add_network()
9730 wpas.set_network(id, "mode", "2")
9731 wpas.set_network_quoted(id, "ssid", "wpas-ap")
9732 wpas.set_network_quoted(id, "psk", "12345678")
9733 wpas.set_network(id, "frequency", "2437")
9734 wpas.set_network(id, "scan_freq", "2437")
9735 wpas.select_network(id)
9736
9737 dev[1].wait_connected()
9738 dev[2].wait_connected()
9739 wpas.wait_connected()
9740 wpas.request("WPS_PIN any 12345670")
9741
9742 hapd.request("WPS_PBC")
9743 hapd2.request("WPS_PBC")
9744
9745 dev[0].request("SET bss_max_count 1")
9746
9747 id = dev[0].add_network()
9748 dev[0].set_network_quoted(id, "ssid", "testing")
9749
9750 id = dev[0].add_network()
9751 dev[0].set_network_quoted(id, "ssid", "testing")
9752 dev[0].set_network(id, "key_mgmt", "WPS")
9753
9754 dev[0].request("WPS_PBC")
9755 ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], timeout=10)
9756 dev[0].request("WPS_CANCEL")
9757
9758 id = dev[0].add_network()
9759 dev[0].set_network_quoted(id, "ssid", "testing")
9760 dev[0].set_network(id, "key_mgmt", "WPS")
9761
9762 dev[0].scan(freq="2412")
9763
9764 def test_ap_wps_pbc_2ap(dev, apdev):
9765 """WPS PBC with two APs advertising same SSID"""
9766 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9767 "wpa_passphrase": "12345678", "wpa": "2",
9768 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9769 "wps_independent": "1"}
9770 hapd = hostapd.add_ap(apdev[0], params)
9771 params = {"ssid": "wps", "eap_server": "1", "wps_state": "2",
9772 "wpa_passphrase": "123456789", "wpa": "2",
9773 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9774 "wps_independent": "1"}
9775 hapd2 = hostapd.add_ap(apdev[1], params)
9776 hapd.request("WPS_PBC")
9777
9778 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
9779 wpas.interface_add("wlan5", drv_params="force_connect_cmd=1")
9780 wpas.dump_monitor()
9781 wpas.flush_scan_cache()
9782
9783 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
9784 wpas.scan_for_bss(apdev[1]['bssid'], freq="2412")
9785 wpas.request("WPS_PBC")
9786 wpas.wait_connected()
9787 wpas.request("DISCONNECT")
9788 hapd.request("DISABLE")
9789 hapd2.request("DISABLE")
9790 wpas.flush_scan_cache()
9791
9792 def test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9793 """WPS ER enrolling a new device to a configured AP"""
9794 try:
9795 _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev)
9796 finally:
9797 dev[0].request("WPS_ER_STOP")
9798
9799 def _test_ap_wps_er_enrollee_to_conf_ap(dev, apdev):
9800 ssid = "wps-er-enrollee-to-conf-ap"
9801 ap_pin = "12345670"
9802 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9803 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9804 "wpa_passphrase": "12345678", "wpa": "2",
9805 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9806 "device_name": "Wireless AP", "manufacturer": "Company",
9807 "model_name": "WAP", "model_number": "123",
9808 "serial_number": "12345", "device_type": "6-0050F204-1",
9809 "os_version": "01020300",
9810 "config_methods": "label push_button",
9811 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9812 hapd = hostapd.add_ap(apdev[0], params)
9813 bssid = hapd.own_addr()
9814
9815 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9816 dev[0].dump_monitor()
9817
9818 dev[0].request("WPS_ER_START ifname=lo")
9819 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9820 if ev is None:
9821 raise Exception("AP discovery timed out")
9822 if ap_uuid not in ev:
9823 raise Exception("Expected AP UUID not found")
9824
9825 pin = dev[2].wps_read_pin()
9826 addr2 = dev[2].own_addr()
9827 dev[0].dump_monitor()
9828 dev[2].scan_for_bss(bssid, freq=2412)
9829 dev[2].dump_monitor()
9830 dev[2].request("WPS_PIN %s %s" % (bssid, pin))
9831
9832 for i in range(3):
9833 ev = dev[0].wait_event(["WPS-ER-ENROLLEE-ADD"], timeout=10)
9834 if ev is None:
9835 raise Exception("Enrollee not seen")
9836 if addr2 in ev:
9837 break
9838 if addr2 not in ev:
9839 raise Exception("Unexpected Enrollee MAC address")
9840 dev[0].dump_monitor()
9841
9842 dev[0].request("WPS_ER_SET_CONFIG " + ap_uuid + " " + str(id))
9843 dev[0].request("WPS_ER_PIN " + addr2 + " " + pin + " " + addr2)
9844 dev[2].wait_connected(timeout=30)
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_er_enrollee_to_conf_ap2(dev, apdev):
9850 """WPS ER enrolling a new device to a configured AP (2)"""
9851 try:
9852 _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev)
9853 finally:
9854 dev[0].request("WPS_ER_STOP")
9855
9856 def _test_ap_wps_er_enrollee_to_conf_ap2(dev, apdev):
9857 ssid = "wps-er-enrollee-to-conf-ap"
9858 ap_pin = "12345670"
9859 ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
9860 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9861 "wpa_passphrase": "12345678", "wpa": "2",
9862 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9863 "device_name": "Wireless AP", "manufacturer": "Company",
9864 "model_name": "WAP", "model_number": "123",
9865 "serial_number": "12345", "device_type": "6-0050F204-1",
9866 "os_version": "01020300",
9867 "config_methods": "label push_button",
9868 "ap_pin": ap_pin, "uuid": ap_uuid, "upnp_iface": "lo"}
9869 hapd = hostapd.add_ap(apdev[0], params)
9870 bssid = hapd.own_addr()
9871
9872 id = dev[0].connect(ssid, psk="12345678", scan_freq="2412")
9873 dev[0].dump_monitor()
9874
9875 dev[0].request("WPS_ER_START ifname=lo")
9876 ev = dev[0].wait_event(["WPS-ER-AP-ADD"], timeout=15)
9877 if ev is None:
9878 raise Exception("AP discovery timed out")
9879 if ap_uuid not in ev:
9880 raise Exception("Expected AP UUID not found")
9881
9882 dev[0].request("WPS_ER_LEARN " + ap_uuid + " " + ap_pin)
9883 ev = dev[0].wait_event(["WPS-ER-AP-SETTINGS"], timeout=15)
9884 if ev is None:
9885 raise Exception("AP learn timed out")
9886 if ap_uuid not in ev:
9887 raise Exception("Expected AP UUID not in settings")
9888 ev = dev[0].wait_event(["WPS-FAIL"], timeout=15)
9889 if ev is None:
9890 raise Exception("WPS-FAIL after AP learn timed out")
9891 time.sleep(0.1)
9892
9893 pin = dev[1].wps_read_pin()
9894 addr1 = dev[1].own_addr()
9895 dev[0].dump_monitor()
9896 dev[0].request("WPS_ER_PIN any " + pin)
9897 time.sleep(0.1)
9898 dev[1].scan_for_bss(bssid, freq=2412)
9899 dev[1].request("WPS_PIN any %s" % pin)
9900 ev = dev[1].wait_event(["WPS-SUCCESS"], timeout=30)
9901 if ev is None:
9902 raise Exception("Enrollee did not report success")
9903 dev[1].wait_connected(timeout=15)
9904 ev = dev[0].wait_event(["WPS-SUCCESS"], timeout=15)
9905 if ev is None:
9906 raise Exception("WPS ER did not report success")
9907
9908 def test_ap_wps_ignore_broadcast_ssid(dev, apdev):
9909 """WPS AP trying to ignore broadcast SSID"""
9910 ssid = "test-wps"
9911 hapd = hostapd.add_ap(apdev[0],
9912 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9913 "ignore_broadcast_ssid": "1"})
9914 if "FAIL" not in hapd.request("WPS_PBC"):
9915 raise Exception("WPS unexpectedly enabled")
9916
9917 def test_ap_wps_wep(dev, apdev):
9918 """WPS AP trying to enable WEP"""
9919 ssid = "test-wps"
9920 hapd = hostapd.add_ap(apdev[0],
9921 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9922 "ieee80211n": "0", "wep_key0": '"hello"'})
9923 if "FAIL" not in hapd.request("WPS_PBC"):
9924 raise Exception("WPS unexpectedly enabled")
9925
9926 def test_ap_wps_tkip(dev, apdev):
9927 """WPS AP trying to enable TKIP"""
9928 ssid = "test-wps"
9929 hapd = hostapd.add_ap(apdev[0],
9930 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
9931 "ieee80211n": "0", "wpa": '1',
9932 "wpa_key_mgmt": "WPA-PSK",
9933 "wpa_passphrase": "12345678"})
9934 if "FAIL" not in hapd.request("WPS_PBC"):
9935 raise Exception("WPS unexpectedly enabled")
9936
9937 def test_ap_wps_conf_dummy_cred(dev, apdev):
9938 """WPS PIN provisioning with configured AP using dummy cred"""
9939 ssid = "test-wps-conf"
9940 hapd = hostapd.add_ap(apdev[0],
9941 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9942 "wpa_passphrase": "12345678", "wpa": "2",
9943 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
9944 hapd.request("WPS_PIN any 12345670")
9945 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
9946 dev[0].dump_monitor()
9947 try:
9948 hapd.set("wps_testing_dummy_cred", "1")
9949 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " 12345670")
9950 for i in range(1, 3):
9951 ev = dev[0].wait_event(["WPS-CRED-RECEIVED"], timeout=15)
9952 if ev is None:
9953 raise Exception("WPS credential %d not received" % i)
9954 dev[0].wait_connected(timeout=30)
9955 finally:
9956 hapd.set("wps_testing_dummy_cred", "0")
9957
9958 def test_ap_wps_rf_bands(dev, apdev):
9959 """WPS and wps_rf_bands configuration"""
9960 ssid = "test-wps-conf"
9961 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9962 "wpa_passphrase": "12345678", "wpa": "2",
9963 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9964 "wps_rf_bands": "ag"}
9965
9966 hapd = hostapd.add_ap(apdev[0], params)
9967 bssid = hapd.own_addr()
9968 hapd.request("WPS_PBC")
9969 dev[0].scan_for_bss(bssid, freq="2412")
9970 dev[0].dump_monitor()
9971 dev[0].request("WPS_PBC " + bssid)
9972 dev[0].wait_connected(timeout=30)
9973 bss = dev[0].get_bss(bssid)
9974 logger.info("BSS: " + str(bss))
9975 if "103c000103" not in bss['ie']:
9976 raise Exception("RF Bands attribute with expected values not found")
9977 dev[0].request("DISCONNECT")
9978 dev[0].wait_disconnected()
9979 hapd.set("wps_rf_bands", "ad")
9980 hapd.set("wps_rf_bands", "a")
9981 hapd.set("wps_rf_bands", "g")
9982 hapd.set("wps_rf_bands", "b")
9983 hapd.set("wps_rf_bands", "ga")
9984 hapd.disable()
9985 dev[0].dump_monitor()
9986 dev[0].flush_scan_cache()
9987
9988 def test_ap_wps_pbc_in_m1(dev, apdev):
9989 """WPS and pbc_in_m1"""
9990 ssid = "test-wps-conf"
9991 params = {"ssid": ssid, "eap_server": "1", "wps_state": "2",
9992 "wpa_passphrase": "12345678", "wpa": "2",
9993 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
9994 "config_methods": "virtual_push_button virtual_display",
9995 "pbc_in_m1": "1"}
9996
9997 hapd = hostapd.add_ap(apdev[0], params)
9998 bssid = hapd.own_addr()
9999 hapd.request("WPS_PBC")
10000 dev[0].scan_for_bss(bssid, freq="2412")
10001 dev[0].dump_monitor()
10002 dev[0].request("WPS_PBC " + bssid)
10003 dev[0].wait_connected(timeout=30)
10004 dev[0].request("DISCONNECT")
10005 dev[0].wait_disconnected()
10006 hapd.disable()
10007 dev[0].dump_monitor()
10008 dev[0].flush_scan_cache()
10009
10010 def test_ap_wps_pbc_mac_addr_change(dev, apdev, params):
10011 """WPS M1 with MAC address change"""
10012 ssid = "test-wps-mac-addr-change"
10013 hapd = hostapd.add_ap(apdev[0],
10014 {"ssid": ssid, "eap_server": "1", "wps_state": "1"})
10015 hapd.request("WPS_PBC")
10016 if "PBC Status: Active" not in hapd.request("WPS_GET_STATUS"):
10017 raise Exception("PBC status not shown correctly")
10018 dev[0].flush_scan_cache()
10019
10020 test_addr = '02:11:22:33:44:55'
10021 addr = dev[0].get_status_field("address")
10022 if addr == test_addr:
10023 raise Exception("Unexpected initial MAC address")
10024
10025 try:
10026 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
10027 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
10028 test_addr])
10029 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
10030 addr1 = dev[0].get_status_field("address")
10031 if addr1 != test_addr:
10032 raise Exception("Failed to change MAC address")
10033
10034 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10035 dev[0].request("WPS_PBC " + apdev[0]['bssid'])
10036 dev[0].wait_connected(timeout=30)
10037 status = dev[0].get_status()
10038 if status['wpa_state'] != 'COMPLETED' or \
10039 status['bssid'] != apdev[0]['bssid']:
10040 raise Exception("Not fully connected")
10041
10042 out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
10043 "wps.message_type == 0x04",
10044 display=["wps.mac_address"])
10045 res = out.splitlines()
10046
10047 if len(res) < 1:
10048 raise Exception("No M1 message with MAC address found")
10049 if res[0] != addr1:
10050 raise Exception("Wrong M1 MAC address")
10051 dev[0].request("DISCONNECT")
10052 dev[0].wait_disconnected()
10053 hapd.disable()
10054 dev[0].dump_monitor()
10055 dev[0].flush_scan_cache()
10056 finally:
10057 # Restore MAC address
10058 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'down'])
10059 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'address',
10060 addr])
10061 subprocess.call(['ip', 'link', 'set', 'dev', dev[0].ifname, 'up'])
10062
10063 def test_ap_wps_pin_start_failure(dev, apdev):
10064 """WPS_PIN start failure"""
10065 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
10066 if "FAIL" not in dev[0].request("WPS_PIN any 12345670"):
10067 raise Exception("WPS_PIN not rejected during OOM")
10068 with alloc_fail(dev[0], 1, "wpas_wps_start_dev_pw"):
10069 if "FAIL" not in dev[0].request("WPS_PIN any"):
10070 raise Exception("WPS_PIN not rejected during OOM")
10071
10072 def test_ap_wps_ap_pin_failure(dev, apdev):
10073 """WPS_AP_PIN failure"""
10074 id = dev[0].add_network()
10075 dev[0].set_network(id, "mode", "2")
10076 dev[0].set_network_quoted(id, "ssid", "wpas-ap-wps")
10077 dev[0].set_network_quoted(id, "psk", "1234567890")
10078 dev[0].set_network(id, "frequency", "2412")
10079 dev[0].set_network(id, "scan_freq", "2412")
10080 dev[0].select_network(id)
10081 dev[0].wait_connected()
10082
10083 with fail_test(dev[0], 1,
10084 "os_get_random;wpa_supplicant_ctrl_iface_wps_ap_pin"):
10085 if "FAIL" not in dev[0].request("WPS_AP_PIN random"):
10086 raise Exception("WPS_AP_PIN random accepted")
10087 with alloc_fail(dev[0], 1, "wpas_wps_ap_pin_set"):
10088 if "FAIL" not in dev[0].request("WPS_AP_PIN set 12345670"):
10089 raise Exception("WPS_AP_PIN set accepted")
10090
10091 dev[0].request("DISCONNECT")
10092 dev[0].wait_disconnected()
10093
10094 def test_ap_wps_random_uuid(dev, apdev, params):
10095 """WPS and random UUID on Enrollee"""
10096 ssid = "test-wps-conf"
10097 hapd = hostapd.add_ap(apdev[0],
10098 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10099 "wpa_passphrase": "12345678", "wpa": "2",
10100 "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP"})
10101
10102 config = os.path.join(params['logdir'], 'ap_wps_random_uuid.conf')
10103 with open(config, "w") as f:
10104 f.write("auto_uuid=1\n")
10105
10106 wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
10107
10108 uuid = []
10109 for i in range(3):
10110 wpas.interface_add("wlan5", config=config)
10111
10112 wpas.scan_for_bss(apdev[0]['bssid'], freq="2412")
10113 wpas.dump_monitor()
10114 wpas.request("WPS_PBC " + apdev[0]['bssid'])
10115
10116 ev = hapd.wait_event(["WPS-ENROLLEE-SEEN"], timeout=10)
10117 if ev is None:
10118 raise Exception("Enrollee not seen")
10119 uuid.append(ev.split(' ')[2])
10120 wpas.request("WPS_CANCEL")
10121 wpas.dump_monitor()
10122
10123 wpas.interface_remove("wlan5")
10124
10125 hapd.dump_monitor()
10126
10127 logger.info("Seen UUIDs: " + str(uuid))
10128 if uuid[0] == uuid[1] or uuid[0] == uuid[2] or uuid[1] == uuid[2]:
10129 raise Exception("Same UUID used multiple times")
10130
10131 def test_ap_wps_conf_pin_gcmp_128(dev, apdev):
10132 """WPS PIN provisioning with configured AP using GCMP-128"""
10133 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP")
10134
10135 def test_ap_wps_conf_pin_gcmp_256(dev, apdev):
10136 """WPS PIN provisioning with configured AP using GCMP-256"""
10137 run_ap_wps_conf_pin_cipher(dev, apdev, "GCMP-256")
10138
10139 def test_ap_wps_conf_pin_ccmp_256(dev, apdev):
10140 """WPS PIN provisioning with configured AP using CCMP-256"""
10141 run_ap_wps_conf_pin_cipher(dev, apdev, "CCMP-256")
10142
10143 def run_ap_wps_conf_pin_cipher(dev, apdev, cipher):
10144 if cipher not in dev[0].get_capability("pairwise"):
10145 raise HwsimSkip("Cipher %s not supported" % cipher)
10146 ssid = "test-wps-conf-pin"
10147 hapd = hostapd.add_ap(apdev[0],
10148 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10149 "wpa_passphrase": "12345678", "wpa": "2",
10150 "wpa_key_mgmt": "WPA-PSK",
10151 "rsn_pairwise": cipher})
10152 logger.info("WPS provisioning step")
10153 pin = dev[0].wps_read_pin()
10154 hapd.request("WPS_PIN any " + pin)
10155 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10156 dev[0].request("WPS_PIN %s %s" % (apdev[0]['bssid'], pin))
10157 dev[0].wait_connected(timeout=15)
10158
10159 def test_ap_wps_and_sae(dev, apdev):
10160 """Initial AP configuration with first WPS Enrollee and adding SAE"""
10161 try:
10162 run_ap_wps_and_sae(dev, apdev)
10163 finally:
10164 dev[0].set("wps_cred_add_sae", "0")
10165
10166 def run_ap_wps_and_sae(dev, apdev):
10167 ssid = "test-wps-sae"
10168 hapd = hostapd.add_ap(apdev[0],
10169 {"ssid": ssid, "eap_server": "1", "wps_state": "1",
10170 "wps_cred_add_sae": "1"})
10171 logger.info("WPS provisioning step")
10172 pin = dev[0].wps_read_pin()
10173 hapd.request("WPS_PIN any " + pin)
10174
10175 dev[0].set("wps_cred_add_sae", "1")
10176 dev[0].request("SET sae_groups ")
10177 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10178 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10179 dev[0].wait_connected(timeout=30)
10180 status = dev[0].get_status()
10181 if status['key_mgmt'] != "SAE":
10182 raise Exception("SAE not used")
10183 if 'pmf' not in status or status['pmf'] != "1":
10184 raise Exception("PMF not enabled")
10185
10186 pin = dev[1].wps_read_pin()
10187 hapd.request("WPS_PIN any " + pin)
10188 dev[1].scan_for_bss(apdev[0]['bssid'], freq="2412", force_scan=True)
10189 dev[1].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10190 dev[1].wait_connected(timeout=30)
10191 status = dev[1].get_status()
10192 if status['key_mgmt'] != "WPA2-PSK":
10193 raise Exception("WPA2-PSK not used")
10194 if 'pmf' in status:
10195 raise Exception("PMF enabled")
10196
10197 def test_ap_wps_conf_and_sae(dev, apdev):
10198 """WPS PBC provisioning with configured AP using PSK+SAE"""
10199 try:
10200 run_ap_wps_conf_and_sae(dev, apdev)
10201 finally:
10202 dev[0].set("wps_cred_add_sae", "0")
10203
10204 def run_ap_wps_conf_and_sae(dev, apdev):
10205 ssid = "test-wps-conf-sae"
10206 hapd = hostapd.add_ap(apdev[0],
10207 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10208 "wpa_passphrase": "12345678", "wpa": "2",
10209 "ieee80211w": "1", "sae_require_mfp": "1",
10210 "wpa_key_mgmt": "WPA-PSK SAE",
10211 "rsn_pairwise": "CCMP"})
10212
10213 dev[0].set("wps_cred_add_sae", "1")
10214 dev[0].request("SET sae_groups ")
10215 dev[0].scan_for_bss(apdev[0]['bssid'], freq="2412")
10216 pin = dev[0].wps_read_pin()
10217 hapd.request("WPS_PIN any " + pin)
10218 dev[0].request("WPS_PIN " + apdev[0]['bssid'] + " " + pin)
10219 dev[0].wait_connected(timeout=30)
10220 status = dev[0].get_status()
10221 if status['key_mgmt'] != "SAE":
10222 raise Exception("SAE not used")
10223 if 'pmf' not in status or status['pmf'] != "1":
10224 raise Exception("PMF not enabled")
10225
10226 dev[1].connect(ssid, psk="12345678", scan_freq="2412", proto="WPA2",
10227 key_mgmt="WPA-PSK", ieee80211w="0")
10228
10229 def test_ap_wps_reg_config_and_sae(dev, apdev):
10230 """WPS registrar configuring an AP using AP PIN and using PSK+SAE"""
10231 try:
10232 run_ap_wps_reg_config_and_sae(dev, apdev)
10233 finally:
10234 dev[0].set("wps_cred_add_sae", "0")
10235
10236 def run_ap_wps_reg_config_and_sae(dev, apdev):
10237 ssid = "test-wps-init-ap-pin-sae"
10238 appin = "12345670"
10239 hostapd.add_ap(apdev[0],
10240 {"ssid": ssid, "eap_server": "1", "wps_state": "2",
10241 "ap_pin": appin, "wps_cred_add_sae": "1"})
10242 logger.info("WPS configuration step")
10243 dev[0].flush_scan_cache()
10244 dev[0].set("wps_cred_add_sae", "1")
10245 dev[0].request("SET sae_groups ")
10246 dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412)
10247 dev[0].dump_monitor()
10248 new_ssid = "wps-new-ssid"
10249 new_passphrase = "1234567890"
10250 dev[0].wps_reg(apdev[0]['bssid'], appin, new_ssid, "WPA2PSK", "CCMP",
10251 new_passphrase)
10252 status = dev[0].get_status()
10253 if status['key_mgmt'] != "SAE":
10254 raise Exception("SAE not used")
10255 if 'pmf' not in status or status['pmf'] != "1":
10256 raise Exception("PMF not enabled")
10257
10258 dev[1].connect(new_ssid, psk=new_passphrase, scan_freq="2412", proto="WPA2",
10259 key_mgmt="WPA-PSK", ieee80211w="0")